From 70a632a085788a35cc2139d81dfb9300b33db2fe Mon Sep 17 00:00:00 2001 From: Bobby Lat Date: Fri, 12 Jul 2024 17:27:15 +0800 Subject: [PATCH] add tests for Box implmentation --- src/algopy_testing/box.py | 2 +- tests/test_box.py | 76 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 77 insertions(+), 1 deletion(-) create mode 100644 tests/test_box.py diff --git a/src/algopy_testing/box.py b/src/algopy_testing/box.py index 422a87e..3870c06 100644 --- a/src/algopy_testing/box.py +++ b/src/algopy_testing/box.py @@ -29,7 +29,7 @@ def __init__( self._type = type_ # if key parameter is empty string, generate a random 32 bytes for key - if isinstance(key, str) and key == "": + if not bool(key): self._key = algopy.Bytes(secrets.token_bytes(32)) else: self._key = ( diff --git a/tests/test_box.py b/tests/test_box.py new file mode 100644 index 0000000..e61a69d --- /dev/null +++ b/tests/test_box.py @@ -0,0 +1,76 @@ +from collections.abc import Generator + +import pytest +from algopy_testing import arc4 +from algopy_testing.box import Box +from algopy_testing.context import AlgopyTestContext, algopy_testing_context +from algopy_testing.primitives.biguint import BigUInt +from algopy_testing.primitives.bytes import Bytes +from algopy_testing.primitives.string import String +from algopy_testing.primitives.uint64 import UInt64 +from algopy_testing.utils import as_bytes, as_string + + +@pytest.fixture() +def context() -> Generator[AlgopyTestContext, None, None]: + with algopy_testing_context() as ctx: + yield ctx + ctx.reset() + + +@pytest.mark.parametrize( + ("value_type", "key"), + [ + (UInt64, ""), + (Bytes, b""), + (String, Bytes()), + (BigUInt, String()), + (arc4.String, ""), + (arc4.DynamicArray, b""), + ], +) +def test_box_init_without_key( + context: AlgopyTestContext, + value_type: type, + key: bytes | str | Bytes | String, +) -> None: + box = Box(value_type, key=key) + assert not bool(box) + assert len(box.key) > 0 + with pytest.raises(ValueError, match="Box has not been created"): + _ = box.value + + with pytest.raises(ValueError, match="Box has not been created"): + _ = box.length + + +@pytest.mark.parametrize( + ("value_type", "key"), + [ + (UInt64, "key"), + (Bytes, b"key"), + (String, Bytes(b"key")), + (BigUInt, String("key")), + (arc4.String, "Key"), + (arc4.DynamicArray, b"Key"), + ], +) +def test_box_init_with_key( + context: AlgopyTestContext, + value_type: type, + key: bytes | str | Bytes | String, +) -> None: + box = Box(value_type, key=key) + assert not bool(box) + assert len(box.key) > 0 + + key_bytes = ( + String(as_string(key)).bytes if isinstance(key, str | String) else Bytes(as_bytes(key)) + ) + assert box.key == key_bytes + + with pytest.raises(ValueError, match="Box has not been created"): + _ = box.value + + with pytest.raises(ValueError, match="Box has not been created"): + _ = box.length