Skip to content

Commit 075a67b

Browse files
committed
implemented mario feedback
1 parent b030265 commit 075a67b

File tree

3 files changed

+51
-45
lines changed

3 files changed

+51
-45
lines changed

src/ethereum_test_rpc/rpc.py

Lines changed: 16 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111

1212
from ethereum_test_base_types import Address, Bytes, Hash, to_json
1313
from ethereum_test_types import Transaction
14+
from pytest_plugins.logging import get_logger
1415

1516
from .types import (
1617
EthConfigResponse,
@@ -24,6 +25,7 @@
2425
TransactionByHashResponse,
2526
)
2627

28+
logger = get_logger(__name__)
2729
BlockNumberType = int | Literal["latest", "earliest", "pending"]
2830

2931

@@ -79,14 +81,17 @@ def post_request(
7981
self,
8082
*,
8183
method: str,
82-
params: Any | None = None,
84+
params: List[Any] | None = None,
8385
extra_headers: Dict | None = None,
8486
request_id: int | str | None = None,
8587
timeout: int | None = None,
8688
) -> Any:
8789
"""Send JSON-RPC POST request to the client RPC server at port defined in the url."""
8890
if extra_headers is None:
8991
extra_headers = {}
92+
if params is None:
93+
params = []
94+
9095
assert self.namespace, "RPC namespace not set"
9196

9297
next_request_id_counter = next(self.request_id_counter)
@@ -104,8 +109,7 @@ def post_request(
104109
}
105110
headers = base_header | self.extra_headers | extra_headers
106111

107-
# print(f"Sending RPC request to {self.url}, timeout is set to {timeout}...")
108-
print(f"Sending RPC request, timeout is set to {timeout}...") # don't leak url in logs
112+
logger.debug(f"Sending RPC request, timeout is set to {timeout}...")
109113
response = requests.post(self.url, json=json, headers=headers, timeout=timeout)
110114
response.raise_for_status()
111115
response_json = response.json()
@@ -149,7 +153,7 @@ def config(self, timeout: int | None = None):
149153
try:
150154
response = self.post_request(method="config", timeout=timeout)
151155
if response is None:
152-
print("eth_config request: failed to get response")
156+
logger.warning("eth_config request: failed to get response")
153157
return None
154158
return EthConfigResponse.model_validate(
155159
response, context=self.response_validation_context
@@ -158,7 +162,7 @@ def config(self, timeout: int | None = None):
158162
pprint(e.errors())
159163
raise e
160164
except Exception as e:
161-
print(f"exception occurred when sending JSON-RPC request: {e}")
165+
logger.error(f"exception occurred when sending JSON-RPC request: {e}")
162166
raise e
163167

164168
def chain_id(self) -> int:
@@ -215,7 +219,7 @@ def get_transaction_by_hash(self, transaction_hash: Hash) -> TransactionByHashRe
215219
"""`eth_getTransactionByHash`: Returns transaction details."""
216220
try:
217221
response = self.post_request(
218-
method="getTransactionByHash", params=f"{transaction_hash}"
222+
method="getTransactionByHash", params=[f"{transaction_hash}"]
219223
)
220224
if response is None:
221225
return None
@@ -249,7 +253,7 @@ def send_raw_transaction(
249253
try:
250254
response = self.post_request(
251255
method="sendRawTransaction",
252-
params=f"{transaction_rlp.hex()}",
256+
params=[transaction_rlp.hex()],
253257
request_id=request_id, # noqa: E501
254258
)
255259

@@ -265,7 +269,7 @@ def send_transaction(self, transaction: Transaction) -> Hash:
265269
try:
266270
response = self.post_request(
267271
method="sendRawTransaction",
268-
params=f"{transaction.rlp().hex()}",
272+
params=[transaction.rlp().hex()],
269273
request_id=transaction.metadata_string(), # noqa: E501
270274
)
271275

@@ -423,7 +427,7 @@ def forkchoice_updated(
423427
if payload_attributes is None:
424428
params = [to_json(forkchoice_state)]
425429
else:
426-
params = [to_json(forkchoice_state), to_json(payload_attributes)]
430+
params = [to_json(forkchoice_state), None]
427431

428432
return ForkchoiceUpdateResponse.model_validate(
429433
self.post_request(
@@ -448,7 +452,7 @@ def get_payload(
448452
return GetPayloadResponse.model_validate(
449453
self.post_request(
450454
method=method,
451-
params=f"{payload_id}",
455+
params=[f"{payload_id}"],
452456
),
453457
context=self.response_validation_context,
454458
)
@@ -466,7 +470,7 @@ def get_blobs(
466470
return GetBlobsResponse.model_validate(
467471
self.post_request(
468472
method=method,
469-
params=params,
473+
params=[params],
470474
),
471475
context=self.response_validation_context,
472476
)
@@ -486,4 +490,4 @@ class AdminRPC(BaseRPC):
486490

487491
def add_peer(self, enode: str) -> bool:
488492
"""`admin_addPeer`: Add a peer by enode URL."""
489-
return self.post_request(method="addPeer", params=enode)
493+
return self.post_request(method="addPeer", params=[enode])

src/pytest_plugins/execute/eth_config/eth_config.py

Lines changed: 28 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import pytest
99

1010
from ethereum_test_rpc import EthRPC
11+
from pytest_plugins.logging import get_logger
1112

1213
from .types import NetworkConfigFile
1314

@@ -20,6 +21,8 @@
2021
EXECUTION_CLIENTS = ["besu", "erigon", "geth", "nethermind", "nimbusel", "reth"]
2122
CONSENSUS_CLIENTS = ["grandine", "lighthouse", "lodestar", "nimbus", "prysm", "teku"]
2223

24+
logger = get_logger(__name__)
25+
2326

2427
def pytest_addoption(parser):
2528
"""Add command-line options to pytest."""
@@ -54,10 +57,10 @@ def pytest_addoption(parser):
5457
action="store",
5558
dest="clients",
5659
type=str,
57-
default="besu,erigon,geth,nethermind,reth",
58-
help="Comma-separated list of clients to be tested in majority mode. This flag will be "
59-
"ignored when you pass a value for the network-config-file flag. Default: "
60-
"besu,erigon,geth,nethermind,reth",
60+
default=None,
61+
help="Comma-separated list of clients to be tested in majority mode. Example: "
62+
'"besu,erigon,geth,nethermind,nimbusel,reth"\nIf you do not pass a value, majority mode '
63+
"testing will be disabled.",
6164
)
6265
eth_config_group.addoption(
6366
"--rpc-endpoint",
@@ -97,36 +100,37 @@ def pytest_configure(config: pytest.Config) -> None:
97100
config.network = network_configs.root[network_name] # type: ignore
98101

99102
# prepare majority test mode
100-
# parse clients list
101-
clients.replace(" ", "")
102-
clients = clients.split(",")
103-
for c in clients:
104-
if c not in EXECUTION_CLIENTS:
105-
pytest.exit(f"Unsupported client was passed: {c}")
106-
print(f"Provided client list: {clients}")
107-
108-
# store majority mode configuration
109-
if ".ethpandaops.io" in rpc_endpoint:
110-
print("Ethpandaops RPC detected, toggling majority test on")
111-
config.option.majority_clients = clients # List[str]
103+
# parse clients list if something was passed for it
104+
if clients:
105+
clients.replace(" ", "")
106+
clients = clients.split(",")
107+
for c in clients:
108+
if c not in EXECUTION_CLIENTS:
109+
pytest.exit(f"Unsupported client was passed: {c}")
110+
logger.info(f"Provided client list: {clients}")
111+
# activate majority mode if also URL condition is met
112+
if ".ethpandaops.io" in rpc_endpoint:
113+
logger.info("Ethpandaops RPC detected")
114+
logger.info("Toggling majority test on")
115+
config.option.majority_clients = clients # List[str]
112116
else:
113-
print("No ethpandaops RPC detected, majority test will not be toggled on")
117+
logger.info("Majority test mode is disabled because no --clients value was passed.")
114118

115119
if config.getoption("collectonly", default=False):
116120
return
117121

118122
# Test out the RPC endpoint to be able to fail fast if it's not working
119123
eth_rpc = EthRPC(rpc_endpoint)
120124
try:
121-
print("Will now perform a connection check (request chain_id)..")
125+
logger.debug("Will now perform a connection check (request chain_id)..")
122126
chain_id = eth_rpc.chain_id()
123-
print(f"Connection check ok (successfully got chain id {chain_id})")
127+
logger.debug(f"Connection check ok (successfully got chain id {chain_id})")
124128
except Exception as e:
125129
pytest.exit(f"Could not connect to RPC endpoint {rpc_endpoint}: {e}")
126130
try:
127-
print("Will now briefly check whether eth_config is supported by target rpc..")
131+
logger.debug("Will now briefly check whether eth_config is supported by target rpc..")
128132
eth_rpc.config()
129-
print("Connection check ok (successfully got eth_config response)")
133+
logger.debug("Connection check ok (successfully got eth_config response)")
130134
except Exception as e:
131135
pytest.exit(f"RPC endpoint {rpc_endpoint} does not support `eth_config`: {e}")
132136

@@ -137,12 +141,6 @@ def rpc_endpoint(request) -> str:
137141
return request.config.getoption("rpc_endpoint")
138142

139143

140-
# @pytest.fixture(autouse=True, scope="session")
141-
# def eth_rpc(rpc_endpoint: str) -> EthRPC:
142-
# """Initialize ethereum RPC client for the execution client under test."""
143-
# return EthRPC(rpc_endpoint)
144-
145-
146144
def all_rpc_endpoints(config) -> Dict[str, List[EthRPC]]:
147145
"""Derive a mapping of exec clients to the RPC URLs they are reachable at."""
148146
rpc_endpoint = config.getoption("rpc_endpoint")
@@ -182,7 +180,9 @@ def pytest_generate_tests(metafunc: pytest.Metafunc):
182180
if metafunc.definition.name == "test_eth_config_majority":
183181
if len(all_rpc_endpoints_dict) < 2:
184182
# The test function is not run because we only have a single client, so no majority comparison # noqa: E501
185-
print("Skipping eth_config majority because less than 2 exec clients were passed")
183+
logger.info(
184+
"Skipping eth_config majority because less than 2 exec clients were passed"
185+
)
186186
metafunc.parametrize(
187187
["all_rpc_endpoints"],
188188
[],

src/pytest_plugins/execute/eth_config/execute_eth_config.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,12 @@
88
import pytest
99

1010
from ethereum_test_rpc import EthConfigResponse, EthRPC
11+
from pytest_plugins.logging import get_logger
1112

1213
from .types import NetworkConfig
1314

15+
logger = get_logger(__name__)
16+
1417

1518
@pytest.fixture(scope="function")
1619
def eth_config_response(eth_rpc: List[EthRPC]) -> EthConfigResponse | None:
@@ -34,7 +37,6 @@ def current_time() -> int:
3437
@pytest.fixture(scope="function")
3538
def expected_eth_config(network: NetworkConfig, current_time: int) -> EthConfigResponse:
3639
"""Calculate the current fork value to verify against the client's response."""
37-
print(f"Network provided: {network}, Type: {type(network)}")
3840
return network.get_eth_config(current_time)
3941

4042

@@ -191,7 +193,7 @@ def test_eth_config_majority(
191193
response = eth_rpc_target.config(timeout=10)
192194
if response is None:
193195
# safely split url to not leak rpc_endpoint in logs
194-
print(
196+
logger.warning(
195197
f"When trying to get eth_config from {eth_rpc_target} a problem occurred" # problem itself is logged by .config() call # noqa: E501
196198
)
197199
continue
@@ -201,7 +203,7 @@ def test_eth_config_majority(
201203
client_to_url_used_dict[exec_client] = (
202204
eth_rpc_target.url
203205
) # remember which cl+el combination was used # noqa: E501
204-
print(f"Response of {exec_client}: {response_str}\n\n")
206+
logger.info(f"Response of {exec_client}: {response_str}\n\n")
205207

206208
break # no need to gather more responses for this client
207209

@@ -218,7 +220,7 @@ def test_eth_config_majority(
218220
for client in responses.keys():
219221
response_bytes = json.dumps(responses[client], sort_keys=True).encode("utf-8")
220222
response_hash = sha256(response_bytes).digest().hex()
221-
print(f"Response hash of client {client}: {response_hash}")
223+
logger.info(f"Response hash of client {client}: {response_hash}")
222224
client_to_hash_dict[client] = response_hash
223225

224226
# if not all responses have the same hash there is a critical consensus issue
@@ -236,4 +238,4 @@ def test_eth_config_majority(
236238
)
237239
assert expected_hash != ""
238240

239-
print("All clients returned the same eth_config response. Test has been passed!")
241+
logger.info("All clients returned the same eth_config response. Test has been passed!")

0 commit comments

Comments
 (0)