Skip to content

Commit

Permalink
Lint tests
Browse files Browse the repository at this point in the history
  • Loading branch information
fjarri committed Dec 31, 2023
1 parent 6156411 commit ef44dc3
Show file tree
Hide file tree
Showing 14 changed files with 145 additions and 139 deletions.
3 changes: 2 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -160,4 +160,5 @@ target-version = "py38"

[tool.isort]
profile = "black"
src_paths = ["pons", "test"]
src_paths = ["pons", "tests"]
known_first_party = ["pons"]
4 changes: 2 additions & 2 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

@pytest.fixture
def test_provider():
yield TesterProvider(root_balance=Amount.ether(100))
return TesterProvider(root_balance=Amount.ether(100))


@pytest.fixture
Expand All @@ -17,7 +17,7 @@ async def session(test_provider):

@pytest.fixture
def root_signer(test_provider):
yield test_provider.root
return test_provider.root


@pytest.fixture
Expand Down
29 changes: 29 additions & 0 deletions tests/ruff.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# Extend the `pyproject.toml` file in the parent directory.
extend = "../pyproject.toml"

flake8-pytest-style.fixture-parentheses = false

ignore = [
# assert usage is what we do in tests
"S101",
# have to access private members sometimes
"SLF001",
# skipping type annotations for now
"ANN001",
"ANN002",
"ANN003",
"ANN201",
"ANN202",
# no docstrings in tests
"D100",
"D101",
"D102",
"D103",
"D107",
# We need it quite often during RPC and Solidity encoding/decoding
"FBT003",
# Yeah, that's great if your context manager calls are a few characters long
"SIM117",
# Too many false positives in the testing context.
"PLR2004",
]
2 changes: 1 addition & 1 deletion tests/test_abi_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,7 @@ def test_normalization_roundtrip():
assert struct._denormalize(expected_normalized) == value


def check_topic_encode_decode(tp, val, encoded_val, can_be_decoded=True):
def check_topic_encode_decode(tp, val, encoded_val, *, can_be_decoded=True):
assert tp.encode_to_topic(val) == encoded_val
if can_be_decoded:
assert tp.decode_from_topic(encoded_val) == val
Expand Down
57 changes: 31 additions & 26 deletions tests/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,14 +27,14 @@
from pons._abi_types import encode_args, keccak
from pons._client import BadResponseFormat, ProviderError, TransactionFailed
from pons._contract_abi import PANIC_ERROR
from pons._entities import rpc_decode_block, rpc_encode_data
from pons._entities import rpc_encode_data
from pons._provider import RPCError


@pytest.fixture
def compiled_contracts():
path = Path(__file__).resolve().parent / "TestClient.sol"
yield compile_contract_file(path)
return compile_contract_file(path)


@contextmanager
Expand All @@ -60,7 +60,7 @@ async def test_net_version(test_provider, session):

# This is not going to get called
def wrong_net_version():
raise NotImplementedError() # pragma: no cover
raise NotImplementedError # pragma: no cover

# The result should have been cached the first time
with monkeypatched(test_provider, "net_version", wrong_net_version):
Expand All @@ -81,7 +81,7 @@ async def test_eth_chain_id(test_provider, session):

# This is not going to get called
def wrong_chain_id():
raise NotImplementedError() # pragma: no cover
raise NotImplementedError # pragma: no cover

# The result should have been cached the first time
with monkeypatched(test_provider, "eth_chain_id", wrong_chain_id):
Expand Down Expand Up @@ -132,12 +132,13 @@ async def test_wait_for_transaction_receipt(
tx_hash = await session.broadcast_transfer(root_signer, another_signer.address, to_transfer)

# The receipt won't be available until we mine, so the waiting should time out
timeout = 5
start_time = trio.current_time()
with pytest.raises(trio.TooSlowError):
with trio.fail_after(5):
with trio.fail_after(timeout):
receipt = await session.wait_for_transaction_receipt(tx_hash)
end_time = trio.current_time()
assert end_time - start_time == 5
assert end_time - start_time == timeout

# Now let's enable mining while we wait for the receipt
receipt = None
Expand All @@ -147,7 +148,7 @@ async def get_receipt():
receipt = await session.wait_for_transaction_receipt(tx_hash)

async def delayed_enable_mining():
await trio.sleep(5)
await trio.sleep(timeout)
test_provider.enable_auto_mine_transactions()

async with trio.open_nursery() as nursery:
Expand Down Expand Up @@ -197,14 +198,16 @@ async def test_eth_call_decoding_error(session, compiled_contracts, root_signer)
async def test_estimate_deploy(session, compiled_contracts):
compiled_contract = compiled_contracts["BasicContract"]
gas = await session.estimate_deploy(compiled_contract.constructor(1))
assert isinstance(gas, int) and gas > 0
assert isinstance(gas, int)
assert gas > 0


async def test_estimate_transfer(session, root_signer, another_signer):
gas = await session.estimate_transfer(
root_signer.address, another_signer.address, Amount.ether(10)
)
assert isinstance(gas, int) and gas > 0
assert isinstance(gas, int)
assert gas > 0

with pytest.raises(
ProviderError,
Expand All @@ -219,7 +222,8 @@ async def test_estimate_transact(session, compiled_contracts, root_signer):
compiled_contract = compiled_contracts["BasicContract"]
deployed_contract = await session.deploy(root_signer, compiled_contract.constructor(1))
gas = await session.estimate_transact(deployed_contract.method.setState(456))
assert isinstance(gas, int) and gas > 0
assert isinstance(gas, int)
assert gas > 0


async def test_eth_gas_price(session):
Expand Down Expand Up @@ -328,7 +332,7 @@ def mock_get_transaction_receipt(tx_hash_hex):
await session.deploy(root_signer, basic_contract.constructor(0))


async def test_transact(test_provider, session, compiled_contracts, root_signer):
async def test_transact(session, compiled_contracts, root_signer):
basic_contract = compiled_contracts["BasicContract"]

# Normal transact
Expand Down Expand Up @@ -369,21 +373,22 @@ async def test_transact_and_return_events(

deployed_contract = await session.deploy(root_signer, basic_contract.constructor(123))

Event1 = deployed_contract.event.Event1
Event2 = deployed_contract.event.Event2
event1 = deployed_contract.event.Event1
event2 = deployed_contract.event.Event2

results_for = lambda x: {
Event1: [{"value": x}, {"value": x + 1}],
Event2: [{"value": x + 2}, {"value": x + 3}],
}
def results_for(x):
return {
event1: [{"value": x}, {"value": x + 1}],
event2: [{"value": x + 2}, {"value": x + 3}],
}

# Normal operation: one relevant transaction in the block

x = 1
result = await session.transact(
root_signer,
deployed_contract.method.emitMultipleEvents(x),
return_events=[Event1, Event2],
return_events=[event1, event2],
)
assert result == results_for(x)

Expand All @@ -396,7 +401,7 @@ async def test_transact_and_return_events(

async def transact(signer, x):
result = await session.transact(
signer, deployed_contract.method.emitMultipleEvents(x), return_events=[Event1, Event2]
signer, deployed_contract.method.emitMultipleEvents(x), return_events=[event1, event2]
)
results[x] = result

Expand All @@ -415,7 +420,7 @@ async def delayed_enable_mining():
assert results[x2] == results_for(x2)


async def test_get_block(test_provider, session, root_signer, another_signer):
async def test_get_block(session, root_signer, another_signer):
to_transfer = Amount.ether(10)
await session.transfer(root_signer, another_signer.address, to_transfer)

Expand All @@ -438,7 +443,7 @@ async def test_get_block(test_provider, session, root_signer, another_signer):
assert block_info is None


async def test_eth_get_transaction_by_hash(test_provider, session, root_signer, another_signer):
async def test_eth_get_transaction_by_hash(session, root_signer, another_signer):
to_transfer = Amount.ether(1)

tx_hash = await session.broadcast_transfer(root_signer, another_signer.address, to_transfer)
Expand All @@ -451,7 +456,7 @@ async def test_eth_get_transaction_by_hash(test_provider, session, root_signer,


async def test_eth_get_filter_changes_bad_response(test_provider, session, monkeypatch):
monkeypatch.setattr(test_provider, "eth_get_filter_changes", lambda filter_id: {"foo": 1})
monkeypatch.setattr(test_provider, "eth_get_filter_changes", lambda _filter_id: {"foo": 1})

block_filter = await session.eth_new_block_filter()

Expand All @@ -461,7 +466,7 @@ async def test_eth_get_filter_changes_bad_response(test_provider, session, monke
await session.eth_get_filter_changes(block_filter)


async def test_block_filter(test_provider, session, root_signer, another_signer):
async def test_block_filter(session, root_signer, another_signer):
to_transfer = Amount.ether(1)

await session.transfer(root_signer, another_signer.address, to_transfer)
Expand Down Expand Up @@ -871,7 +876,7 @@ async def test_unknown_error_reasons(test_provider, session, compiled_contracts,

# Provider returns an unknown panic code

def eth_estimate_gas(*args, **kwargs):
def eth_estimate_gas(*_args, **_kwargs):
# Invalid selector
data = PANIC_ERROR.selector + encode_args((abi.uint(256), 888))
raise RPCError(RPCErrorCode.EXECUTION_ERROR, "execution reverted", rpc_encode_data(data))
Expand All @@ -882,7 +887,7 @@ def eth_estimate_gas(*args, **kwargs):

# Provider returns an unknown error (a selector not present in the ABI)

def eth_estimate_gas(*args, **kwargs):
def eth_estimate_gas(*_args, **_kwargs):
# Invalid selector
data = b"1234" + encode_args((abi.uint(256), 1))
raise RPCError(RPCErrorCode.EXECUTION_ERROR, "execution reverted", rpc_encode_data(data))
Expand All @@ -895,7 +900,7 @@ def eth_estimate_gas(*args, **kwargs):

# Provider returns an error with an unknown RPC code

def eth_estimate_gas(*args, **kwargs):
def eth_estimate_gas(*_args, **_kwargs):
# Invalid selector
data = PANIC_ERROR.selector + encode_args((abi.uint(256), 0))
raise RPCError(12345, "execution reverted", rpc_encode_data(data))
Expand Down
4 changes: 2 additions & 2 deletions tests/test_compiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
def test_multiple_contracts():
path = Path(__file__).resolve().parent / "TestCompiler.sol"
contracts = compile_contract_file(path, evm_version=EVMVersion.SHANGHAI, optimize=True)
assert list(sorted(contracts)) == ["Contract1", "Contract2"]
assert sorted(contracts) == ["Contract1", "Contract2"]


def test_import_remappings():
Expand All @@ -15,4 +15,4 @@ def test_import_remappings():
contracts = compile_contract_file(
path, import_remappings={"@to_be_remapped": root_path / "test_compiler_subdir"}
)
assert list(sorted(contracts)) == ["Contract1", "Contract2"]
assert sorted(contracts) == ["Contract1", "Contract2"]
16 changes: 9 additions & 7 deletions tests/test_contract.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from collections import namedtuple
from pathlib import Path
from typing import NamedTuple, Tuple

import pytest

Expand All @@ -21,12 +21,11 @@
@pytest.fixture
def compiled_contracts():
path = Path(__file__).resolve().parent / "TestContract.sol"
yield compile_contract_file(path)
return compile_contract_file(path)


def test_abi_declaration(compiled_contracts):
"""Checks that the compiler output is parsed correctly."""

compiled_contract = compiled_contracts["JsonAbiTest"]

cabi = compiled_contract.abi
Expand Down Expand Up @@ -70,7 +69,6 @@ def test_abi_declaration(compiled_contracts):

def test_api_binding(compiled_contracts):
"""Checks that the methods are bound correctly on deploy."""

compiled_contract = compiled_contracts["JsonAbiTest"]

address = Address(b"\xab" * 20)
Expand Down Expand Up @@ -112,9 +110,13 @@ def test_api_binding(compiled_contracts):
)

# We only need a couple of fields
fake_log_entry = namedtuple("fake_log_entry", ["topics", "data", "address"])
class FakeLogEntry(NamedTuple):
data: bytes
address: Address
topics: Tuple[LogTopic, ...]

decoded = event_filter.decode_log_entry(
fake_log_entry(
FakeLogEntry(
address=address,
topics=[LogTopic(abi.uint(256).encode(1)), LogTopic(keccak(b"1234"))],
data=encode_args((abi.bytes(4), b"4567"), (abi.bytes(), b"bytestring")),
Expand All @@ -124,5 +126,5 @@ def test_api_binding(compiled_contracts):

with pytest.raises(ValueError, match="Log entry originates from a different contract"):
decoded = event_filter.decode_log_entry(
fake_log_entry(address=Address(b"\xba" * 20), topics=[], data=b"")
FakeLogEntry(address=Address(b"\xba" * 20), topics=[], data=b"")
)
Loading

0 comments on commit ef44dc3

Please sign in to comment.