From 738a7e91a7fff8a48f591ff0895defa927724da8 Mon Sep 17 00:00:00 2001 From: dromanov Date: Wed, 18 Feb 2026 18:18:57 +0300 Subject: [PATCH 1/2] chore: remove print statements --- tests/core/bitswap/test_integration.py | 11 +- .../discovery/rendezvous/test_integration.py | 9 +- tests/core/kad_dht/test_kad_dht.py | 8 +- tests/core/pubsub/test_dummyaccount_demo.py | 5 +- .../pubsub/test_gossipsub_direct_peers.py | 22 ++- .../security/test_security_multistream.py | 6 +- .../test_multiplexer_selection.py | 8 +- tests/core/transport/quic/test_listener.py | 5 +- tests/core/transport/test_tcp.py | 4 +- .../attack_simulation/run_trio_tests.py | 145 ++++++++---------- tests/examples/test_examples.py | 7 +- .../websocket/py_node/py_websocket_node.py | 8 +- tests/interop/websocket/test_js_ws_ping.py | 17 +- .../websocket/test_websocket_bidirectional.py | 15 +- .../websocket/test_websocket_py_to_js.py | 9 +- 15 files changed, 147 insertions(+), 132 deletions(-) diff --git a/tests/core/bitswap/test_integration.py b/tests/core/bitswap/test_integration.py index a949edc1b..1e0417c02 100644 --- a/tests/core/bitswap/test_integration.py +++ b/tests/core/bitswap/test_integration.py @@ -1,5 +1,6 @@ """Integration tests for Bitswap file transfer between nodes.""" +import logging from pathlib import Path import tempfile @@ -15,6 +16,8 @@ from libp2p.crypto.secp256k1 import create_new_key_pair from libp2p.peer.peerinfo import info_from_p2p_addr +logger = logging.getLogger(__name__) + class TestBitswapIntegration: """Integration tests for Bitswap protocol.""" @@ -382,8 +385,8 @@ async def test_dont_have_response(self): # Step 4: Request a non-existent block and verify we # get a DontHave response - print( - "\n--- Step 4: Request nonexistent block and " + logger.debug( + "--- Step 4: Request nonexistent block and " "verify DontHave response ---" ) @@ -410,7 +413,7 @@ async def request_nonexistent(): # The ACTUAL test: Did we receive a DontHave # response? - print( + logger.info( f"DontHave responses: {client_bitswap._dont_have_responses}" ) assert nonexistent_cid in client_bitswap._dont_have_responses, ( @@ -421,7 +424,7 @@ async def request_nonexistent(): provider_host.get_id() in client_bitswap._dont_have_responses[nonexistent_cid] ), "Provider should have sent the DontHave response" - print("✓ DontHave response received from provider!") + logger.info("✓ DontHave response received from provider!") # Cancel the background request test_nursery.cancel_scope.cancel() diff --git a/tests/core/discovery/rendezvous/test_integration.py b/tests/core/discovery/rendezvous/test_integration.py index 011155688..97be524f0 100644 --- a/tests/core/discovery/rendezvous/test_integration.py +++ b/tests/core/discovery/rendezvous/test_integration.py @@ -2,6 +2,7 @@ Integration tests for rendezvous discovery functionality. """ +import logging import secrets from unittest.mock import AsyncMock, Mock @@ -19,6 +20,8 @@ from libp2p.peer.id import ID from libp2p.peer.peerinfo import PeerInfo +logger = logging.getLogger(__name__) + def create_test_host(port: int = 0): """Create a test host with random key pair.""" @@ -140,13 +143,13 @@ async def test_full_rendezvous_workflow(): except Exception as e: # Log the error for debugging - print(f"Integration test error: {e}") + logger.debug("Integration test error: %s", e) # Don't fail the test for connection issues in unit tests raise except Exception as e: # Handle any startup/shutdown errors gracefully - print(f"Host management error: {e}") + logger.debug("Host management error: %s", e) raise @@ -267,7 +270,7 @@ async def test_rendezvous_registration_refresh(): except Exception as e: # Handle mock-related issues gracefully - print(f"Refresh test error: {e}") + logger.warning("Refresh test error: %s", e) # Cancel nursery nursery.cancel_scope.cancel() diff --git a/tests/core/kad_dht/test_kad_dht.py b/tests/core/kad_dht/test_kad_dht.py index 6397827aa..732e21e27 100644 --- a/tests/core/kad_dht/test_kad_dht.py +++ b/tests/core/kad_dht/test_kad_dht.py @@ -277,9 +277,11 @@ async def test_put_and_get_value(dht_pair: tuple[KadDHT, KadDHT]): local_value_record = dht_a.value_store.get(key_bytes) assert local_value_record is not None assert local_value_record.value == value, "Local value storage failed" - print("number of nodes in peer store", dht_a.host.get_peerstore().peer_ids()) + logger.debug( + "number of nodes in peer store: %s", dht_a.host.get_peerstore().peer_ids() + ) await dht_a.routing_table.add_peer(peer_b_info) - print("Routing table of a has ", dht_a.routing_table.get_peer_ids()) + logger.debug("Routing table of a has : %s", dht_a.routing_table.get_peer_ids()) # An extra FIND_NODE req is sent between the 2 nodes while dht creation, # so both the nodes will have records of each other before PUT_VALUE req is sent @@ -330,7 +332,7 @@ async def test_put_and_get_value(dht_pair: tuple[KadDHT, KadDHT]): # Retrieve the value using the second node with trio.fail_after(TEST_TIMEOUT): retrieved_value = await dht_b.get_value(key) - print("the value stored in node b is", dht_b.get_value_store_size()) + logger.debug("the value stored in node b is: %d", dht_b.get_value_store_size()) logger.debug("Retrieved value: %s", retrieved_value) # These are the records that were sent between the peers during the PUT_VALUE req diff --git a/tests/core/pubsub/test_dummyaccount_demo.py b/tests/core/pubsub/test_dummyaccount_demo.py index 395e482f5..fce2d731b 100644 --- a/tests/core/pubsub/test_dummyaccount_demo.py +++ b/tests/core/pubsub/test_dummyaccount_demo.py @@ -1,6 +1,7 @@ from collections.abc import ( Callable, ) +import logging import pytest import trio @@ -12,6 +13,8 @@ DummyAccountNode, ) +logger = logging.getLogger(__name__) + async def wait_for_convergence( nodes: tuple[DummyAccountNode, ...], @@ -48,7 +51,7 @@ async def wait_for_convergence( if not failed_indices: elapsed = trio.current_time() - start_time if log_success: - print(f"✓ Converged in {elapsed:.3f}s with {len(nodes)} nodes") + logger.debug(f"✓ Converged in {elapsed:.3f}s with {len(nodes)} nodes") return elapsed = trio.current_time() - start_time diff --git a/tests/core/pubsub/test_gossipsub_direct_peers.py b/tests/core/pubsub/test_gossipsub_direct_peers.py index adb20a803..1b97787f3 100644 --- a/tests/core/pubsub/test_gossipsub_direct_peers.py +++ b/tests/core/pubsub/test_gossipsub_direct_peers.py @@ -1,3 +1,5 @@ +import logging + import pytest import trio @@ -14,6 +16,8 @@ PubsubFactory, ) +logger = logging.getLogger(__name__) + @pytest.mark.trio async def test_attach_peer_records(): @@ -40,16 +44,18 @@ async def test_attach_peer_records(): # Check that each host has the other's peer record peer_ids_0 = peer_store_0.peer_ids() peer_ids_1 = peer_store_1.peer_ids() + host_ids_0 = host_0.get_id() + host_ids_1 = host_1.get_id() - print(f"Peer store 0 IDs: {peer_ids_0}") - print(f"Peer store 1 IDs: {peer_ids_1}") - print(f"Host 0 ID: {host_0.get_id()}") - print(f"Host 1 ID: {host_1.get_id()}") + logger.info("Peer store 0 IDs: %s", peer_ids_0) + logger.info("Peer store 1 IDs: %s", peer_ids_1) + logger.info("Host 0 ID: %s", host_ids_0) + logger.info("Host 1 ID: %s", host_ids_1) - assert host_0.get_id() in peer_ids_1, "Peer 0 not found in peer store 1" + assert host_ids_0 in peer_ids_1, "Peer 0 not found in peer store 1" except Exception as e: - print(f"Test failed with error: {e}") + logger.debug("Test failed with error: %s", e) raise @@ -114,7 +120,7 @@ async def test_reject_graft(): ) except Exception as e: - print(f"Test failed with error: {e}") + logger.debug("Test failed with error: %s", e) raise @@ -171,5 +177,5 @@ async def test_heartbeat_reconnect(): ) except Exception as e: - print(f"Test failed with error: {e}") + logger.debug("Test failed with error: %s", e) raise diff --git a/tests/core/security/test_security_multistream.py b/tests/core/security/test_security_multistream.py index d4fed72dc..82ce251b5 100644 --- a/tests/core/security/test_security_multistream.py +++ b/tests/core/security/test_security_multistream.py @@ -1,3 +1,5 @@ +import logging + import pytest import trio @@ -23,6 +25,8 @@ noninitiator_key_pair = create_new_key_pair() +logger = logging.getLogger(__name__) + async def perform_simple_test(assertion_func, security_protocol): async with host_pair_factory(security_protocol=security_protocol) as hosts: @@ -64,7 +68,7 @@ def get_secured_conn(conn): return muxed_conn._connection # Last resort - warn but return the muxed_conn itself for type checking else: - print(f"Warning: Cannot find secured connection in {type(muxed_conn)}") + logger.warning(f"Cannot find secured connection in {type(muxed_conn)}") return muxed_conn # Get secured connections for both peers diff --git a/tests/core/stream_muxer/test_multiplexer_selection.py b/tests/core/stream_muxer/test_multiplexer_selection.py index 9b45324e6..1602a7f16 100644 --- a/tests/core/stream_muxer/test_multiplexer_selection.py +++ b/tests/core/stream_muxer/test_multiplexer_selection.py @@ -18,6 +18,8 @@ # Enable logging for debugging logging.basicConfig(level=logging.DEBUG) +logger = logging.getLogger(__name__) + # Fixture to create hosts with a specified muxer preference @pytest.fixture @@ -88,7 +90,7 @@ async def echo_handler(stream): await stream.write(data) await stream.close() except Exception as e: - print(f"Error in echo handler: {e}") + logger.warning("Error in echo handler: %s", e) host_a.set_stream_handler(ECHO_PROTOCOL, echo_handler) @@ -165,7 +167,7 @@ async def echo_handler(stream): await stream.write(data) await stream.close() except Exception as e: - print(f"Error in echo handler: {e}") + logger.warning("Error in echo handler: %s", e) host_a.set_stream_handler(ECHO_PROTOCOL, echo_handler) @@ -235,7 +237,7 @@ async def echo_handler(stream): await stream.write(data) await stream.close() except Exception as e: - print(f"Error in echo handler: {e}") + logger.warning("Error in echo handler: %s", e) host_a.set_stream_handler(ECHO_PROTOCOL, echo_handler) diff --git a/tests/core/transport/quic/test_listener.py b/tests/core/transport/quic/test_listener.py index 872d8dcbe..187ffa19e 100644 --- a/tests/core/transport/quic/test_listener.py +++ b/tests/core/transport/quic/test_listener.py @@ -1,3 +1,4 @@ +import logging from unittest.mock import AsyncMock, Mock, patch import pytest @@ -20,6 +21,8 @@ create_quic_multiaddr, ) +logger = logging.getLogger(__name__) + class TestQUICListener: """Test suite for QUIC listener functionality.""" @@ -137,7 +140,7 @@ async def test_listener_port_binding(self, listener: QUICListener): # By the time we get here, the listener and its tasks have been fully # shut down, allowing the nursery to exit without hanging. - print("TEST COMPLETED SUCCESSFULLY.") + logger.info("TEST COMPLETED SUCCESSFULLY.") @pytest.mark.trio async def test_listener_stats_tracking(self, listener): diff --git a/tests/core/transport/test_tcp.py b/tests/core/transport/test_tcp.py index d2c956d63..09e5f5318 100644 --- a/tests/core/transport/test_tcp.py +++ b/tests/core/transport/test_tcp.py @@ -154,10 +154,10 @@ async def ping_stream(i: int): if response == b"\x01" * PING_LENGTH: latency_ms = int((trio.current_time() - start) * 1000) latencies.append(latency_ms) - print(f"[TCP Ping #{i}] Latency: {latency_ms} ms") + logger.debug(f"[TCP Ping #{i}] Latency: {latency_ms} ms") await stream.close() except Exception as e: - print(f"[TCP Ping #{i}] Failed: {e}") + logger.debug(f"[TCP Ping #{i}] Failed: {e}") failures.append(i) if stream: try: diff --git a/tests/examples/attack_simulation/run_trio_tests.py b/tests/examples/attack_simulation/run_trio_tests.py index 7c96b0d90..4d8278359 100644 --- a/tests/examples/attack_simulation/run_trio_tests.py +++ b/tests/examples/attack_simulation/run_trio_tests.py @@ -6,6 +6,7 @@ handle the async context required by trio.sleep() and trio.current_time(). """ +import logging import os import sys @@ -27,11 +28,12 @@ ) from .fork_attack.long_range_fork import ChainState, ForkAttacker, LongRangeForkScenario +logger = logging.getLogger(__name__) + async def test_invalid_block_basic(): """Test basic invalid block functionality""" - print("Testing Invalid Block Basic Functionality") - print("-" * 50) + logger.debug("Testing Invalid Block Basic Functionality") # Test block creation validator = MaliciousValidator("validator_0", 0.8) @@ -42,7 +44,6 @@ async def test_invalid_block_basic(): assert block.block_number == 1000 assert block.parent_hash == "parent_999" assert block.invalidity_type == BlockInvalidityType.INVALID_STATE_TRANSITION - print("[PASSED] Block creation") # Test propagation to light clients light_clients = ["lc1", "lc2", "lc3", "lc4", "lc5"] @@ -52,10 +53,6 @@ async def test_invalid_block_basic(): assert "acceptance_rate" in result assert "propagation_time" in result - print( - f"[PASSED] Light client propagation (acceptance: " - f"{result['acceptance_rate']:.1%})" - ) # Test propagation to full nodes full_nodes = ["fn1", "fn2", "fn3", "fn4", "fn5"] @@ -65,18 +62,16 @@ async def test_invalid_block_basic(): assert "acceptance_rate" in result assert "propagation_time" in result - print( - f"[PASSED] Full node propagation (acceptance: {result['acceptance_rate']:.1%})" + logger.debug( + "[PASSED] Full node propagation (acceptance: %.1f%%)", + result["acceptance_rate"] * 100, ) - - print("[PASSED] Invalid Block Basic Tests: ALL PASSED") return True async def test_bootnode_poisoning_basic(): """Test basic bootnode poisoning functionality""" - print("\nTesting Bootnode Poisoning Basic Functionality") - print("-" * 50) + logger.debug("Testing Bootnode Poisoning Basic Functionality") # Test bootnode attacker creation malicious_pool = [f"malicious_peer_{i}" for i in range(5)] @@ -85,7 +80,6 @@ async def test_bootnode_poisoning_basic(): assert attacker.bootnode_id == "bootnode_0" assert len(attacker.malicious_peer_pool) == 5 assert attacker.intensity == 0.9 - print("[PASSED] Bootnode attacker creation") # Test bootnode poisoning scenario honest_peers = [f"honest_peer_{i}" for i in range(10)] @@ -101,30 +95,29 @@ async def test_bootnode_poisoning_basic(): assert "attack_type" in results assert "isolation_metrics" in results assert "recovery_metrics" in results - print("[PASSED] Bootnode poisoning scenario") - print(f" - Isolation rate: {results['isolation_metrics']['isolation_rate']:.1%}") - print(f" - Recovery rate: {results['recovery_metrics']['recovery_rate']:.1%}") - - print("[PASSED] Bootnode Poisoning Basic Tests: ALL PASSED") + logger.debug( + "[PASSED] Bootnode poisoning scenario\n" + " - Isolation rate: %.1f%%\n" + " - Recovery rate: %.1f%%", + results["isolation_metrics"]["isolation_rate"] * 100, + results["recovery_metrics"]["recovery_rate"] * 100, + ) return True async def test_finality_stall_basic(): """Test basic finality stall functionality""" - print("\nTesting Finality Stall Basic Functionality") - print("-" * 50) + logger.debug("\nTesting Finality Stall Basic Functionality") # Test light client node creation lc = LightClientNode("lc_0", memory_limit_mb=200.0) assert lc.node_id == "lc_0" assert lc.memory_limit_mb == 200.0 - print("[PASSED] Light client node creation") # Test finality stall attacker attacker = FinalityStallAttacker("attacker_0", 0.8) assert attacker.attacker_id == "attacker_0" assert attacker.intensity == 0.8 - print("[PASSED] Finality stall attacker creation") # Test finality stall scenario light_clients = [ @@ -142,21 +135,20 @@ async def test_finality_stall_basic(): assert "attack_type" in results assert "memory_metrics" in results assert "detection_metrics" in results - print("[PASSED] Finality stall scenario") - print(f" - Memory exhaustion: {results['memory_metrics']['exhaustion_rate']:.1%}") - print( - f" - Timeout detection: " - f"{results['detection_metrics']['timeout_detection_rate']:.1%}" - ) - print("[PASSED] Finality Stall Basic Tests: ALL PASSED") + logger.debug( + "[PASSED] Finality stall scenario\n" + " - Memory exhaustion: %.1f%%\n" + " - Timeout detection: %.1f%%", + results["memory_metrics"]["exhaustion_rate"] * 100, + results["detection_metrics"]["timeout_detection_rate"], + ) return True async def test_long_range_fork_basic(): """Test basic long-range fork functionality""" - print("\nTesting Long-Range Fork Basic Functionality") - print("-" * 50) + logger.debug("Testing Long-Range Fork Basic Functionality") # Test chain state creation canonical_chain = ChainState( @@ -176,13 +168,11 @@ async def test_long_range_fork_basic(): assert canonical_chain.block_height == 1000 assert stale_fork.block_height == 800 - print("[PASSED] Chain state creation") # Test fork attacker attacker = ForkAttacker("fork_attacker_0", stale_fork, canonical_chain, 0.7) assert attacker.attacker_id == "fork_attacker_0" assert attacker.intensity == 0.7 - print("[PASSED] Fork attacker creation") # Test long-range fork scenario online_peers = [f"online_peer_{i}" for i in range(10)] @@ -196,73 +186,60 @@ async def test_long_range_fork_basic(): assert "attack_type" in results assert "fork_metrics" in results assert "detection_metrics" in results - print("[PASSED] Long-range fork scenario") - print( - f" - Fork replay success: " - f"{results['fork_metrics']['replay_success_rate']:.1%}" - ) - print(f" - Detection rate: {results['detection_metrics']['detection_rate']:.1%}") - print("[PASSED] Long-Range Fork Basic Tests: ALL PASSED") + logger.debug( + "[PASSED] Long-range fork scenario\n" + " - Fork replay success: %.1f%%\n" + " - Detection rate: %.1f%%", + results["fork_metrics"]["replay_success_rate"] * 100, + results["detection_metrics"]["detection_rate"] * 100, + ) return True async def run_all_tests(): """Run all attack simulation tests""" - print("ATTACK SIMULATION TEST SUITE") - print("=" * 60) - print("Testing extended threat model attack simulations") - print("Using trio.run() for proper async context handling") - print() + logger.info("ATTACK SIMULATION TEST SUITE") test_results = {} + tests = [ + ("invalid_block", test_invalid_block_basic), + ("bootnode_poisoning", test_bootnode_poisoning_basic), + ("finality_stall", test_finality_stall_basic), + ("long_range_fork", test_long_range_fork_basic), + ] - try: - test_results["invalid_block"] = await test_invalid_block_basic() - except Exception as e: - print(f"[FAILED] Invalid Block Tests: {e}") - test_results["invalid_block"] = False - - try: - test_results["bootnode_poisoning"] = await test_bootnode_poisoning_basic() - except Exception as e: - print(f"[FAILED] Bootnode Poisoning Tests: {e}") - test_results["bootnode_poisoning"] = False - - try: - test_results["finality_stall"] = await test_finality_stall_basic() - except Exception as e: - print(f"[FAILED] Finality Stall Tests: {e}") - test_results["finality_stall"] = False - - try: - test_results["long_range_fork"] = await test_long_range_fork_basic() - except Exception as e: - print(f"[FAILED] Long-Range Fork Tests: {e}") - test_results["long_range_fork"] = False + for name, test_func in tests: + try: + test_results[name] = await test_func() + logger.info("%s [PASSED]", name.replace("_", " ").title()) + except Exception as e: + logger.error( + "%s [FAILED] %s", + name.replace("_", " ").title(), + e, + exc_info=True, + ) + test_results[name] = False # Summary - print("\n" + "=" * 60) - print("TEST RESULTS SUMMARY") - print("=" * 60) - passed_tests = sum(1 for result in test_results.values() if result) total_tests = len(test_results) - print(f"[PASSED] Passed: {passed_tests}/{total_tests}") - print() + logger.info("TEST SUMMARY") + logger.info("Passed: %d / %d", passed_tests, total_tests) - for test_name, result in test_results.items(): - status = "[PASSED]" if result else "[FAILED]" - test_display = test_name.replace("_", " ").title() - print(f"{status} {test_display}") + if passed_tests < total_tests: + logger.warning("Failed tests:") + for name, ok in test_results.items(): + if not ok: + logger.warning(" • %s", name.replace("_", " ").title()) if passed_tests == total_tests: - print("\n[PASSED] ALL TESTS PASSED!") - print("Extended threat model attack simulations are working correctly") + logger.info("ALL TESTS PASSED") + logger.info("Extended threat model attack simulations are working correctly") else: - print(f"\n[FAILED] {total_tests - passed_tests} TESTS FAILED") - print("Some attack simulations need attention") + logger.warning("%d test(s) failed", total_tests - passed_tests) return passed_tests == total_tests @@ -274,7 +251,7 @@ def main(): success = trio.run(run_all_tests) sys.exit(0 if success else 1) except Exception as e: - print(f"[FAILED] Test runner failed: {e}") + logger.critical("Test runner crashed: %s", e, exc_info=True) sys.exit(1) diff --git a/tests/examples/test_examples.py b/tests/examples/test_examples.py index 3ed285e8d..3f60f8acb 100644 --- a/tests/examples/test_examples.py +++ b/tests/examples/test_examples.py @@ -222,7 +222,7 @@ async def handle_subscription_b(subscription): nonlocal received_by_b message = await subscription.get() received_by_b = message.data.decode("utf-8") - print(f"Host B received: {received_by_b}") + logger.debug("Host B received message: %s", received_by_b) b_received.set() async with background_trio_service(pubsub_a): @@ -236,9 +236,9 @@ async def handle_subscription_b(subscription): peer_info_b = info_from_p2p_addr(listen_addrs_b[0]) try: await pubsub_a.host.connect(peer_info_b) - print("Connection attempt completed") + logger.debug("Connection attempt completed") except Exception as e: - print(f"Connection error: {e}") + logger.debug("Connection error: %s", e) raise subscription_b = await pubsub_b.subscribe(PUBSUB_TEST_TOPIC) @@ -321,7 +321,6 @@ async def identify_push_demo(host_a, host_b): ) @pytest.mark.trio async def test_protocols(test, security_protocol): - print("!@# ", security_protocol) async with HostFactory.create_batch_and_listen( 2, security_protocol=security_protocol ) as hosts: diff --git a/tests/interop/websocket/py_node/py_websocket_node.py b/tests/interop/websocket/py_node/py_websocket_node.py index 7677cead5..0ba800e0c 100644 --- a/tests/interop/websocket/py_node/py_websocket_node.py +++ b/tests/interop/websocket/py_node/py_websocket_node.py @@ -233,7 +233,7 @@ async def run_py_server_test( "http_enabled": True, "libp2p_enabled": LIBP2P_AVAILABLE, } - print(f"SERVER_INFO:{json.dumps(server_info)}") + logger.info(f"SERVER_INFO:{json.dumps(server_info)}") logger.info(f"Server ready - waiting {duration}s for connections...") await trio.sleep(duration) if node.received_messages: @@ -281,7 +281,7 @@ async def run_py_client_test(target_addr: str, message: str) -> dict[str, Any]: if __name__ == "__main__": if len(sys.argv) < 2: - print("Usage: python py_websocket_node.py [args...]") + logger.error("Usage: python py_websocket_node.py [args...]") sys.exit(1) mode = sys.argv[1] @@ -291,9 +291,9 @@ async def run_py_client_test(target_addr: str, message: str) -> dict[str, Any]: secure = sys.argv[3].lower() == "true" if len(sys.argv) > 3 else False duration = int(sys.argv[4]) if len(sys.argv) > 4 else 30 results = trio.run(run_py_server_test, port, secure, duration) - print("RESULTS:", json.dumps(results, indent=2)) + logger.info("RESULTS:\n%s", json.dumps(results, indent=2)) elif mode == "client": target_addr = sys.argv[2] if len(sys.argv) > 2 else "/ip4/127.0.0.1/tcp/8002" message = sys.argv[3] if len(sys.argv) > 3 else "Hello from Python client" results = trio.run(run_py_client_test, target_addr, message) - print("RESULTS:", json.dumps(results, indent=2)) + logger.info("RESULTS:\n%s", json.dumps(results, indent=2)) diff --git a/tests/interop/websocket/test_js_ws_ping.py b/tests/interop/websocket/test_js_ws_ping.py index 7607809fd..ef2826e74 100644 --- a/tests/interop/websocket/test_js_ws_ping.py +++ b/tests/interop/websocket/test_js_ws_ping.py @@ -1,3 +1,4 @@ +import logging import os import shutil import subprocess @@ -24,6 +25,8 @@ 22 # Required for Promise.withResolvers in @chainsafe/libp2p-noise v17+ ) +logger = logging.getLogger(__name__) + @pytest.mark.trio @pytest.mark.timeout(120) # type: ignore[attr-defined] @@ -125,11 +128,15 @@ async def read_stream(stream, sink: list[str]) -> None: maddr = Multiaddr(addr_line) # Debug: Print what we're trying to connect to - print(f"JS Node Peer ID: {peer_id_line}") - print(f"JS Node Address: {addr_line}") + logger.debug("JS Node Peer ID: %s", peer_id_line) + logger.debug("JS Node Address: %s", addr_line) # Optional: print captured logs for debugging - print("--- JS stdout (partial) ---\n" + "".join(captured_out)[-2000:]) - print("--- JS stderr (partial) ---\n" + "".join(captured_err)[-2000:]) + logger.debug( + "--- JS stdout (last 2000 chars) ---\n%s", "".join(captured_out)[-2000:] + ) + logger.debug( + "--- JS stderr (last 2000 chars) ---\n%s", "".join(captured_err)[-2000:] + ) # Set up Python host using new_host() factory - same approach as test-plans # This properly handles WebSocket transport for dialing @@ -164,7 +171,7 @@ async def read_stream(stream, sink: list[str]) -> None: # Add peer info to peerstore before connecting host.get_peerstore().add_addrs(peer_id, [maddr], 60) # 60 second TTL - print(f"Python trying to connect to: {peer_info}") + logger.debug("Python trying to connect to: %s", peer_info) # Use the host as a context manager async with host.run(listen_addrs=[ws_listen_addr]): diff --git a/tests/interop/websocket/test_websocket_bidirectional.py b/tests/interop/websocket/test_websocket_bidirectional.py index 403b77e09..a46a25794 100644 --- a/tests/interop/websocket/test_websocket_bidirectional.py +++ b/tests/interop/websocket/test_websocket_bidirectional.py @@ -1,3 +1,4 @@ +import logging from pathlib import Path import subprocess @@ -6,6 +7,8 @@ from tests.interop.websocket.py_node.py_websocket_node import PyWebSocketNode +logger = logging.getLogger(__name__) + @pytest.mark.trio async def test_bidirectional_communication(): @@ -18,7 +21,7 @@ async def test_bidirectional_communication(): if not js_node_path.exists(): pytest.fail(f"JS Node script not found at {js_node_path}") - print("Starting JavaScript server...") + logger.info("Starting JavaScript server...") js_process = subprocess.Popen( ["node", str(js_node_path), "server", "8005", "false", "30000"], stdout=subprocess.PIPE, @@ -26,9 +29,9 @@ async def test_bidirectional_communication(): ) await trio.sleep(3) - print("JavaScript server started on port 8005") + logger.info("JavaScript server started on port 8005") - print("Setting up Python client...") + logger.info("Setting up Python client...") py_node = PyWebSocketNode() await py_node.setup_node() @@ -42,7 +45,7 @@ async def test_bidirectional_communication(): successful_exchanges = 0 - print(f"\nSending {len(test_messages)} messages to JavaScript server...\n") + logger.info("Sending %d messages to JavaScript server...", len(test_messages)) for i, message in enumerate(test_messages, 1): try: @@ -51,12 +54,12 @@ async def test_bidirectional_communication(): if response and message in response: successful_exchanges += 1 else: - print(f"Exchange {i} failed: unexpected response") + logger.warning("Exchange %d failed: unexpected response", i) await trio.sleep(0.1) except Exception as e: - print(f"Exchange {i} failed: {e}") + logger.warning("Exchange %d failed: %s", i, e) await py_node.stop() diff --git a/tests/interop/websocket/test_websocket_py_to_js.py b/tests/interop/websocket/test_websocket_py_to_js.py index 0b300a81c..f6373725b 100644 --- a/tests/interop/websocket/test_websocket_py_to_js.py +++ b/tests/interop/websocket/test_websocket_py_to_js.py @@ -1,3 +1,4 @@ +import logging from pathlib import Path import subprocess @@ -10,6 +11,8 @@ from tests.interop.websocket.py_node.py_websocket_node import PyWebSocketNode from tests.interop.websocket.py_node.test_utils import TestResults +logger = logging.getLogger() + @pytest.mark.trio async def test_py_client_js_server(): @@ -25,7 +28,7 @@ async def test_py_client_js_server(): if not js_node_path.exists(): pytest.fail(f"JS Node script not found at {js_node_path}") - print("Starting JavaScript server...") + logger.info("Starting JavaScript server...") js_process = subprocess.Popen( ["node", str(js_node_path), "server", "8002", "false", "15000"], stdout=subprocess.PIPE, @@ -35,14 +38,14 @@ async def test_py_client_js_server(): # Give JS server time to start await trio.sleep(3) - print("Setting up Python client...") + logger.info("Setting up Python client...") node = PyWebSocketNode() await node.setup_node() target_addr = "/ip4/127.0.0.1/tcp/8002" test_message = "Hello from Python client" - print(f"Sending message to JS server: {test_message}") + logger.info(f"Sending message to JS server: {test_message}") try: response = await node.dial_and_send(target_addr, test_message) From e5a9b813494f73eddd0761b095ca3979fea5361b Mon Sep 17 00:00:00 2001 From: dromanov Date: Wed, 18 Feb 2026 18:19:21 +0300 Subject: [PATCH 2/2] docs: add newsfragmets --- newsfragments/1207.internal.rst | 1 + 1 file changed, 1 insertion(+) create mode 100644 newsfragments/1207.internal.rst diff --git a/newsfragments/1207.internal.rst b/newsfragments/1207.internal.rst new file mode 100644 index 000000000..19134200e --- /dev/null +++ b/newsfragments/1207.internal.rst @@ -0,0 +1 @@ +Remove ``print`` statements and change it to logging