code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def test_merge_configs(): """ The test covers most cases in `merge_config()`. See comment below explaining `expected`. """ global_config = { "ethereum": { "mainnet": {"default_provider": "node"}, "local": {"default_provider": "test", "required_confirmations": 5}, } } project_config = { "ethereum": { "local": {"default_provider": "node"}, "sepolia": {"default_provider": "alchemy"}, }, "test": "foo", } actual = merge_configs(global_config, project_config) # Expected case `key only in global`: "mainnet" # Expected case `non-primitive override from project`: local -> default_provider, which # is `test` in global but `geth` in project; thus it is `geth` in expected. # Expected case `merge sub-dictionaries`: `ethereum` is being merged. # Expected case `add missing project keys`: `test` is added, so is `sepolia` (nested-example). expected = { "ethereum": { "local": {"default_provider": "node", "required_confirmations": 5}, "mainnet": {"default_provider": "node"}, "sepolia": {"default_provider": "alchemy"}, }, "test": "foo", } assert actual == expected
The test covers most cases in `merge_config()`. See comment below explaining `expected`.
test_merge_configs
python
ApeWorX/ape
tests/functional/test_config.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_config.py
Apache-2.0
def test_contracts_folder_invalid(project): """ Show that we can still attempt to use `.get_config()` when config is invalid. """ with pytest.raises(ConfigError): with project.temp_config(**{"contracts_folder": {}}): _ = project.contracts_folder # Ensure config is fine _after_ something invalid. assert project.contracts_folder
Show that we can still attempt to use `.get_config()` when config is invalid.
test_contracts_folder_invalid
python
ApeWorX/ape
tests/functional/test_config.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_config.py
Apache-2.0
def test_get_config_hyphen_in_plugin_name(config): """ Tests against a bug noticed with ape-polygon-zkevm installed on Ape 0.8.0 release where the config no longer worked. """ class CustomConfig(PluginConfig): x: int = 123 mock_cfg_with_hyphens = CustomConfig original_method = config.local_project.config._get_config_plugin_classes # Hack in the fake plugin to test the behavior. def hacked_in_method(): yield from [*list(original_method()), ("mock-plugin", mock_cfg_with_hyphens)] config.local_project.config._get_config_plugin_classes = hacked_in_method try: cfg = config.get_config("mock-plugin") assert isinstance(cfg, CustomConfig) assert cfg.x == 123 finally: config.local_project.config._get_config_plugin_classes = original_method
Tests against a bug noticed with ape-polygon-zkevm installed on Ape 0.8.0 release where the config no longer worked.
test_get_config_hyphen_in_plugin_name
python
ApeWorX/ape
tests/functional/test_config.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_config.py
Apache-2.0
def test_get_config_unknown_plugin(config): """ Simulating reading plugin configs w/o those plugins installed. """ actual = config.get_config("thisshouldnotbeinstalled") assert isinstance(actual, PluginConfig)
Simulating reading plugin configs w/o those plugins installed.
test_get_config_unknown_plugin
python
ApeWorX/ape
tests/functional/test_config.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_config.py
Apache-2.0
def test_project_level_settings(project): """ Settings can be configured in an ape-config.yaml file that are not part of any plugin. This test ensures that works. """ # NOTE: Using strings for the values to show simple validation occurs. with project.temp_config(my_string="my_string", my_int=123, my_bool=True): assert project.config.my_string == "my_string" assert project.config.my_int == 123 assert project.config.my_bool is True
Settings can be configured in an ape-config.yaml file that are not part of any plugin. This test ensures that works.
test_project_level_settings
python
ApeWorX/ape
tests/functional/test_config.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_config.py
Apache-2.0
def test_console_extras_uses_ape_namespace(mocker, mock_console): """ Test that if console is given extras, those are included in the console but not as args to the extras files, as those files expect items from the default ape namespace. """ namespace_patch = mocker.patch("ape_console._cli._create_namespace") accounts_custom = mocker.MagicMock() extras = {"accounts": accounts_custom} console(extra_locals=extras) actual = namespace_patch.call_args[1] assert actual["accounts"] == accounts_custom
Test that if console is given extras, those are included in the console but not as args to the extras files, as those files expect items from the default ape namespace.
test_console_extras_uses_ape_namespace
python
ApeWorX/ape
tests/functional/test_console.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_console.py
Apache-2.0
def test_custom_exception_handler_handles_non_ape_project(mocker): """ If the user has assigned the variable ``project`` to something else in their active ``ape console`` session, the exception handler **SHOULD NOT** attempt to use its ``.path``. """ session = mocker.MagicMock() session.user_ns = {"project": 123} # Like doing `project = 123` in a console. err = Exception() handler_patch = mocker.patch("ape_console.plugin.handle_ape_exception") # Execute - this was failing before the fix. custom_exception_handler(session, None, err, None) # We are expecting the local project's path in the handler. expected_path = ManagerAccessMixin.local_project.path handler_patch.assert_called_once_with(err, [expected_path])
If the user has assigned the variable ``project`` to something else in their active ``ape console`` session, the exception handler **SHOULD NOT** attempt to use its ``.path``.
test_custom_exception_handler_handles_non_ape_project
python
ApeWorX/ape
tests/functional/test_console.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_console.py
Apache-2.0
def test_Contract_from_json_str_retrieval_check_fails(mocker, chain, vyper_contract_instance): """ Tests a bug when providing an abi= but fetch-attempt raises that we don't raise since the abi was already given. """ # Make `.get()` fail. orig = chain.contracts.get mock_get = mocker.MagicMock() mock_get.side_effect = Exception abi_str = json.dumps([abi.model_dump() for abi in vyper_contract_instance.contract_type.abi]) chain.contracts.get = mock_get try: contract = Contract(vyper_contract_instance.address, abi=abi_str) finally: chain.contracts.get = orig # Mostly, we are asserting it did not fail. assert isinstance(contract, ContractInstance)
Tests a bug when providing an abi= but fetch-attempt raises that we don't raise since the abi was already given.
test_Contract_from_json_str_retrieval_check_fails
python
ApeWorX/ape
tests/functional/test_contract.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_contract.py
Apache-2.0
def test_Contract_from_file(contract_instance): """ need feedback about the json file specifications """ PROJECT_PATH = Path(__file__).parent CONTRACTS_FOLDER = PROJECT_PATH / "data" / "contracts" / "ethereum" / "abi" json_abi_file = f"{CONTRACTS_FOLDER}/contract_abi.json" address = contract_instance.address contract = Contract(address, abi=json_abi_file) assert isinstance(contract, ContractInstance) assert contract.address == address assert contract.myNumber() == 0
need feedback about the json file specifications
test_Contract_from_file
python
ApeWorX/ape
tests/functional/test_contract.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_contract.py
Apache-2.0
def test_cache_non_checksum_address(chain, vyper_contract_instance): """ When caching a non-checksum address, it should use its checksum form automatically. """ if vyper_contract_instance.address in chain.contracts: del chain.contracts[vyper_contract_instance.address] lowered_address = vyper_contract_instance.address.lower() chain.contracts[lowered_address] = vyper_contract_instance.contract_type assert chain.contracts[vyper_contract_instance.address] == vyper_contract_instance.contract_type
When caching a non-checksum address, it should use its checksum form automatically.
test_cache_non_checksum_address
python
ApeWorX/ape
tests/functional/test_contracts_cache.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_contracts_cache.py
Apache-2.0
def test_get_proxy_implementation_missing(chain, owner, vyper_contract_container): """ Proxy is cached but implementation is missing. """ placeholder = vyper_contract_container.deploy(1001, sender=owner) assert chain.contracts[placeholder.address] # This must be cached! proxy_container = _make_minimal_proxy(placeholder.address) minimal_proxy = owner.deploy(proxy_container, sender=owner) chain.provider.network.__dict__["explorer"] = None # Ensure no explorer, messes up test. if minimal_proxy.address in chain.contracts: # Delete the proxy but make sure it does not delete the implementation! # (which it normally does here). del chain.contracts[minimal_proxy.address] chain.contracts[placeholder.address] = placeholder actual = chain.contracts.get(minimal_proxy.address) assert actual == minimal_proxy.contract_type
Proxy is cached but implementation is missing.
test_get_proxy_implementation_missing
python
ApeWorX/ape
tests/functional/test_contracts_cache.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_contracts_cache.py
Apache-2.0
def test_get_proxy_pass_proxy_info_and_no_explorer( chain, owner, proxy_contract_container, ethereum, dummy_live_network_with_explorer ): """ Tests the condition of both passing `proxy_info=` and setting `use_explorer=False` when getting the ContractType of a proxy. """ explorer = dummy_live_network_with_explorer.explorer placeholder = "0xBEbeBeBEbeBebeBeBEBEbebEBeBeBebeBeBebebe" if placeholder in chain.contracts: del chain.contracts[placeholder] proxy = proxy_contract_container.deploy(placeholder, sender=owner, required_confirmations=0) info = ProxyInfo(type=ProxyType.Minimal, target=placeholder) explorer.get_contract_type.reset_mock() chain.contracts.get(proxy.address, proxy_info=info, fetch_from_explorer=False) # Ensure explorer was not used. assert explorer.get_contract_type.call_count == 0
Tests the condition of both passing `proxy_info=` and setting `use_explorer=False` when getting the ContractType of a proxy.
test_get_proxy_pass_proxy_info_and_no_explorer
python
ApeWorX/ape
tests/functional/test_contracts_cache.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_contracts_cache.py
Apache-2.0
def test_deploy_no_deployment_bytecode(owner, bytecode): """ https://github.com/ApeWorX/ape/issues/1904 """ expected = ( r"Cannot deploy: contract 'Apes' has no deployment-bytecode\. " r"Are you attempting to deploy an interface\?" ) contract_type = ContractType.model_validate( {"abi": [], "contractName": "Apes", "deploymentBytecode": bytecode} ) contract = ContractContainer(contract_type) with pytest.raises(MissingDeploymentBytecodeError, match=expected): contract.deploy(sender=owner)
ERROR: type should be string, got "\n https://github.com/ApeWorX/ape/issues/1904\n "
test_deploy_no_deployment_bytecode
python
ApeWorX/ape
tests/functional/test_contract_container.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_contract_container.py
Apache-2.0
def test_contract_decode_logs_falsy_check(owner, vyper_contract_instance): """ Verifies a bug fix where false-y values differing were ignored. """ tx = vyper_contract_instance.setNumber(1, sender=owner) with pytest.raises(AssertionError): assert tx.events == [vyper_contract_instance.NumberChange(newNum=0)]
Verifies a bug fix where false-y values differing were ignored.
test_contract_decode_logs_falsy_check
python
ApeWorX/ape
tests/functional/test_contract_event.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_contract_event.py
Apache-2.0
def test_contract_call(vyper_contract_instance): """ By default, calls returndata gets decoded into Python types. """ result = vyper_contract_instance.myNumber() assert isinstance(result, int)
By default, calls returndata gets decoded into Python types.
test_contract_call
python
ApeWorX/ape
tests/functional/test_contract_instance.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_contract_instance.py
Apache-2.0
def test_contract_call_decode_false(vyper_contract_instance): """ Use decode=False to get the raw bytes returndata of a function call. """ result = vyper_contract_instance.myNumber(decode=False) assert not isinstance(result, int) assert isinstance(result, bytes)
Use decode=False to get the raw bytes returndata of a function call.
test_contract_call_decode_false
python
ApeWorX/ape
tests/functional/test_contract_instance.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_contract_instance.py
Apache-2.0
def test_transact_specify_auto_gas(vyper_contract_instance, owner): """ Tests that we can specify "auto" gas even though "max" is the default for local networks. """ receipt = vyper_contract_instance.setNumber(111, sender=owner, gas="auto") assert not receipt.failed
Tests that we can specify "auto" gas even though "max" is the default for local networks.
test_transact_specify_auto_gas
python
ApeWorX/ape
tests/functional/test_contract_instance.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_contract_instance.py
Apache-2.0
def test_decode_call_input_no_method_id(contract_instance, calldata): """ Ensure Ape can figure out the method if the ID is missing. """ anonymous_calldata = calldata[4:] method = contract_instance.setNumber.call actual = method.decode_input(anonymous_calldata) expected = "setNumber(uint256)", {"num": 222} assert actual == expected
Ensure Ape can figure out the method if the ID is missing.
test_decode_call_input_no_method_id
python
ApeWorX/ape
tests/functional/test_contract_instance.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_contract_instance.py
Apache-2.0
def test_decode_transaction_input_no_method_id(contract_instance, calldata): """ Ensure Ape can figure out the method if the ID is missing. """ anonymous_calldata = calldata[4:] method = contract_instance.setNumber actual = method.decode_input(anonymous_calldata) expected = "setNumber(uint256)", {"num": 222} assert actual == expected
Ensure Ape can figure out the method if the ID is missing.
test_decode_transaction_input_no_method_id
python
ApeWorX/ape
tests/functional/test_contract_instance.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_contract_instance.py
Apache-2.0
def test_is_contract_when_code_is_str(mock_provider, owner): """ Tests the cases when an ecosystem uses str for ContractCode. """ # Set up the provider to return str instead of HexBytes for code. mock_provider._web3.eth.get_code.return_value = "0x1234" assert owner.is_contract # When the return value is the string "0x", it should not code as having code. mock_provider._web3.eth.get_code.return_value = "0x" assert not owner.is_contract
Tests the cases when an ecosystem uses str for ContractCode.
test_is_contract_when_code_is_str
python
ApeWorX/ape
tests/functional/test_contract_instance.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_contract_instance.py
Apache-2.0
def test_struct_input_web3_named_tuple(solidity_contract_instance, owner): """ Show we integrate nicely with web3 contracts notion of namedtuples. """ data = {"a": solidity_contract_instance.address, "b": HexBytes(123), "c": 321} w3_named_tuple = recursive_dict_to_namedtuple(data) assert not solidity_contract_instance.setStruct(w3_named_tuple, sender=owner).failed actual = solidity_contract_instance.myStruct() assert actual.a == solidity_contract_instance.address # B is automatically right-padded. expected_b = HexBytes("0x7b00000000000000000000000000000000000000000000000000000000000000") assert actual.b == expected_b assert actual.c == data["c"]
Show we integrate nicely with web3 contracts notion of namedtuples.
test_struct_input_web3_named_tuple
python
ApeWorX/ape
tests/functional/test_contract_instance.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_contract_instance.py
Apache-2.0
def test_get_error_by_signature(error_contract): """ Helps in cases where multiple errors have same name. Only happens when importing or using types from interfaces. """ signature = error_contract.Unauthorized.abi.signature actual = error_contract.get_error_by_signature(signature) expected = error_contract.Unauthorized assert actual == expected
Helps in cases where multiple errors have same name. Only happens when importing or using types from interfaces.
test_get_error_by_signature
python
ApeWorX/ape
tests/functional/test_contract_instance.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_contract_instance.py
Apache-2.0
def test_fallback(fallback_contract, owner): """ Test that shows __call__ uses the contract's defined fallback method. We know this is a successful test because otherwise you would get a ContractLogicError. """ receipt = fallback_contract(sender=owner, gas=40000, data="0x123") assert not receipt.failed
Test that shows __call__ uses the contract's defined fallback method. We know this is a successful test because otherwise you would get a ContractLogicError.
test_fallback
python
ApeWorX/ape
tests/functional/test_contract_instance.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_contract_instance.py
Apache-2.0
def test_value_to_non_payable_fallback_and_no_receive( vyper_fallback_contract, owner, vyper_fallback_contract_type ): """ Test that shows when fallback is non-payable and there is no receive, and you try to send a value, it fails. """ # Hack to set fallback as non-payable. contract_type_data = vyper_fallback_contract_type.model_dump() for abi in contract_type_data["abi"]: if abi.get("type") == "fallback": abi["stateMutability"] = "non-payable" break new_contract_type = ContractType.model_validate(contract_type_data) contract = owner.chain_manager.contracts.instance_at(vyper_fallback_contract.address) contract.contract_type = new_contract_type # Setting to completely override instead of merge. expected = ( r"Contract's fallback is non-payable and there is no receive ABI\. Unable to send value\." ) with pytest.raises(MethodNonPayableError, match=expected): contract(sender=owner, value=1) # Show can bypass by using `as_transaction()` and `owner.call()`. txn = contract.as_transaction(sender=owner, value=1) receipt = owner.call(txn) # NOTE: This actually passed because the non-payble was hacked in (see top of test). # The actual contract's default is payable, so the receipt actually succeeds. # ** Nonetheless, this test is only proving you can bypass the checks **. assert not receipt.failed
Test that shows when fallback is non-payable and there is no receive, and you try to send a value, it fails.
test_value_to_non_payable_fallback_and_no_receive
python
ApeWorX/ape
tests/functional/test_contract_instance.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_contract_instance.py
Apache-2.0
def test_fallback_with_data_and_value_and_receive(solidity_fallback_contract, owner): """ In the case when there is a fallback method and a receive method, if the user sends data, it will hit the fallback method. But if they also send a value, it would fail if the fallback is non-payable. """ expected = "Sending both value= and data= but fallback is non-payable." with pytest.raises(MethodNonPayableError, match=expected): solidity_fallback_contract(sender=owner, data="0x123", value=1) # Show can bypass by using `as_transaction()` and `owner.call()`. txn = solidity_fallback_contract.as_transaction(sender=owner, data="0x123", value=1) with pytest.raises(ContractLogicError): owner.call(txn)
In the case when there is a fallback method and a receive method, if the user sends data, it will hit the fallback method. But if they also send a value, it would fail if the fallback is non-payable.
test_fallback_with_data_and_value_and_receive
python
ApeWorX/ape
tests/functional/test_contract_instance.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_contract_instance.py
Apache-2.0
def test_fallback_not_defined(contract_instance, owner): """ Test that shows __call__ attempts to use the Fallback method, which is not defined and results in a ContractLogicError. """ with pytest.raises(ContractLogicError): # Fails because no fallback is defined in these contracts. contract_instance(sender=owner)
Test that shows __call__ attempts to use the Fallback method, which is not defined and results in a ContractLogicError.
test_fallback_not_defined
python
ApeWorX/ape
tests/functional/test_contract_instance.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_contract_instance.py
Apache-2.0
def test_line_rate_when_no_statements(self): """ An edge case: when a function has no statements, its line rate it either 0% if it was not called or 100% if it called. """ function = FunctionCoverage(name="bar", full_name="bar()") assert function.hit_count == 0 function.hit_count += 1 assert function.line_rate == 1
An edge case: when a function has no statements, its line rate it either 0% if it was not called or 100% if it called.
test_line_rate_when_no_statements
python
ApeWorX/ape
tests/functional/test_coverage.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_coverage.py
Apache-2.0
def test_repr_manifest_project(): """ Tests against assuming the dependency manager is related to a local project (could be from a manifest-project). """ manifest = PackageManifest() project = Project.from_manifest(manifest, config_override={"name": "testname123"}) dm = project.dependencies actual = repr(dm) expected = "<DependencyManager project=testname123>" assert actual == expected
Tests against assuming the dependency manager is related to a local project (could be from a manifest-project).
test_repr_manifest_project
python
ApeWorX/ape
tests/functional/test_dependencies.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_dependencies.py
Apache-2.0
def test_dependency_with_multiple_versions(project_with_downloaded_dependencies): """ Testing the case where we have OpenZeppelin installed multiple times with different versions. """ name = "openzeppelin" dm = project_with_downloaded_dependencies.dependencies # We can get both projects at once! One for each version. oz_310 = dm.get_dependency(name, "3.1.0", allow_install=False) oz_442 = dm.get_dependency(name, "4.4.2", allow_install=False) base_uri = "https://github.com/OpenZeppelin/openzeppelin-contracts/releases/tag" assert oz_310.version == "3.1.0" assert oz_310.name == name assert str(oz_310.uri) == f"{base_uri}/v3.1.0" assert oz_442.version == "4.4.2" assert oz_442.name == name assert str(oz_442.uri) == f"{base_uri}/v4.4.2"
Testing the case where we have OpenZeppelin installed multiple times with different versions.
test_dependency_with_multiple_versions
python
ApeWorX/ape
tests/functional/test_dependencies.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_dependencies.py
Apache-2.0
def test_get_dependency_returns_latest_updates(project, project_with_contracts): """ Integration test showing how to utilize the changes to dependencies from the config. """ cfg = [{"name": "dep", "version": "10.1.10", "local": f"{project_with_contracts.path}"}] with project.temp_config(dependencies=cfg): project.dependencies.install() dep = project.dependencies.get_dependency("dep", "10.1.10") assert dep.package_id == f"{project_with_contracts.path}" assert dep.api.local == project_with_contracts.path # Changing the version in the config and force re-installing should change the package data. project.config["dependencies"][0]["local"] = f"{Path(__file__).parent}" project.dependencies.install(use_cache=False) # Show `.get_dependency()` will return the updated version when given name alone. dep = project.dependencies.get_dependency("dep", "10.1.10") assert dep.api.local == Path(__file__).parent
Integration test showing how to utilize the changes to dependencies from the config.
test_get_dependency_returns_latest_updates
python
ApeWorX/ape
tests/functional/test_dependencies.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_dependencies.py
Apache-2.0
def test_install_already_installed(mocker, project, with_dependencies_project_path): """ Some dependencies never produce sources because of default compiler extension behavior (example: a16z_erc4626-tests repo). """ dm = project.dependencies dep = dm.install(local=with_dependencies_project_path, name="wdep") # Set up a spy on the fetch API, which can be costly and require internet. real_api = dep.api mock_api = mocker.MagicMock() dep.api = mock_api # Remove in-memory cache. dep._installation = None # Install again. with pytest.raises(ProjectError): dep.install() dep.api = real_api # Ensure it doesn't need to re-fetch assert mock_api.call_count == 0
Some dependencies never produce sources because of default compiler extension behavior (example: a16z_erc4626-tests repo).
test_install_already_installed
python
ApeWorX/ape
tests/functional/test_dependencies.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_dependencies.py
Apache-2.0
def test_name_from_github(self): """ When not given a name, it is derived from the github suffix. """ dependency = GithubDependency( # type: ignore github="ApeWorX/ApeNotAThing", version="3.0.0" ) assert dependency.name == "apenotathing"
When not given a name, it is derived from the github suffix.
test_name_from_github
python
ApeWorX/ape
tests/functional/test_dependencies.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_dependencies.py
Apache-2.0
def test_fetch_missing_v_prefix(self, mock_client): """ Show if the version expects a v-prefix but you don't provide one that it still works. """ dependency = GithubDependency( github="ApeWorX/ApeNotAThing", version="3.0.0", name="apetestdep" ) dependency._github_client = mock_client # Simulate only v-prefix succeeding from GH def only_want_v(n0, n1, vers, pth): if not vers.startswith("v"): raise ValueError("nope") mock_client.download_package.side_effect = only_want_v with create_tempdir() as path: dependency.fetch(path) calls = mock_client.download_package.call_args_list assert mock_client.download_package.call_count == 2 # Show it first tried w/o v assert calls[0][0] == ("ApeWorX", "ApeNotAThing", "3.0.0", path) # The second call has the v! assert calls[1][0] == ("ApeWorX", "ApeNotAThing", "v3.0.0", path)
Show if the version expects a v-prefix but you don't provide one that it still works.
test_fetch_missing_v_prefix
python
ApeWorX/ape
tests/functional/test_dependencies.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_dependencies.py
Apache-2.0
def test_fetch_unneeded_v_prefix(self, mock_client): """ Show if the version expects not to have a v-prefix but you provide one that it still works. """ dependency = GithubDependency( github="ApeWorX/ApeNotAThing", version="v3.0.0", name="apetestdep" ) dependency._github_client = mock_client # Simulate only non-v-prefix succeeding from GH def only_want_non_v(n0, n1, vers, pth): if vers.startswith("v"): raise ValueError("nope") mock_client.download_package.side_effect = only_want_non_v with create_tempdir() as path: dependency.fetch(path) calls = mock_client.download_package.call_args_list assert mock_client.download_package.call_count == 2 # Show it first tried with the v assert calls[0][0] == ("ApeWorX", "ApeNotAThing", "v3.0.0", path) # The second call does not have the v! assert calls[1][0] == ("ApeWorX", "ApeNotAThing", "3.0.0", path)
Show if the version expects not to have a v-prefix but you provide one that it still works.
test_fetch_unneeded_v_prefix
python
ApeWorX/ape
tests/functional/test_dependencies.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_dependencies.py
Apache-2.0
def test_fetch_given_version_when_expects_reference(self, mock_client): """ Show that if a user configures `version:`, but version fails, it tries `ref:` instead as a backup. """ dependency = GithubDependency( github="ApeWorX/ApeNotAThing", version="v3.0.0", name="apetestdep" ) dependency._github_client = mock_client # Simulate no versions ever found on GH Api. mock_client.download_package.side_effect = ValueError("nope") # Simulate only the non-v prefix ref working (for a fuller flow) def needs_non_v_prefix_ref(n0, n1, dst_path, branch, scheme): # NOTE: This assertion is very important! # We must only give it non-existing directories. assert not dst_path.is_dir() if branch.startswith("v"): raise ValueError("nope") mock_client.clone_repo.side_effect = needs_non_v_prefix_ref with create_tempdir() as path: dependency.fetch(path) calls = mock_client.clone_repo.call_args_list assert mock_client.clone_repo.call_count == 2 # Show it first tried with the v assert calls[0][0] == ("ApeWorX", "ApeNotAThing", path) assert calls[0][1] == {"branch": "v3.0.0", "scheme": "https"} # The second call does not have the v! assert calls[1][0] == ("ApeWorX", "ApeNotAThing", path) assert calls[1][1] == {"branch": "3.0.0", "scheme": "https"}
Show that if a user configures `version:`, but version fails, it tries `ref:` instead as a backup.
test_fetch_given_version_when_expects_reference
python
ApeWorX/ape
tests/functional/test_dependencies.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_dependencies.py
Apache-2.0
def test_fetch_ref(self, mock_client): """ When specifying ref, it does not try version API at all. """ dependency = GithubDependency(github="ApeWorX/ApeNotAThing", ref="3.0.0", name="apetestdep") dependency._github_client = mock_client with create_tempdir() as path: dependency.fetch(path) assert mock_client.download_package.call_count == 0 mock_client.clone_repo.assert_called_once_with( "ApeWorX", "ApeNotAThing", path, branch="3.0.0", scheme="https", )
When specifying ref, it does not try version API at all.
test_fetch_ref
python
ApeWorX/ape
tests/functional/test_dependencies.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_dependencies.py
Apache-2.0
def test_fetch_existing_destination_with_read_only_files(self, mock_client): """ Show it handles when the destination contains read-only files already """ dependency = GithubDependency(github="ApeWorX/ApeNotAThing", ref="3.0.0", name="apetestdep") dependency._github_client = mock_client with create_tempdir() as path: readonly_file = path / "readme.txt" readonly_file.write_text("readme!") # NOTE: This only makes a difference on Windows. If using a UNIX system, # rmtree still deletes readonly files regardless. Windows is more restrictive. os.chmod(readonly_file, 0o444) # Read-only permissions dependency.fetch(path) assert not readonly_file.is_file()
Show it handles when the destination contains read-only files already
test_fetch_existing_destination_with_read_only_files
python
ApeWorX/ape
tests/functional/test_dependencies.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_dependencies.py
Apache-2.0
def test_contracts_folder(self, project_from_dependency): """ The local dependency fixture uses a longer contracts folder path. This test ensures that the contracts folder field is honored, specifically In the case when it contains sub-paths. """ actual = project_from_dependency.contracts_folder expected = project_from_dependency.path / "source" / "v0.1" assert actual == expected
The local dependency fixture uses a longer contracts folder path. This test ensures that the contracts folder field is honored, specifically In the case when it contains sub-paths.
test_contracts_folder
python
ApeWorX/ape
tests/functional/test_dependencies.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_dependencies.py
Apache-2.0
def test_getattr(self, project_with_downloaded_dependencies): """ Access contracts using __getattr__ from the dependency's project. """ name = "openzeppelin" oz_442 = project_with_downloaded_dependencies.dependencies.get_dependency(name, "4.4.2") contract = oz_442.project.AccessControl assert contract.contract_type.name == "AccessControl"
Access contracts using __getattr__ from the dependency's project.
test_getattr
python
ApeWorX/ape
tests/functional/test_dependencies.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_dependencies.py
Apache-2.0
def test_cache_deployment_live_network_new_ecosystem( self, zero_address, cache, contract_name, mock_sepolia, eth_tester_provider ): """ Tests the case when caching a deployment in a new ecosystem. """ ecosystem_name = mock_sepolia.ecosystem.name local = eth_tester_provider.network eth_tester_provider.network = mock_sepolia # Make the ecosystem key not exist. deployments = cache._deployments.pop(ecosystem_name, None) cache.cache_deployment(zero_address, contract_name) eth_tester_provider.network = local if deployments is not None: cache._deployments[ecosystem_name] = deployments cache.cachefile.unlink(missing_ok=True) # In memory cached still work. assert contract_name in cache assert cache[contract_name][-1].address == zero_address # Show it did NOT cache to disk. if cache.cachefile.is_file(): disk_data = json.loads(cache.cachefile.read_text()) assert contract_name not in disk_data["ecosystems"][ecosystem_name]["sepolia"]
Tests the case when caching a deployment in a new ecosystem.
test_cache_deployment_live_network_new_ecosystem
python
ApeWorX/ape
tests/functional/test_deploymentscache.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_deploymentscache.py
Apache-2.0
def test_encode_calldata_byte_array(ethereum, sequence_type, item_type): """ Tests against a bug where we could not pass a tuple of HexStr for a byte-array. """ abi = make_method_abi( "mint", inputs=[{"name": "leaf", "type": "bytes32"}, {"name": "proof", "type": "bytes32[]"}] ) hexstr_array = sequence_type( ( item_type("0xfadbd3"), item_type("0x9c6b2c"), item_type("0xc5d246"), ) ) actual = ethereum.encode_calldata(abi, "0x0123", hexstr_array) assert isinstance(actual, bytes)
Tests against a bug where we could not pass a tuple of HexStr for a byte-array.
test_encode_calldata_byte_array
python
ApeWorX/ape
tests/functional/test_ecosystem.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_ecosystem.py
Apache-2.0
def test_decode_block_with_hex_values(ethereum): """ When using WS providers directly, the values are all hex strings (more raw). This test ensures we can still decode blocks that are in this form. """ raw_block = { "baseFeePerGas": "0x62d76fae2", "difficulty": "0x0", "extraData": "0x506f776572656420627920626c6f58726f757465", "gasLimit": "0x1c9c380", "gasUsed": "0x91b5e5", "hash": "0x925cac44d8bac5df3e3eeed6379b3924d6769a054b3c4079899c1d9b442a4041", "logsBloom": "0x7823d304ab8c72f91270a023c11482f341a08a00c91b00f8859906c8e9f22e04b19d311e422cfa79d8107e2b901fc7d9c62fcd2d8a673802f500f4a023693525a2ce66481cc51d1a4e97422b8424912b8c719c6821589a240d5015c5cbe4de46b3b60ad43621cd2f540119b3c938d88f011a49d755a31cc415f34896596912d40b0397d0c544571704ea001c56303f02086e16a3a3b7168f443d224034102ca4c6b21456932dae401c8da7c51d36ae3804c8a084811802c708ae94b7010302100700a28f156d2ca2d61420320e82e8b9927b626bc0ec003dfa09009e3d1668798fb0f8c81a205eb100ee8ea2e20c6041b2d8b2b01bd4d14e8acfaa317049d654", "miner": "0x6b3a8798e5fb9fc5603f3ab5ea2e8136694e55d0", "mixHash": "0x0493af8ac5b7de66c7660c22a703a54069cbd561a2767537eaef994bd77e084b", "nonce": "0x0000000000000000", "number": "0x11234df", "parentHash": "0x47651c13bda353d1bbc610bbdb8a9aa1436629f05f8a32a27f143200da698df8", "receiptsRoot": "0xa5abe7eeac74aa03ea82421fcef9b74d1822cfe0ee4b29a8dc01eef31e7d0019", "sha3Uncles": "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347", "size": "0x1cf02", "stateRoot": "0x59eb1dfb098361d1f74dffc8436da680715f671dc3f02be28f4db3f44b1a09bf", "timestamp": "0x64e4b0cb", "transactionsRoot": "0xf2e3c3e4fbe06ff882f3deb8a7ec8cbbe09e55b2c995d93dd0a36d5e843f3efc", } actual = ethereum.decode_block(raw_block) assert actual.difficulty == 0
When using WS providers directly, the values are all hex strings (more raw). This test ensures we can still decode blocks that are in this form.
test_decode_block_with_hex_values
python
ApeWorX/ape
tests/functional/test_ecosystem.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_ecosystem.py
Apache-2.0
def test_decode_logs_topics_not_first(ethereum): """ Tests against a condition where we could not decode logs if the topics were not defined first. """ abi_dict = { "anonymous": False, "inputs": [ {"indexed": False, "internalType": "address", "name": "sender", "type": "address"}, {"indexed": True, "internalType": "address", "name": "owner", "type": "address"}, {"indexed": True, "internalType": "int24", "name": "tickLower", "type": "int24"}, {"indexed": True, "internalType": "int24", "name": "tickUpper", "type": "int24"}, {"indexed": False, "internalType": "uint128", "name": "amount", "type": "uint128"}, {"indexed": False, "internalType": "uint256", "name": "amount0", "type": "uint256"}, {"indexed": False, "internalType": "uint256", "name": "amount1", "type": "uint256"}, ], "name": "Mint", "type": "event", } abi = EventABI.model_validate(abi_dict) logs = [ { "address": "0x3416cf6c708da44db2624d63ea0aaef7113527c6", "blockHash": "0x488f23ba55f64bf1aac02ee7278b70c3f4bb2fb57b8aaa6ab3b481f1809f18ea", "blockNumber": "0xcfa869", "data": "0x000000000000000000000000c36442b4a4522e871399cd717abdd847ab11fe8800000000000000000000000000000000000000000000000000821d6b102660fb000000000000000000000000000000000000000000000000000009fde8545338000000000000000000000000000000000000000000000000000003548cf35031", "logIndex": "0x7a", "removed": False, "topics": [ "0x7a53080ba414158be7ec69b987b5fb7d07dee101fe85488f0853ae16239d0bde", "0x000000000000000000000000c36442b4a4522e871399cd717abdd847ab11fe88", "0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc", "0x0000000000000000000000000000000000000000000000000000000000000004", ], "transactionHash": "0xf093a630478562d03e3b2476a5b0551609722747d442a462579fa02e1332a941", "transactionIndex": "0x41", } ] actual = list(ethereum.decode_logs(logs, abi)) assert actual
Tests against a condition where we could not decode logs if the topics were not defined first.
test_decode_logs_topics_not_first
python
ApeWorX/ape
tests/functional/test_ecosystem.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_ecosystem.py
Apache-2.0
def test_decode_receipt_misleading_blob_receipt(ethereum): """ Tests a strange situation (noticed on Tenderly nodes) where _some_ of the keys indicate blob-related fields, set to ``0``, and others are missing, because it's not actually a blob receipt. In this case, don't use the blob-receipt class. """ data = { "type": 2, "status": 1, "cumulativeGasUsed": 10565720, "logsBloom": HexBytes( "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" ), "logs": [], "transactionHash": HexBytes( "0x62fc9991bc7fb0c76bc83faaa8d1c17fc5efb050542e58ac358932f80aa7a087" ), "from": "0x1f9090aaE28b8a3dCeaDf281B0F12828e676c326", "to": "0xeBec795c9c8bBD61FFc14A6662944748F299cAcf", "contractAddress": None, "gasUsed": 21055, "effectiveGasPrice": 7267406643, "blockHash": HexBytes("0xa47fc133f829183b751488c1146f1085451bcccd247db42066dc6c89eaf5ebac"), "blockNumber": 21051245, "transactionIndex": 130, "blobGasUsed": 0, } actual = ethereum.decode_receipt(data) assert not isinstance(actual, SharedBlobReceipt) assert isinstance(actual, Receipt)
Tests a strange situation (noticed on Tenderly nodes) where _some_ of the keys indicate blob-related fields, set to ``0``, and others are missing, because it's not actually a blob receipt. In this case, don't use the blob-receipt class.
test_decode_receipt_misleading_blob_receipt
python
ApeWorX/ape
tests/functional/test_ecosystem.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_ecosystem.py
Apache-2.0
def test_default_transaction_type_changed_at_class_level(ethereum): """ Simulates an L2 plugin changing the default at the definition-level. """ class L2NetworkConfig(BaseEthereumConfig): DEFAULT_TRANSACTION_TYPE: ClassVar[int] = TransactionType.STATIC.value config = L2NetworkConfig() assert config.local.default_transaction_type.value == 0 assert config.mainnet.default_transaction_type.value == 0 assert config.mainnet_fork.default_transaction_type.value == 0
Simulates an L2 plugin changing the default at the definition-level.
test_default_transaction_type_changed_at_class_level
python
ApeWorX/ape
tests/functional/test_ecosystem.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_ecosystem.py
Apache-2.0
def test_decode_returndata_list_with_1_struct(ethereum): """ Tests a condition where an array of a list with 1 struct would be turned into a raw tuple instead of the Struct class. """ abi = make_method_abi( "getArrayOfStructs", outputs=[ ABIType( name="", type="tuple[]", components=[ ABIType(name="a", type="address", components=None, internal_type=None), ABIType(name="b", type="bytes32", components=None, internal_type=None), ], internal_type=None, ) ], ) raw_data = HexBytes( "0x000000000000000000000000000000000000000000000000000000000000002" "00000000000000000000000000000000000000000000000000000000000000001" "000000000000000000000000f39fd6e51aad88f6f4ce6ab8827279cfffb92266f" "d91dc47b758f65fd0f6fe511566770c0ae3f94ff9999ceb23bfec3ac9fdc168" ) actual = ethereum.decode_returndata(abi, raw_data) assert len(actual) == 1 # The result should still be a list. # There was also a bug where it was mistakenly a tuple! assert isinstance(actual[0], list) assert len(actual[0]) == 1 assert actual[0][0].a == "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266" assert actual[0][0].b == HexBytes( "0xfd91dc47b758f65fd0f6fe511566770c0ae3f94ff9999ceb23bfec3ac9fdc168" )
Tests a condition where an array of a list with 1 struct would be turned into a raw tuple instead of the Struct class.
test_decode_returndata_list_with_1_struct
python
ApeWorX/ape
tests/functional/test_ecosystem.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_ecosystem.py
Apache-2.0
def test_create_transaction_with_none_values(ethereum, eth_tester_provider): """ Tests against None being in place of values in kwargs, causing their actual defaults not to get used and ValidationErrors to occur. """ static = ethereum.create_transaction( value=None, data=None, chain_id=None, gas_price=None, nonce=None, receiver=None ) dynamic = ethereum.create_transaction( value=None, data=None, chain_id=None, max_fee=None, max_priority_fee=None, nonce=None, receiver=None, ) assert isinstance(static, StaticFeeTransaction) # Because used gas_price assert isinstance(dynamic, DynamicFeeTransaction) # Because used max_fee for tx in (static, dynamic): assert tx.data == b"" # None is not allowed. assert tx.value == 0 # None is same as 0. assert tx.chain_id == eth_tester_provider.chain_id assert tx.nonce is None assert static.gas_price is None assert dynamic.max_fee is None assert dynamic.max_priority_fee is None
Tests against None being in place of values in kwargs, causing their actual defaults not to get used and ValidationErrors to occur.
test_create_transaction_with_none_values
python
ApeWorX/ape
tests/functional/test_ecosystem.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_ecosystem.py
Apache-2.0
def test_default_network_name_when_not_set_and_no_local_uses_only( project, custom_networks_config_dict ): """ Tests a condition that is rare but when a default network is not set but there is a single network. In this case, it should use the single network by default. """ net = copy.deepcopy(custom_networks_config_dict["networks"]["custom"][0]) # In a situation with an ecosystem with only a single network. ecosystem_name = "acustomeco" net["ecosystem"] = ecosystem_name only_network = "onlynet" # More obvious name for test. net["name"] = only_network with project.temp_config(networks={"custom": [net]}): ecosystem = project.network_manager.get_ecosystem(ecosystem_name) ecosystem._default_network = None actual = ecosystem.default_network_name if actual == LOCAL_NETWORK_NAME: # For some reason, this test is flake-y. Offer more info # to try and debug when this happens (intermittent CI failure). all_nets = ", ".join([x for x in ecosystem.networks.keys()]) pytest.fail( f"assert '{LOCAL_NETWORK_NAME}' == '{only_network}'. More info below:\n" f"ecosystem_name={ecosystem.name}\n" f"networks={all_nets}\n" f"type={type(ecosystem)}" ) else: # This should pass. assert ecosystem.default_network_name == only_network
Tests a condition that is rare but when a default network is not set but there is a single network. In this case, it should use the single network by default.
test_default_network_name_when_not_set_and_no_local_uses_only
python
ApeWorX/ape
tests/functional/test_ecosystem.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_ecosystem.py
Apache-2.0
def test_enrich_trace_handles_call_type_enum(ethereum, vyper_contract_instance, owner): """ Testing a custom trace whose call tree uses an Enum type instead of a str. """ class PluginTxTrace(TransactionTrace): def get_calltree(self) -> CallTreeNode: call = super().get_calltree() # Force enum value instead of str. call.call_type = CallType.CALL return call tx = vyper_contract_instance.setNumber(96247783, sender=owner) trace = PluginTxTrace(transaction_hash=tx.txn_hash) actual = ethereum.enrich_trace(trace) assert isinstance(actual, PluginTxTrace) assert actual._enriched_calltree is not None assert re.match(r"VyperContract\.setNumber\(num=\d*\) \[\d* gas]", repr(actual)) # Hook into helper method hackily with an enum. # Notice the mode is Python and not JSON here. call = trace.get_calltree().model_dump(by_alias=True) actual = ethereum._enrich_calltree(call) assert actual["call_type"] == CallType.CALL.value
Testing a custom trace whose call tree uses an Enum type instead of a str.
test_enrich_trace_handles_call_type_enum
python
ApeWorX/ape
tests/functional/test_ecosystem.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_ecosystem.py
Apache-2.0
def test_receipt_is_subclass(self, vyper_contract_instance, owner): """ Ensure TransactionError knows subclass Receipts are still receipts. (There was a bug once when it didn't, and that caused internal AttributeErrors). """ class SubclassReceipt(Receipt): pass receipt = vyper_contract_instance.setNumber(123, sender=owner) receipt_data = {**receipt.model_dump(), "transaction": receipt.transaction} sub_receipt = SubclassReceipt.model_validate(receipt_data) err = TransactionError(txn=sub_receipt) assert isinstance(err.txn, ReceiptAPI) # Same check used.
Ensure TransactionError knows subclass Receipts are still receipts. (There was a bug once when it didn't, and that caused internal AttributeErrors).
test_receipt_is_subclass
python
ApeWorX/ape
tests/functional/test_exceptions.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_exceptions.py
Apache-2.0
def test_call_with_txn_and_not_source_tb(self, failing_call): """ Simulating a failing-call, making sure it doesn't blow up if it doesn't get a source-tb. """ err = TransactionError(txn=failing_call) assert err.source_traceback is None
Simulating a failing-call, making sure it doesn't blow up if it doesn't get a source-tb.
test_call_with_txn_and_not_source_tb
python
ApeWorX/ape
tests/functional/test_exceptions.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_exceptions.py
Apache-2.0
def test_call_with_source_tb_and_not_txn(self, mocker, project_with_contract): """ Simulating a failing call, making sure the source-tb lines show up when a txn is NOT given. """ # Using mocks for simplicity. Otherwise have to use a bunch of models from ethpm-types; # most of the stuff being mocked seems simple but is calculated from AST-Nodes and such. src_path = "path/to/VyperFile.vy" mock_tb = mocker.MagicMock() mock_exec = mocker.MagicMock() mock_exec.depth = 1 mock_exec.source_path = src_path mock_exec.begin_lineno = 5 mock_exec.end_lineno = 5 mock_closure = mocker.MagicMock() mock_closure.name = "setNumber" mock_exec.closure = mock_closure mock_tb.__getitem__.return_value = mock_exec mock_tb.__len__.return_value = 1 mock_tb.return_value = mock_tb err = TransactionError( source_traceback=mock_tb, project=project_with_contract, set_ape_traceback=True ) # Have to raise for sys.exc_info() to be available. try: raise err except Exception: pass def assert_ape_traceback(err_arg): assert err_arg.__traceback__ is not None # The Vyper-frame gets injected at tb_next. assert err_arg.__traceback__.tb_next is not None actual = str(err_arg.__traceback__.tb_next.tb_frame) assert src_path in actual assert_ape_traceback(err) err2 = TransactionError( source_traceback=mock_tb, project=project_with_contract, set_ape_traceback=False, ) try: raise err2 except Exception: pass # No Ape frames are here. if err2.__traceback__: assert err2.__traceback__.tb_next is None err3 = ContractLogicError(source_traceback=mock_tb, project=project_with_contract) try: raise err3 except Exception: pass assert_ape_traceback(err3)
Simulating a failing call, making sure the source-tb lines show up when a txn is NOT given.
test_call_with_source_tb_and_not_txn
python
ApeWorX/ape
tests/functional/test_exceptions.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_exceptions.py
Apache-2.0
def test_source_traceback_from_txn(self, owner): """ Was not given a source-traceback but showing we can deduce one from the given transaction. """ tx = owner.transfer(owner, 0) err = TransactionError(txn=tx) _ = err.source_traceback assert err._attempted_source_traceback
Was not given a source-traceback but showing we can deduce one from the given transaction.
test_source_traceback_from_txn
python
ApeWorX/ape
tests/functional/test_exceptions.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_exceptions.py
Apache-2.0
def test_local_network(self): """ Testing we are NOT mentioning explorer plugins for the local-network, as 99.9% of the time it is confusing. """ err = ContractNotFoundError(ZERO_ADDRESS, False, f"ethereum:{LOCAL_NETWORK_NAME}:test") assert str(err) == f"Failed to get contract type for address '{ZERO_ADDRESS}'."
Testing we are NOT mentioning explorer plugins for the local-network, as 99.9% of the time it is confusing.
test_local_network
python
ApeWorX/ape
tests/functional/test_exceptions.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_exceptions.py
Apache-2.0
def test_isolation_supported_flag_set_after_successful_snapshot(fixtures): """ Testing the unusual case where `.supported` was changed manually after a successful snapshot and before the restore attempt. """ class CustomIsolationManager(IsolationManager): take_called = False restore_called = False def take_snapshot(self) -> Optional["SnapshotID"]: self.take_called = True return 123 def restore(self, scope: Scope): self.restore_called = True isolation_manager = CustomIsolationManager( fixtures.isolation_manager.config_wrapper, fixtures.isolation_manager.receipt_capture, ) isolation_context = isolation_manager.isolation(Scope.FUNCTION) next(isolation_context) # Enter. assert isolation_manager.take_called assert not isolation_manager.restore_called # HACK: Change the flag manually to show it will avoid # the restore. isolation_manager.supported = False isolation_manager.take_called = False # Reset next(isolation_context, None) # Exit. # Even though snapshotting worked, the flag was changed, # and so the restore never gets attempted. assert not isolation_manager.take_called
Testing the unusual case where `.supported` was changed manually after a successful snapshot and before the restore attempt.
test_isolation_supported_flag_set_after_successful_snapshot
python
ApeWorX/ape
tests/functional/test_fixtures.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_fixtures.py
Apache-2.0
def test_config_custom_networks_default(ethereum, project, custom_networks_config_dict): """ Shows you don't get AttributeError when custom network config is not present. """ with project.temp_config(**custom_networks_config_dict): network = ethereum.apenet cfg = network.config assert cfg.default_transaction_type == TransactionType.DYNAMIC
Shows you don't get AttributeError when custom network config is not present.
test_config_custom_networks_default
python
ApeWorX/ape
tests/functional/test_network_api.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_network_api.py
Apache-2.0
def test_providers_NAME_defined(mocker): """ Show that when a provider plugin used the NAME ClassVar, the provider's name is that instead of the plugin's name. """ ecosystem_name = "my-ecosystem" network_name = "my-network" provider_name = "my-provider" class MyProvider(ProviderAPI): NAME: ClassVar[str] = provider_name class MyNetwork(NetworkAPI): def _get_plugin_providers(self): yield "my-provider-plugin", (ecosystem_name, network_name, MyProvider) class MyEcosystem(Ethereum): pass ecosystem = MyEcosystem(name=ecosystem_name) network = MyNetwork(name=network_name, ecosystem=ecosystem) actual = list(network.providers) assert actual == [provider_name] # And not "my-provider-plugin"
Show that when a provider plugin used the NAME ClassVar, the provider's name is that instead of the plugin's name.
test_providers_NAME_defined
python
ApeWorX/ape
tests/functional/test_network_api.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_network_api.py
Apache-2.0
def test_is_mainnet_from_config(project): """ Simulate an EVM plugin with a weird named mainnet that properly configured it. """ chain_id = 9191919191919919121177171 ecosystem_name = "ismainnettest" network_name = "primarynetwork" network_type = create_network_type(chain_id, chain_id) class MyConfig(BaseEthereumConfig): primarynetwork: NetworkConfig = create_network_config(is_mainnet=True) class MyEcosystem(Ethereum): name: str = ecosystem_name @property def config(self): return MyConfig() ecosystem = MyEcosystem() network = network_type(name=network_name, ecosystem=ecosystem) assert network.is_mainnet
Simulate an EVM plugin with a weird named mainnet that properly configured it.
test_is_mainnet_from_config
python
ApeWorX/ape
tests/functional/test_network_api.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_network_api.py
Apache-2.0
def test_explorer(networks): """ Local network does not have an explorer, by default. """ network = networks.ethereum.local network.__dict__.pop("explorer", None) # Ensure not cached yet. assert network.explorer is None
Local network does not have an explorer, by default.
test_explorer
python
ApeWorX/ape
tests/functional/test_network_api.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_network_api.py
Apache-2.0
def test_explorer_when_network_registered(networks, mocker): """ Tests the simple flow of having the Explorer plugin register the networks it supports. """ network = networks.ethereum.local network.__dict__.pop("explorer", None) # Ensure not cached yet. name = "my-explorer" def explorer_cls(*args, **kwargs): res = mocker.MagicMock() res.name = name return res mock_plugin_explorers = mocker.patch( "ape.api.networks.NetworkAPI._plugin_explorers", new_callable=mock.PropertyMock ) mock_plugin_explorers.return_value = [("my-example", ("ethereum", "local", explorer_cls))] assert network.explorer is not None assert network.explorer.name == name
Tests the simple flow of having the Explorer plugin register the networks it supports.
test_explorer_when_network_registered
python
ApeWorX/ape
tests/functional/test_network_api.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_network_api.py
Apache-2.0
def test_explorer_when_adhoc_network_supported(networks, mocker): """ Tests the flow of when a chain is supported by an explorer but not registered in the plugin (API-flow). """ network = networks.ethereum.local network.__dict__.pop("explorer", None) # Ensure not cached yet. NAME = "my-explorer" class MyExplorer: name: str = NAME def __init__(self, *args, **kwargs): pass @classmethod def supports_chain(cls, chain_id): return True mock_plugin_explorers = mocker.patch( "ape.api.networks.NetworkAPI._plugin_explorers", new_callable=mock.PropertyMock ) # NOTE: Ethereum is not registered at the plugin level, but is at the API level. mock_plugin_explorers.return_value = [ ("my-example", ("some-other-ecosystem", "local", MyExplorer)) ] assert network.explorer is not None assert network.explorer.name == NAME
Tests the flow of when a chain is supported by an explorer but not registered in the plugin (API-flow).
test_explorer_when_adhoc_network_supported
python
ApeWorX/ape
tests/functional/test_network_api.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_network_api.py
Apache-2.0
def test_getattr_evm_chains_ecosystem(networks): """ Show we can getattr evm-chains only ecosystems. """ actual = networks.moonbeam assert actual.name == "moonbeam"
Show we can getattr evm-chains only ecosystems.
test_getattr_evm_chains_ecosystem
python
ApeWorX/ape
tests/functional/test_network_manager.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_network_manager.py
Apache-2.0
def test_getattr_plugin_ecosystem_same_name_as_evm_chains(mocker, networks): """ Show when an ecosystem is both in evm-chains and an installed plugin that Ape prefers the installed plugin. """ moonbeam_plugin = mocker.MagicMock() networks._plugin_ecosystems["moonbeam"] = moonbeam_plugin actual = networks.moonbeam del networks._plugin_ecosystems["moonbeam"] assert actual == moonbeam_plugin assert actual != networks._evmchains_ecosystems["moonbeam"]
Show when an ecosystem is both in evm-chains and an installed plugin that Ape prefers the installed plugin.
test_getattr_plugin_ecosystem_same_name_as_evm_chains
python
ApeWorX/ape
tests/functional/test_network_manager.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_network_manager.py
Apache-2.0
def test_fork_network_not_forkable(networks, eth_tester_provider): """ Show correct failure when trying to fork the local network. """ expected = "Unable to fork network 'local'." with pytest.raises(NetworkError, match=expected): with networks.fork(): pass
Show correct failure when trying to fork the local network.
test_fork_network_not_forkable
python
ApeWorX/ape
tests/functional/test_network_manager.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_network_manager.py
Apache-2.0
def test_fork_no_providers(networks, mock_sepolia, disable_fork_providers): """ Show correct failure when trying to fork without ape-hardhat or ape-foundry installed. """ expected = "No providers for network 'sepolia-fork'." with pytest.raises(NetworkError, match=expected): with networks.fork(): pass
Show correct failure when trying to fork without ape-hardhat or ape-foundry installed.
test_fork_no_providers
python
ApeWorX/ape
tests/functional/test_network_manager.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_network_manager.py
Apache-2.0
def test_fork_use_non_existing_provider(networks, mock_sepolia): """ Show correct failure when specifying a non-existing provider. """ expected = "No provider named 'NOT_EXISTS' in network 'sepolia-fork' in ecosystem 'ethereum'.*" with pytest.raises(ProviderNotFoundError, match=expected): with networks.fork(provider_name="NOT_EXISTS"): pass
Show correct failure when specifying a non-existing provider.
test_fork_use_non_existing_provider
python
ApeWorX/ape
tests/functional/test_network_manager.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_network_manager.py
Apache-2.0
def test_fork_specify_provider(networks, mock_sepolia, mock_fork_provider): """ Happy-path fork test when specifying the provider. """ ctx = networks.fork(provider_name="mock") assert ctx._disconnect_after is True with ctx as provider: assert provider.name == "mock" assert provider.network.name == "sepolia-fork"
Happy-path fork test when specifying the provider.
test_fork_specify_provider
python
ApeWorX/ape
tests/functional/test_network_manager.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_network_manager.py
Apache-2.0
def test_fork_with_provider_settings(networks, mock_sepolia, mock_fork_provider): """ Show it uses the given provider settings. """ settings = {"fork": {"ethereum": {"sepolia": {"block_number": 123}}}} with networks.fork(provider_settings=settings): actual = mock_fork_provider.partial_call assert actual[1]["provider_settings"] == settings
Show it uses the given provider settings.
test_fork_with_provider_settings
python
ApeWorX/ape
tests/functional/test_network_manager.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_network_manager.py
Apache-2.0
def test_custom_networks_defined_in_non_local_project(custom_networks_config_dict): """ Showing we can read and use custom networks that are not defined in the local project. """ # Ensure we are using a name that is not used anywhere else, for accurte testing. net_name = "customnetdefinedinnonlocalproj" eco_name = "customecosystemnotdefinedyet" custom_networks = copy.deepcopy(custom_networks_config_dict) custom_networks["networks"]["custom"][0]["name"] = net_name custom_networks["networks"]["custom"][0]["ecosystem"] = eco_name with ape.Project.create_temporary_project(config_override=custom_networks) as temp_project: nm = temp_project.network_manager # Tests `.get_ecosystem()` for custom networks. ecosystem = nm.get_ecosystem(eco_name) assert ecosystem.name == eco_name network = ecosystem.get_network(net_name) assert network.name == net_name
Showing we can read and use custom networks that are not defined in the local project.
test_custom_networks_defined_in_non_local_project
python
ApeWorX/ape
tests/functional/test_network_manager.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_network_manager.py
Apache-2.0
def test_get_ecosystem_from_evmchains(networks): """ Show we can call `.get_ecosystem()` for an ecosystem only defined in evmchains. """ moonbeam = networks.get_ecosystem("moonbeam") assert isinstance(moonbeam, EcosystemAPI) assert moonbeam.name == "moonbeam"
Show we can call `.get_ecosystem()` for an ecosystem only defined in evmchains.
test_get_ecosystem_from_evmchains
python
ApeWorX/ape
tests/functional/test_network_manager.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_network_manager.py
Apache-2.0
def mock_python_path(tmp_path): """Create a temporary path to simulate a Python interpreter location.""" python_path = tmp_path / "python" python_path.touch() return f"{python_path}"
Create a temporary path to simulate a Python interpreter location.
mock_python_path
python
ApeWorX/ape
tests/functional/test_plugins.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_plugins.py
Apache-2.0
def test_getattr_empty_contract(tmp_project): """ Tests against a condition where would infinitely compile. """ source_id = tmp_project.Other.contract_type.source_id path = tmp_project.sources.lookup(source_id) path.unlink(missing_ok=True) path.write_text("", encoding="utf8") # Should have re-compiled. contract = tmp_project.Other assert not contract.contract_type.methods
Tests against a condition where would infinitely compile.
test_getattr_empty_contract
python
ApeWorX/ape
tests/functional/test_project.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_project.py
Apache-2.0
def test_extract_manifest_when_sources_missing(tmp_project): """ Show that if a source is missing, it is OK. This happens when changing branches after compiling and sources are only present on one of the branches. """ contract = make_contract("notreallyhere") tmp_project.manifest.contract_types = {contract.name: contract} manifest = tmp_project.extract_manifest() # Source is skipped because missing. assert "notreallyhere" not in manifest.contract_types
Show that if a source is missing, it is OK. This happens when changing branches after compiling and sources are only present on one of the branches.
test_extract_manifest_when_sources_missing
python
ApeWorX/ape
tests/functional/test_project.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_project.py
Apache-2.0
def test_load_contracts_after_deleting_same_named_contract(tmp_project, compilers, mock_compiler): """ Tests against a scenario where you: 1. Add and compile a contract 2. Delete that contract 3. Add a new contract with same name somewhere else Test such that we are able to compile successfully and not get a misleading collision error from deleted files. """ init_contract = tmp_project.contracts_folder / "foo.__mock__" init_contract.write_text("LALA", encoding="utf8") compilers.registered_compilers[".__mock__"] = mock_compiler result = tmp_project.load_contracts() assert "foo" in result # Goodbye. init_contract.unlink() # Since we are changing files mid-session, we need to refresh the project. # Typically, users don't have to do this. tmp_project.refresh_sources() result = tmp_project.load_contracts() assert "foo" not in result # Was deleted. # Also ensure it is gone from paths. assert "foo.__mock__" not in [x.name for x in tmp_project.sources.paths] # Create a new contract with the same name. new_contract = tmp_project.contracts_folder / "bar.__mock__" new_contract.write_text("BAZ", encoding="utf8") tmp_project.refresh_sources() mock_compiler.overrides = {"contractName": "foo"} result = tmp_project.load_contracts() assert "foo" in result
Tests against a scenario where you: 1. Add and compile a contract 2. Delete that contract 3. Add a new contract with same name somewhere else Test such that we are able to compile successfully and not get a misleading collision error from deleted files.
test_load_contracts_after_deleting_same_named_contract
python
ApeWorX/ape
tests/functional/test_project.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_project.py
Apache-2.0
def test_project_api_foundry_and_ape_config_found(foundry_toml): """ If a project is both a Foundry project and an Ape project, ensure both configs are honored. """ with create_tempdir() as tmpdir: foundry_cfg_file = tmpdir / "foundry.toml" foundry_cfg_file.write_text(foundry_toml, encoding="utf8") ape_cfg_file = tmpdir / "ape-config.yaml" ape_cfg_file.write_text("name: testfootestfootestfoo", encoding="utf8") temp_project = Project(tmpdir) assert isinstance(temp_project.project_api, MultiProject) # This came from the ape config file. assert temp_project.config.name == "testfootestfootestfoo" # This came from the foundry toml file. assert temp_project.config.contracts_folder == "src" assert len(temp_project.config.solidity.import_remapping) > 0
If a project is both a Foundry project and an Ape project, ensure both configs are honored.
test_project_api_foundry_and_ape_config_found
python
ApeWorX/ape
tests/functional/test_project.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_project.py
Apache-2.0
def test_from_manifest_load_contracts(self, contract_type): """ Show if contract-types are missing but sources set, compiling will add contract-types. """ manifest = make_manifest(contract_type, include_contract_type=False) project = Project.from_manifest(manifest) assert not project.manifest.contract_types, "Setup failed" # Returns containers, not types. actual = project.load_contracts() assert actual[contract_type.name].contract_type == contract_type # Also, show it got set on the manifest. assert project.manifest.contract_types == {contract_type.name: contract_type}
Show if contract-types are missing but sources set, compiling will add contract-types.
test_from_manifest_load_contracts
python
ApeWorX/ape
tests/functional/test_project.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_project.py
Apache-2.0
def test_hash(self, with_dependencies_project_path, project_from_manifest): """ Show we can use projects in sets. """ project_0 = Project(with_dependencies_project_path) project_1 = Project.from_python_library("web3") project_2 = project_from_manifest # Show we can use in sets. project_set = {project_0, project_1, project_2} assert len(project_set) == 3 # Show we can use as dict-keys: project_dict = {project_0: 123} assert project_dict[project_0] == 123
Show we can use projects in sets.
test_hash
python
ApeWorX/ape
tests/functional/test_project.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_project.py
Apache-2.0
def test_lookup_same_source_id_as_local_project(self, project, tmp_project): """ Tests against a bug where if the source ID of the project matched a file in the local project, it would mistakenly return the path to the local file instead of the project's file. """ source_id = project.contracts["ContractA"].source_id path = project.sources.lookup(source_id) assert path.is_file(), "Test path does not exist." cfg = {"contracts_folder": project.config.contracts_folder} with Project.create_temporary_project(config_override=cfg) as other_tmp_project: new_source = other_tmp_project.path / source_id new_source.parent.mkdir(parents=True, exist_ok=True) new_source.write_text(path.read_text(encoding="utf8"), encoding="utf8") actual = other_tmp_project.sources.lookup(source_id) assert actual is not None expected = other_tmp_project.path / source_id assert actual == expected
Tests against a bug where if the source ID of the project matched a file in the local project, it would mistakenly return the path to the local file instead of the project's file.
test_lookup_same_source_id_as_local_project
python
ApeWorX/ape
tests/functional/test_project.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_project.py
Apache-2.0
def test_lookup_missing_contracts_prefix(self, project_with_source_files_contract): """ Show we can exclude the `contracts/` prefix in a source ID. """ project = project_with_source_files_contract actual_from_str = project.sources.lookup("ContractA.sol") actual_from_path = project.sources.lookup(Path("ContractA.sol")) expected = project.contracts_folder / "ContractA.sol" assert actual_from_str == actual_from_path == expected assert actual_from_str.is_absolute() assert actual_from_path.is_absolute()
Show we can exclude the `contracts/` prefix in a source ID.
test_lookup_missing_contracts_prefix
python
ApeWorX/ape
tests/functional/test_project.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_project.py
Apache-2.0
def test_chain_id_from_ethereum_base_provider_is_cached(mock_web3, ethereum, eth_tester_provider): """ Simulated chain ID from a plugin (using base-ethereum class) to ensure is also cached. """ def make_request(rpc, arguments): if rpc == "eth_chainId": return {"result": 11155111} # Sepolia return eth_tester_provider.make_request(rpc, arguments) mock_web3.provider.make_request.side_effect = make_request class PluginProvider(Web3Provider): def connect(self): return def disconnect(self): return provider = PluginProvider(name="sim", network=ethereum.sepolia) provider._web3 = mock_web3 assert provider.chain_id == 11155111 # Unset to web3 to prove it does not check it again (else it would fail). provider._web3 = None assert provider.chain_id == 11155111
Simulated chain ID from a plugin (using base-ethereum class) to ensure is also cached.
test_chain_id_from_ethereum_base_provider_is_cached
python
ApeWorX/ape
tests/functional/test_provider.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_provider.py
Apache-2.0
def test_get_contract_logs_multiple_accounts_for_address( chain, contract_instance, owner, eth_tester_provider ): """ Tests the condition when you pass in multiple AddressAPI objects during an address-topic search. """ contract_instance.logAddressArray(sender=owner) # Create logs block = chain.blocks.height log_filter = LogFilter.from_event( event=contract_instance.EventWithAddressArray, search_topics={"some_address": [owner, contract_instance]}, addresses=[contract_instance, owner], start_block=block, stop_block=block, ) logs = [log for log in eth_tester_provider.get_contract_logs(log_filter)] assert len(logs) >= 1 assert logs[-1]["some_address"] == owner.address
Tests the condition when you pass in multiple AddressAPI objects during an address-topic search.
test_get_contract_logs_multiple_accounts_for_address
python
ApeWorX/ape
tests/functional/test_provider.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_provider.py
Apache-2.0
def test_set_timestamp_to_same_time(eth_tester_provider): """ Eth tester normally fails when setting the timestamp to the same time. However, in Ape, we treat it as a no-op and let it pass. """ expected = eth_tester_provider.get_block("pending").timestamp eth_tester_provider.set_timestamp(expected) actual = eth_tester_provider.get_block("pending").timestamp assert actual == expected
Eth tester normally fails when setting the timestamp to the same time. However, in Ape, we treat it as a no-op and let it pass.
test_set_timestamp_to_same_time
python
ApeWorX/ape
tests/functional/test_provider.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_provider.py
Apache-2.0
def test_set_timestamp_handle_same_time_race_condition(mocker, eth_tester_provider): """ Ensures that when we get an error saying the timestamps are the same, we ignore it and treat it as a noop. This handles the race condition when the block advances after ``set_timestamp`` has been called but before the operation completes. """ def side_effect(*args, **kwargs): raise ValidationError( "timestamp must be strictly later than parent, " "but is 0 seconds before.\n" "- child : 0\n" "- parent : 0." ) mocker.patch.object(eth_tester_provider.evm_backend, "time_travel", side_effect=side_effect) eth_tester_provider.set_timestamp(123)
Ensures that when we get an error saying the timestamps are the same, we ignore it and treat it as a noop. This handles the race condition when the block advances after ``set_timestamp`` has been called but before the operation completes.
test_set_timestamp_handle_same_time_race_condition
python
ApeWorX/ape
tests/functional/test_provider.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_provider.py
Apache-2.0
def test_make_request_not_exists_dev_nodes(eth_tester_provider, mock_web3, msg): """ Handle an issue found from Base-sepolia where not-implemented RPCs caused HTTPErrors. """ real_web3 = eth_tester_provider._web3 mock_web3.eth = real_web3.eth def custom_make_request(rpc, params): if rpc == "ape_thisDoesNotExist": return {"error": {"message": msg}} return real_web3.provider.make_request(rpc, params) mock_web3.provider.make_request.side_effect = custom_make_request eth_tester_provider._web3 = mock_web3 try: with pytest.raises( APINotImplementedError, match="RPC method 'ape_thisDoesNotExist' is not implemented by this node instance.", ): eth_tester_provider.make_request("ape_thisDoesNotExist") finally: eth_tester_provider._web3 = real_web3
Handle an issue found from Base-sepolia where not-implemented RPCs caused HTTPErrors.
test_make_request_not_exists_dev_nodes
python
ApeWorX/ape
tests/functional/test_provider.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_provider.py
Apache-2.0
def test_make_request_handles_http_error_method_not_allowed(eth_tester_provider, mock_web3): """ Simulate what *most* of the dev providers do, like hardhat, anvil, and ganache. """ real_web3 = eth_tester_provider._web3 mock_web3.eth = real_web3.eth def custom_make_request(rpc, params): if rpc == "ape_thisDoesNotExist": raise HTTPError("Client error: Method Not Allowed") return real_web3.provider.make_request(rpc, params) mock_web3.provider.make_request.side_effect = custom_make_request eth_tester_provider._web3 = mock_web3 try: with pytest.raises( APINotImplementedError, match="RPC method 'ape_thisDoesNotExist' is not implemented by this node instance.", ): eth_tester_provider.make_request("ape_thisDoesNotExist") finally: eth_tester_provider._web3 = real_web3
Simulate what *most* of the dev providers do, like hardhat, anvil, and ganache.
test_make_request_handles_http_error_method_not_allowed
python
ApeWorX/ape
tests/functional/test_provider.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_provider.py
Apache-2.0
def test_new_when_web3_provider_uri_set(): """ Tests against a confusing case where having an env var $WEB3_PROVIDER_URI caused web3.py to only ever use that RPC URL regardless of what was said in Ape's --network or config. Now, we raise an error to avoid having users think Ape's network system is broken. """ os.environ[WEB3_PROVIDER_URI_ENV_VAR_NAME] = "TEST" expected = ( rf"Ape does not support Web3\.py's environment variable " rf"\${WEB3_PROVIDER_URI_ENV_VAR_NAME}\. If you are using this environment " r"variable name incidentally, please use a different name\. If you are " r"trying to set the network in Web3\.py, please use Ape's `ape-config\.yaml` " r"or `--network` option instead\." ) class MyProvider(Web3Provider): def connect(self): raise NotImplementedError() def disconnect(self): raise NotImplementedError() try: with pytest.raises(ProviderError, match=expected): _ = MyProvider(data_folder=None, name=None, network=None) finally: if WEB3_PROVIDER_URI_ENV_VAR_NAME in os.environ: del os.environ[WEB3_PROVIDER_URI_ENV_VAR_NAME]
Tests against a confusing case where having an env var $WEB3_PROVIDER_URI caused web3.py to only ever use that RPC URL regardless of what was said in Ape's --network or config. Now, we raise an error to avoid having users think Ape's network system is broken.
test_new_when_web3_provider_uri_set
python
ApeWorX/ape
tests/functional/test_provider.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_provider.py
Apache-2.0
def test_provider_not_supports_get_storage( get_contract_type, owner, vyper_contract_instance, ethereum, chain, networks ): """ The get storage slot RPC is required to detect this proxy, so it won't work on EthTester provider. However, we can make sure that it doesn't try to call `get_storage()` more than once. """ class MyProvider(LocalProvider): times_get_storage_was_called: int = 0 def get_storage( # type: ignore[empty-body] self, address: "AddressType", slot: int, block_id: Optional["BlockID"] = None ) -> "HexBytes": self.times_get_storage_was_called += 1 raise NotImplementedError() my_provider = MyProvider(name="test", network=ethereum.local) my_provider._web3 = chain.provider._web3 _type = get_contract_type("beacon") beacon_contract = ContractContainer(_type) target = vyper_contract_instance.address beacon_instance = owner.deploy(beacon_contract, target) beacon = beacon_instance.address _type = get_contract_type("BeaconProxy") contract = ContractContainer(_type) contract_instance = owner.deploy(contract, beacon, HexBytes("")) # Ensure not already cached. if contract_instance.address in chain.contracts.proxy_infos: del chain.contracts.proxy_infos[contract_instance.address] init_provider = networks.active_provider networks.active_provider = my_provider try: actual = ethereum.get_proxy_info(contract_instance.address) finally: networks.active_provider = init_provider assert actual is None # Because of provider. assert my_provider.times_get_storage_was_called == 1
The get storage slot RPC is required to detect this proxy, so it won't work on EthTester provider. However, we can make sure that it doesn't try to call `get_storage()` more than once.
test_provider_not_supports_get_storage
python
ApeWorX/ape
tests/functional/test_proxy.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_proxy.py
Apache-2.0
def test_decode_logs_not_checksummed_addresses(owner, contract_instance, assert_log_values): """ If an RPC returns non-checksummed logs with non-checksummed addresses, show we can still decode them. """ start_number = contract_instance.myNumber() tx = contract_instance.setNumber(1, sender=owner) assert len(tx.logs) == 1 # Hack to make the address lower-case. tx.logs[0]["address"] = tx.logs[0]["address"].lower() events = tx.decode_logs() assert len(events) == 1 assert_log_values(events[0], 1, start_number)
If an RPC returns non-checksummed logs with non-checksummed addresses, show we can still decode them.
test_decode_logs_not_checksummed_addresses
python
ApeWorX/ape
tests/functional/test_receipt.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_receipt.py
Apache-2.0
def test_track_coverage(deploy_receipt, mocker): """ Show that deploy receipts are not tracked. """ mock_runner = mocker.MagicMock() mock_tracker = mocker.MagicMock() mock_runner.coverage_tracker = mock_tracker original = ManagerAccessMixin._test_runner ManagerAccessMixin._test_runner = mock_runner deploy_receipt.track_coverage() assert mock_runner.track_coverage.call_count == 0 ManagerAccessMixin._test_runner = original
Show that deploy receipts are not tracked.
test_track_coverage
python
ApeWorX/ape
tests/functional/test_receipt.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_receipt.py
Apache-2.0
def test_return_value(owner, vyper_contract_instance): """ ``.return_value`` still works when using EthTester provider! It works by using eth_call to get the result rather than tracing-RPCs. """ vyper_contract_instance.loadArrays(sender=owner) receipt = vyper_contract_instance.getNestedArrayMixedDynamic.transact(sender=owner) actual = receipt.return_value assert len(actual) == 5 assert actual[1][1] == [[0], [0, 1], [0, 1, 2]]
``.return_value`` still works when using EthTester provider! It works by using eth_call to get the result rather than tracing-RPCs.
test_return_value
python
ApeWorX/ape
tests/functional/test_receipt.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_receipt.py
Apache-2.0
def test_revert_info_context(owner, reverts_contract_instance): """ Shows no two revert info objects are the same instance. """ rev = reverts() with rev as rev0: reverts_contract_instance.revertStrings(0, sender=owner) with rev as rev1: reverts_contract_instance.revertStrings(1, sender=owner) assert rev0.value.revert_message != rev1.value.revert_message
Shows no two revert info objects are the same instance.
test_revert_info_context
python
ApeWorX/ape
tests/functional/test_reverts_context_manager.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_reverts_context_manager.py
Apache-2.0
def test_revert_error_from_container_with_expected_values( error_contract_container, error_contract, not_owner ): """ Test matching a revert custom Solidity error using the container instead of an instance, so the specific contract instance is not checked, only the ABI is. This is required for proper deploy-txn checks. """ with reverts(error_contract_container.Unauthorized, error_inputs={"addr": not_owner.address}): error_contract.withdraw(sender=not_owner)
Test matching a revert custom Solidity error using the container instead of an instance, so the specific contract instance is not checked, only the ABI is. This is required for proper deploy-txn checks.
test_revert_error_from_container_with_expected_values
python
ApeWorX/ape
tests/functional/test_reverts_context_manager.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_reverts_context_manager.py
Apache-2.0
def test_revert_unexpected_error(error_contract, not_owner): """ Test when given a different error type than what was raised. """ expected = "Expected error 'OtherError' but was 'Unauthorized'" with pytest.raises(AssertionError, match=expected): with reverts(error_contract.OtherError): error_contract.withdraw(sender=not_owner)
Test when given a different error type than what was raised.
test_revert_unexpected_error
python
ApeWorX/ape
tests/functional/test_reverts_context_manager.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_reverts_context_manager.py
Apache-2.0
def test_revert_error_unexpected_inputs(error_contract, owner, not_owner): """ Test matching a revert custom Solidity error with unexpected inputs. """ expected = ( rf"Expected input 'addr' to be '{owner.address}' but was '{not_owner.address}'\." r"\nExpected input 'counter' to be '321' but was '123'\." ) with pytest.raises(AssertionError, match=expected): with reverts(error_contract.Unauthorized, addr=owner.address, counter=321): error_contract.withdraw(sender=not_owner)
Test matching a revert custom Solidity error with unexpected inputs.
test_revert_error_unexpected_inputs
python
ApeWorX/ape
tests/functional/test_reverts_context_manager.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_reverts_context_manager.py
Apache-2.0
def test_revert_fails(owner, reverts_contract_instance): """ Test that ``AssertionError`` is raised if the supplied revert reason does not match the actual revert reason. """ with pytest.raises(AssertionError): with reverts("one"): reverts_contract_instance.revertStrings(0, sender=owner)
Test that ``AssertionError`` is raised if the supplied revert reason does not match the actual revert reason.
test_revert_fails
python
ApeWorX/ape
tests/functional/test_reverts_context_manager.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_reverts_context_manager.py
Apache-2.0
def test_revert_pattern_fails(owner, reverts_contract_instance): """ Test that ``AssertionError`` is raised if the actual revert reason does not match the supplied revert pattern. """ with pytest.raises(AssertionError): with reverts(re.compile(r"[^zero]+")): reverts_contract_instance.revertStrings(0, sender=owner)
Test that ``AssertionError`` is raised if the actual revert reason does not match the supplied revert pattern.
test_revert_pattern_fails
python
ApeWorX/ape
tests/functional/test_reverts_context_manager.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_reverts_context_manager.py
Apache-2.0
def test_revert_partial_fails(owner, reverts_contract_instance): """ Test that ``AssertionError`` is raised if the supplied revert reason does not match the actual revert reason exactly. """ with pytest.raises(AssertionError): with reverts("ze"): reverts_contract_instance.revertStrings(0, sender=owner)
Test that ``AssertionError`` is raised if the supplied revert reason does not match the actual revert reason exactly.
test_revert_partial_fails
python
ApeWorX/ape
tests/functional/test_reverts_context_manager.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_reverts_context_manager.py
Apache-2.0
def test_signable_message_module(signable_message): """ At the time of writing this, SignableMessage is a borrowed construct from `eth_account.messages`. We are changing the module manually so we are testing that it shows Ape's now. """ actual = signable_message.__module__ expected = "ape.types.signatures" assert actual == expected # Also show the 404-causing line in the __doc__ was fixed. assert "EIP-191_" not in signable_message.__doc__ assert "EIP-191" in signable_message.__doc__
At the time of writing this, SignableMessage is a borrowed construct from `eth_account.messages`. We are changing the module manually so we are testing that it shows Ape's now.
test_signable_message_module
python
ApeWorX/ape
tests/functional/test_signatures.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_signatures.py
Apache-2.0
def test_verbosity(self, mocker): """ Show it returns the same as pytest_config's. """ pytest_cfg = mocker.MagicMock() pytest_cfg.option.verbose = False wrapper = ConfigWrapper(pytest_cfg) assert wrapper.verbosity is False
Show it returns the same as pytest_config's.
test_verbosity
python
ApeWorX/ape
tests/functional/test_test.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_test.py
Apache-2.0
def test_verbosity_when_no_capture(self, mocker): """ Shows we enable verbose output when no-capture is set. """ def get_opt(name: str): return "no" if name == "capture" else None pytest_cfg = mocker.MagicMock() pytest_cfg.option.verbose = False # Start off as False pytest_cfg.getoption.side_effect = get_opt wrapper = ConfigWrapper(pytest_cfg) assert wrapper.verbosity is True
Shows we enable verbose output when no-capture is set.
test_verbosity_when_no_capture
python
ApeWorX/ape
tests/functional/test_test.py
https://github.com/ApeWorX/ape/blob/master/tests/functional/test_test.py
Apache-2.0