From dc7cc3a19be999ba147ac7bb33dc2a5b6d16bf26 Mon Sep 17 00:00:00 2001 From: luc10921 Date: Wed, 19 Jun 2024 09:20:22 -0300 Subject: [PATCH] CU-86dtu91p0 - Include how to test smart contract storage using boa test constructor --- docs/source/testing-and-debugging.md | 34 ++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/docs/source/testing-and-debugging.md b/docs/source/testing-and-debugging.md index 4cb68c55..4973c6a6 100644 --- a/docs/source/testing-and-debugging.md +++ b/docs/source/testing-and-debugging.md @@ -135,3 +135,37 @@ of the transaction. result, _ = await self.call("get_message", return_type=str) self.assertEqual(new_message, result) ``` + +#### Accessing the Storage + +To get the key-value pairs stored in the smart contract's storage, you can use the `get_storage` method from +`SmartContractTestCase`. Use it with the prefix of the keys you want to access, and you'll get a `dict[bytes, bytes]`. +If you want to get a dictionary of other types, you can also pass a function as argument to process the keys or values +before adding it to the dict. If want to remove the prefix from the result you can use the `remove_prefix` parameter. + +```python + # inside the HelloWorldWithDeployTest class + async def test_smart_contract_storage(self): + from boaconstructor.storage import as_uint160, as_int + from typing import cast + + # this is the prefix that the GAS smart contract uses to store the accounts and their balances + account_prefix = b'\x14' + + # the return from get_storage needs to be casted to the expected type + accounts = cast( + dict[types.UInt160, int], + await self.get_storage( + account_prefix, target_contract=GAS, remove_prefix=True, + # we are using the methods from `boaconstructor.storage` to return keys as UInt160 and values as int + key_post_processor=as_uint160, values_post_processor=as_int + ) + ) + + self.assertIn(self.genesis.script_hash, accounts) + genesis_balance = accounts[self.genesis.script_hash] + self.assertGreater(genesis_balance, 0) + self.assertIn(self.user1.script_hash, accounts) + user1_balance = accounts[self.user1.script_hash] + self.assertGreater(user1_balance, 0) +```