Skip to content

Commit

Permalink
⚡ update!
Browse files Browse the repository at this point in the history
Signed-off-by: Harmouch101 <[email protected]>
  • Loading branch information
wiseaidev committed Mar 8, 2022
1 parent 0da57af commit 0b74c14
Show file tree
Hide file tree
Showing 51 changed files with 190 additions and 221 deletions.
4 changes: 2 additions & 2 deletions docs/v4_migration.rst
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ printing out new block hashes as they appear:
.. code-block:: python
>>> def new_block_callback(block_hash):
... print "New Block: {0}".format(block_hash)
... print(f"New Block: {block_hash}")
...
>>> new_block_filter = web3.eth.filter('latest')
>>> new_block_filter.watch(new_block_callback)
Expand All @@ -79,7 +79,7 @@ In v4, that same logic:
>>> new_block_filter = web3.eth.filter('latest')
>>> for block_hash in new_block_filter.get_new_entries():
... print("New Block: {}".format(block_hash))
... print(f"New Block: {block_hash}")
The caller is responsible for polling the results from ``get_new_entries()``.
See :ref:`asynchronous_filters` for examples of filter-event handling with web3 v4.
Expand Down
4 changes: 2 additions & 2 deletions docs/web3.eth.rst
Original file line number Diff line number Diff line change
Expand Up @@ -364,7 +364,7 @@ The following methods are available on the ``web3.eth`` namespace.
assert rlp_account == HexaryTrie.get_from_proof(
root, trie_key, format_proof_nodes(proof.accountProof)
), "Failed to verify account proof {}".format(proof.address)
), f"Failed to verify account proof {proof.address}"
for storage_proof in proof.storageProof:
trie_key = keccak(pad_bytes(b'\x00', 32, storage_proof.key))
Expand All @@ -376,7 +376,7 @@ The following methods are available on the ``web3.eth`` namespace.
assert rlp_value == HexaryTrie.get_from_proof(
root, trie_key, format_proof_nodes(storage_proof.proof)
), "Failed to verify storage proof {}".format(storage_proof.key)
), f"Failed to verify storage proof {storage_proof.key}"
return True
Expand Down
12 changes: 6 additions & 6 deletions ethpm/contract.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ def __init__(self, address: bytes, **kwargs: Any) -> None:
)
validate_address(address)
# type ignored to allow for undefined **kwargs on `Contract` base class __init__
super(LinkableContract, self).__init__(address=address, **kwargs) # type: ignore
super().__init__(address=address, **kwargs) # type: ignore

@classmethod
def factory(
Expand All @@ -69,15 +69,15 @@ def factory(
if not is_prelinked_bytecode(to_bytes(hexstr=bytecode), dep_link_refs):
needs_bytecode_linking = True
kwargs = assoc(kwargs, "needs_bytecode_linking", needs_bytecode_linking)
return super(LinkableContract, cls).factory(w3, class_name, **kwargs)
return super().factory(w3, class_name, **kwargs)

@classmethod
def constructor(cls, *args: Any, **kwargs: Any) -> ContractConstructor:
if cls.needs_bytecode_linking:
raise BytecodeLinkingError(
"Contract cannot be deployed until its bytecode is linked."
)
return super(LinkableContract, cls).constructor(*args, **kwargs)
return super().constructor(*args, **kwargs)

@classmethod
def link_bytecode(cls, attr_dict: Dict[str, str]) -> Type["LinkableContract"]:
Expand Down Expand Up @@ -111,7 +111,7 @@ def validate_attr_dict(self, attr_dict: Dict[str, str]) -> None:
"""
Validates that ContractType keys in attr_dict reference existing manifest ContractTypes.
"""
attr_dict_names = list(attr_dict.keys())
attr_dict_names = attr_dict.keys()

if not self.unlinked_references and not self.linked_references:
raise BytecodeLinkingError(
Expand All @@ -122,8 +122,8 @@ def validate_attr_dict(self, attr_dict: Dict[str, str]) -> None:
linked_refs = self.linked_references or ({},)
all_link_refs = unlinked_refs + linked_refs

all_link_names = [ref["name"] for ref in all_link_refs if ref]
if set(attr_dict_names) != set(all_link_names):
all_link_names = {ref["name"] for ref in all_link_refs if ref}
if attr_dict_names != all_link_names:
raise BytecodeLinkingError(
"All link references must be defined when calling "
"`link_bytecode` on a contract factory."
Expand Down
2 changes: 1 addition & 1 deletion ethpm/tools/builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -498,7 +498,7 @@ def normalize_compiler_output(compiler_output: Dict[str, Any]) -> Dict[str, Any]
]
paths, names = zip(*paths_and_names)
if len(names) != len(set(names)):
duplicates = set([name for name in names if names.count(name) > 1])
duplicates = {name for name in names if names.count(name) > 1}
raise ManifestBuildingError(
f"Duplicate contract types: {duplicates} were found in the compiler output."
)
Expand Down
12 changes: 6 additions & 6 deletions ethpm/validation/manifest.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,11 +66,11 @@ def _load_schema_data() -> Dict[str, Any]:


def extract_contract_types_from_deployments(deployment_data: List[Any]) -> Set[str]:
contract_types = set(
contract_types = {
deployment["contractType"]
for chain_deployments in deployment_data
for deployment in chain_deployments.values()
)
}
return contract_types


Expand Down Expand Up @@ -108,11 +108,11 @@ def validate_manifest_deployments(manifest: Dict[str, Any]) -> None:
"""
Validate that a manifest's deployments contracts reference existing contractTypes.
"""
if set(("contractTypes", "deployments")).issubset(manifest):
all_contract_types = list(manifest["contractTypes"].keys())
all_deployments = list(manifest["deployments"].values())
if {"contractTypes", "deployments"}.issubset(manifest):
all_contract_types = manifest["contractTypes"].keys()
all_deployments = manifest["deployments"].values()
all_deployment_names = extract_contract_types_from_deployments(all_deployments)
missing_contract_types = set(all_deployment_names).difference(
missing_contract_types = all_deployment_names.difference(
all_contract_types
)
if missing_contract_types:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ def test_finds_function_with_matching_args(w3, arguments, expected_types):
abi = Contract._find_matching_fn_abi('a', arguments)
assert abi['name'] == 'a'
assert len(abi['inputs']) == len(expected_types)
assert set(get_abi_input_types(abi)) == set(expected_types)
assert get_abi_input_types(abi) == expected_types


def test_finds_function_with_matching_args_deprecation_warning(w3):
Expand All @@ -160,7 +160,7 @@ def test_finds_function_with_matching_args_deprecation_warning(w3):
abi = Contract._find_matching_fn_abi('a', [''])
assert abi['name'] == 'a'
assert len(abi['inputs']) == len(['bytes32'])
assert set(get_abi_input_types(abi)) == set(['bytes32'])
assert get_abi_input_types(abi) == ['bytes32']


def test_error_when_duplicate_match(w3):
Expand Down Expand Up @@ -193,4 +193,4 @@ def test_strict_finds_function_with_matching_args(w3_strict_abi, arguments, expe
abi = Contract._find_matching_fn_abi('a', arguments)
assert abi['name'] == 'a'
assert len(abi['inputs']) == len(expected_types)
assert set(get_abi_input_types(abi)) == set(expected_types)
assert get_abi_input_types(abi) == expected_types
11 changes: 6 additions & 5 deletions tests/core/filtering/test_contract_on_event_filtering.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,23 +80,24 @@ def test_on_sync_filter_with_event_name_and_single_argument(
'arg1': 2,
}}])

txn_hashes = []
txn_hashes = set()
event_id = emitter_event_ids.LogTripleWithIndex
txn_hashes.append(
txn_hashes.add(
emitter.functions.logTriple(event_id, 2, 1, 3).transact()
)
txn_hashes.append(
txn_hashes.add(
emitter.functions.logTriple(event_id, 1, 2, 3).transact()
)
txn_hashes.append(
txn_hashes.add(
emitter.functions.logTriple(event_id, 12345, 2, 54321).transact()
)
for txn_hash in txn_hashes:
wait_for_transaction(w3, txn_hash)

seen_logs = event_filter.get_new_entries()
txn_hashes.pop()
assert len(seen_logs) == 2
assert {log['transactionHash'] for log in seen_logs} == set(txn_hashes[1:])
assert set((log['transactionHash'] for log in seen_logs)) == txn_hashes


@pytest.mark.parametrize('call_as_instance', (True, False))
Expand Down
12 changes: 6 additions & 6 deletions tests/core/filtering/test_filter_against_transaction_logs.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ def test_sync_filter_against_log_events(w3_empty,

txn_filter = w3.eth.filter({})

txn_hashes = []
txn_hashes.append(emitter.functions.logNoArgs(emitter_event_ids.LogNoArguments).transact())
txn_hashes = set()
txn_hashes.add(emitter.functions.logNoArgs(emitter_event_ids.LogNoArguments).transact())

for txn_hash in txn_hashes:
wait_for_transaction(w3, txn_hash)
Expand All @@ -34,7 +34,7 @@ def test_sync_filter_against_log_events(w3_empty,

seen_logs = txn_filter.get_new_entries()

assert set(txn_hashes) == set(log['transactionHash'] for log in seen_logs)
assert txn_hashes == set((log['transactionHash'] for log in seen_logs))


@pytest.mark.skip(reason="fixture 'w3_empty' not found")
Expand All @@ -51,9 +51,9 @@ def test_async_filter_against_log_events(w3_empty,
txn_filter = w3.eth.filter({})
txn_filter.watch(seen_logs.append)

txn_hashes = []
txn_hashes = set()

txn_hashes.append(emitter.functions.logNoArgs(emitter_event_ids.LogNoArguments).transact())
txn_hashes.add(emitter.functions.logNoArgs(emitter_event_ids.LogNoArguments).transact())

for txn_hash in txn_hashes:
wait_for_transaction(w3, txn_hash)
Expand All @@ -64,4 +64,4 @@ def test_async_filter_against_log_events(w3_empty,

txn_filter.stop_watching(30)

assert set(txn_hashes) == set(log['transactionHash'] for log in seen_logs)
assert txn_hashes == set((log['transactionHash'] for log in seen_logs))
5 changes: 1 addition & 4 deletions tests/core/middleware/test_fixture_middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,7 @@

class DummyProvider(BaseProvider):
def make_request(self, method, params):
raise NotImplementedError("Cannot make request for {0}:{1}".format(
method,
params,
))
raise NotImplementedError(f"Cannot make request for {method}:{params}")


@pytest.fixture
Expand Down
2 changes: 1 addition & 1 deletion tests/core/middleware/test_simple_cache_middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ def result_cb(method, params):
def test_simple_cache_middleware_does_not_cache_error_responses(w3_base):
w3 = w3_base
w3.middleware_onion.add(construct_error_generator_middleware({
'fake_endpoint': lambda *_: 'msg-{0}'.format(str(uuid.uuid4())),
'fake_endpoint': lambda *_: f'msg-{uuid.uuid4()}',
}))

w3.middleware_onion.add(construct_simple_cache_middleware(
Expand Down
2 changes: 1 addition & 1 deletion tests/core/middleware/test_time_based_cache_middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ def test_time_based_cache_middleware_does_not_cache_error_response(
counter = itertools.count()

def mk_error(method, params):
return "error-number-{0}".format(next(counter))
return f"error-number-{next(counter)}"

w3.middleware_onion.add(construct_error_generator_middleware({
'fake_endpoint': mk_error,
Expand Down
5 changes: 1 addition & 4 deletions tests/core/middleware/test_transaction_signing.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,10 +83,7 @@

class DummyProvider(BaseProvider):
def make_request(self, method, params):
raise NotImplementedError("Cannot make request for {0}:{1}".format(
method,
params,
))
raise NotImplementedError(f"Cannot make request for {method}:{params}")


@pytest.fixture()
Expand Down
2 changes: 1 addition & 1 deletion tests/core/providers/test_ipc_provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
@pytest.fixture
def jsonrpc_ipc_pipe_path():
with tempfile.TemporaryDirectory() as temp_dir:
ipc_path = os.path.join(temp_dir, '{0}.ipc'.format(uuid.uuid4()))
ipc_path = os.path.join(temp_dir, f'{uuid.uuid4()}.ipc')
try:
yield ipc_path
finally:
Expand Down
4 changes: 2 additions & 2 deletions tests/core/providers/test_websocket_provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ async def empty_server(websocket, path):
def w3(open_port, start_websocket_server):
# need new event loop as the one used by server is already running
event_loop = asyncio.new_event_loop()
endpoint_uri = 'ws://127.0.0.1:{}'.format(open_port)
endpoint_uri = f'ws://127.0.0.1:{open_port}'
event_loop.run_until_complete(wait_for_ws(endpoint_uri))
provider = WebsocketProvider(endpoint_uri, websocket_timeout=0.01)
return Web3(provider)
Expand All @@ -68,6 +68,6 @@ def test_websocket_provider_timeout(w3):

def test_restricted_websocket_kwargs():
invalid_kwargs = {'uri': 'ws://127.0.0.1:8546'}
re_exc_message = r'.*found: {0}*'.format(set(invalid_kwargs.keys()))
re_exc_message = fr'.*found: {set(invalid_kwargs)}*'
with pytest.raises(ValidationError, match=re_exc_message):
WebsocketProvider(websocket_kwargs=invalid_kwargs)
14 changes: 7 additions & 7 deletions tests/core/utilities/test_abi_filtering_by_argument_name.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,14 +48,14 @@
@pytest.mark.parametrize(
'argument_names,expected',
(
([], ['func_1', 'func_2', 'func_3', 'func_4']),
(['a'], ['func_2', 'func_3', 'func_4']),
(['a', 'c'], ['func_4']),
(['c'], ['func_4']),
(['b'], ['func_3', 'func_4']),
([], {'func_1', 'func_2', 'func_3', 'func_4'}),
(['a'], {'func_2', 'func_3', 'func_4'}),
(['a', 'c'], {'func_4'}),
(['c'], {'func_4'}),
(['b'], {'func_3', 'func_4'}),
)
)
def test_filter_by_arguments_1(argument_names, expected):
actual_matches = filter_by_argument_name(argument_names, ABI)
function_names = [match['name'] for match in actual_matches]
assert set(function_names) == set(expected)
function_names = {match['name'] for match in actual_matches}
assert function_names == expected
10 changes: 5 additions & 5 deletions tests/ethpm/_utils/test_contract_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,11 +58,11 @@ def test_validate_contract_name_invalidates(name):
@pytest.mark.parametrize(
"contract_data,expected_kwargs",
(
({"abi": ""}, ["abi"]),
({"deploymentBytecode": {"bytecode": ""}}, ["bytecode"]),
({"abi": ""}, {"abi"}),
({"deploymentBytecode": {"bytecode": ""}}, {"bytecode"}),
(
{"abi": "", "runtimeBytecode": {"bytecode": ""}},
["abi", "bytecode_runtime"],
{"abi", "bytecode_runtime"},
),
(
{
Expand All @@ -74,13 +74,13 @@ def test_validate_contract_name_invalidates(name):
],
},
},
["abi", "bytecode", "unlinked_references"],
{"abi", "bytecode", "unlinked_references"},
),
),
)
def test_generate_contract_factory_kwargs(contract_data, expected_kwargs):
contract_factory = generate_contract_factory_kwargs(contract_data)
assert set(contract_factory.keys()) == set(expected_kwargs)
assert contract_factory.keys() == expected_kwargs


def test_validate_w3_instance_validates(w3):
Expand Down
8 changes: 4 additions & 4 deletions tests/ethpm/validation/test_manifest.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,17 +78,17 @@ def test_validate_deployments_without_deployment(manifest_with_no_deployments):
@pytest.mark.parametrize(
"data,expected",
(
({}, set()),
([{"some": {"contractType": "one"}}], set(["one"])),
([], {}),
([{"some": {"contractType": "one"}}], {"one"}),
(
[{"some": {"contractType": "one"}, "other": {"contractType": "two"}}],
set(["one", "two"]),
{"one", "two"},
),
),
)
def test_extract_contract_types_from_deployments(data, expected):
actual = extract_contract_types_from_deployments(data)
assert actual == expected
assert actual == set(expected)


def test_validate_manifest_version_validates_version_three_string():
Expand Down
14 changes: 6 additions & 8 deletions tests/integration/generate_fixtures/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,11 +183,8 @@ def get_geth_process(geth_binary,
output, errors = proc.communicate()
print(
"Geth Process Exited:\n"
"stdout:{0}\n\n"
"stderr:{1}\n\n".format(
to_text(output),
to_text(errors),
)
f"stdout:{to_text(output)}\n\n"
f"stderr:{to_text(errors)}\n\n"
)


Expand Down Expand Up @@ -235,12 +232,13 @@ def mine_transaction_hash(w3, txn_hash):


def deploy_contract(w3, name, factory):
name = name.upper()
w3.geth.personal.unlock_account(w3.eth.coinbase, KEYFILE_PW)
deploy_txn_hash = factory.constructor().transact({'from': w3.eth.coinbase})
print('{0}_CONTRACT_DEPLOY_HASH: '.format(name.upper()), deploy_txn_hash)
print(f'{name}_CONTRACT_DEPLOY_HASH: {deploy_txn_hash}')
deploy_receipt = mine_transaction_hash(w3, deploy_txn_hash)
print('{0}_CONTRACT_DEPLOY_TRANSACTION_MINED'.format(name.upper()))
print(f'{name}_CONTRACT_DEPLOY_TRANSACTION_MINED')
contract_address = deploy_receipt['contractAddress']
assert is_checksum_address(contract_address)
print('{0}_CONTRACT_ADDRESS:'.format(name.upper()), contract_address)
print(f'{name}_CONTRACT_ADDRESS: {contract_address}')
return deploy_receipt
Loading

0 comments on commit 0b74c14

Please sign in to comment.