Skip to content

Commit 4ecd14f

Browse files
chore: replace print statements with logging in tests (libp2p#1253)
* test: replace print statements with logging Addresses libp2p#1207. Replaces bare print() calls in test files with proper logging calls using the existing logger pattern (logging.getLogger(__name__)). Functional prints in IPC scripts are left unchanged. * lint: fixes * chore: add newsfragment for issue 1207 * test: remove forced DEBUG logging in multiplexer selection test
1 parent 90a4c50 commit 4ecd14f

File tree

14 files changed

+79
-47
lines changed

14 files changed

+79
-47
lines changed

newsfragments/1207.internal.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Replaced bare ``print()`` calls in test modules with logger-based output so test verbosity is configurable and consistent with project conventions.

tests/core/bitswap/test_integration.py

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
"""Integration tests for Bitswap file transfer between nodes."""
22

3+
import logging
34
from pathlib import Path
45
import tempfile
56

@@ -15,6 +16,8 @@
1516
from libp2p.crypto.secp256k1 import create_new_key_pair
1617
from libp2p.peer.peerinfo import info_from_p2p_addr
1718

19+
logger = logging.getLogger(__name__)
20+
1821

1922
class TestBitswapIntegration:
2023
"""Integration tests for Bitswap protocol."""
@@ -447,9 +450,8 @@ async def test_dont_have_response(self):
447450

448451
# Step 4: Request a non-existent block and verify we
449452
# get a DontHave response
450-
print(
451-
"\n--- Step 4: Request nonexistent block and "
452-
"verify DontHave response ---"
453+
logger.debug(
454+
"Step 4: Request nonexistent block and verify DontHave response"
453455
)
454456

455457
# Start the request in the background (will eventually
@@ -475,8 +477,9 @@ async def request_nonexistent():
475477

476478
# The ACTUAL test: Did we receive a DontHave
477479
# response?
478-
print(
479-
f"DontHave responses: {client_bitswap._dont_have_responses}"
480+
logger.debug(
481+
"DontHave responses: %s",
482+
client_bitswap._dont_have_responses,
480483
)
481484
assert (
482485
parse_cid(nonexistent_cid)
@@ -491,7 +494,7 @@ async def request_nonexistent():
491494
parse_cid(nonexistent_cid)
492495
]
493496
), "Provider should have sent the DontHave response"
494-
print("✓ DontHave response received from provider!")
497+
logger.debug("DontHave response received from provider")
495498

496499
# Cancel the background request
497500
test_nursery.cancel_scope.cancel()

tests/core/discovery/rendezvous/test_integration.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
Integration tests for rendezvous discovery functionality.
33
"""
44

5+
import logging
56
import secrets
67
from unittest.mock import AsyncMock, Mock
78

@@ -19,6 +20,8 @@
1920
from libp2p.peer.id import ID
2021
from libp2p.peer.peerinfo import PeerInfo
2122

23+
logger = logging.getLogger(__name__)
24+
2225

2326
def create_test_host(port: int = 0):
2427
"""Create a test host with random key pair."""
@@ -140,13 +143,13 @@ async def test_full_rendezvous_workflow():
140143

141144
except Exception as e:
142145
# Log the error for debugging
143-
print(f"Integration test error: {e}")
146+
logger.error("Integration test error: %s", e)
144147
# Don't fail the test for connection issues in unit tests
145148
raise
146149

147150
except Exception as e:
148151
# Handle any startup/shutdown errors gracefully
149-
print(f"Host management error: {e}")
152+
logger.error("Host management error: %s", e)
150153
raise
151154

152155

@@ -267,7 +270,7 @@ async def test_rendezvous_registration_refresh():
267270

268271
except Exception as e:
269272
# Handle mock-related issues gracefully
270-
print(f"Refresh test error: {e}")
273+
logger.error("Refresh test error: %s", e)
271274

272275
# Cancel nursery
273276
nursery.cancel_scope.cancel()

tests/core/kad_dht/test_kad_dht.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -277,9 +277,12 @@ async def test_put_and_get_value(dht_pair: tuple[KadDHT, KadDHT]):
277277
local_value_record = dht_a.value_store.get(key_bytes)
278278
assert local_value_record is not None
279279
assert local_value_record.value == value, "Local value storage failed"
280-
print("number of nodes in peer store", dht_a.host.get_peerstore().peer_ids())
280+
logger.debug(
281+
"Number of nodes in peer store: %s",
282+
dht_a.host.get_peerstore().peer_ids(),
283+
)
281284
await dht_a.routing_table.add_peer(peer_b_info)
282-
print("Routing table of a has ", dht_a.routing_table.get_peer_ids())
285+
logger.debug("Routing table of a has: %s", dht_a.routing_table.get_peer_ids())
283286

284287
# An extra FIND_NODE req is sent between the 2 nodes while dht creation,
285288
# so both the nodes will have records of each other before PUT_VALUE req is sent
@@ -330,7 +333,7 @@ async def test_put_and_get_value(dht_pair: tuple[KadDHT, KadDHT]):
330333
# Retrieve the value using the second node
331334
with trio.fail_after(TEST_TIMEOUT):
332335
retrieved_value = await dht_b.get_value(key)
333-
print("the value stored in node b is", dht_b.get_value_store_size())
336+
logger.debug("Value store size in node b: %s", dht_b.get_value_store_size())
334337
logger.debug("Retrieved value: %s", retrieved_value)
335338

336339
# These are the records that were sent between the peers during the PUT_VALUE req

tests/core/pubsub/test_dummyaccount_demo.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
from collections.abc import (
22
Callable,
33
)
4+
import logging
45

56
import pytest
67
import trio
@@ -12,6 +13,8 @@
1213
DummyAccountNode,
1314
)
1415

16+
logger = logging.getLogger(__name__)
17+
1518

1619
async def wait_for_convergence(
1720
nodes: tuple[DummyAccountNode, ...],
@@ -48,7 +51,7 @@ async def wait_for_convergence(
4851
if not failed_indices:
4952
elapsed = trio.current_time() - start_time
5053
if log_success:
51-
print(f"✓ Converged in {elapsed:.3f}s with {len(nodes)} nodes")
54+
logger.debug("Converged in %.3fs with %d nodes", elapsed, len(nodes))
5255
return
5356

5457
elapsed = trio.current_time() - start_time

tests/core/pubsub/test_gossipsub_direct_peers.py

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import logging
2+
13
import pytest
24
import trio
35

@@ -14,6 +16,8 @@
1416
PubsubFactory,
1517
)
1618

19+
logger = logging.getLogger(__name__)
20+
1721

1822
@pytest.mark.trio
1923
async def test_attach_peer_records():
@@ -41,15 +45,15 @@ async def test_attach_peer_records():
4145
peer_ids_0 = peer_store_0.peer_ids()
4246
peer_ids_1 = peer_store_1.peer_ids()
4347

44-
print(f"Peer store 0 IDs: {peer_ids_0}")
45-
print(f"Peer store 1 IDs: {peer_ids_1}")
46-
print(f"Host 0 ID: {host_0.get_id()}")
47-
print(f"Host 1 ID: {host_1.get_id()}")
48+
logger.debug("Peer store 0 IDs: %s", peer_ids_0)
49+
logger.debug("Peer store 1 IDs: %s", peer_ids_1)
50+
logger.debug("Host 0 ID: %s", host_0.get_id())
51+
logger.debug("Host 1 ID: %s", host_1.get_id())
4852

4953
assert host_0.get_id() in peer_ids_1, "Peer 0 not found in peer store 1"
5054

5155
except Exception as e:
52-
print(f"Test failed with error: {e}")
56+
logger.error("Test failed with error: %s", e)
5357
raise
5458

5559

@@ -114,7 +118,7 @@ async def test_reject_graft():
114118
)
115119

116120
except Exception as e:
117-
print(f"Test failed with error: {e}")
121+
logger.error("Test failed with error: %s", e)
118122
raise
119123

120124

@@ -171,5 +175,5 @@ async def test_heartbeat_reconnect():
171175
)
172176

173177
except Exception as e:
174-
print(f"Test failed with error: {e}")
178+
logger.error("Test failed with error: %s", e)
175179
raise

tests/core/security/test_security_multistream.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import logging
2+
13
import pytest
24
import trio
35

@@ -19,6 +21,8 @@
1921
host_pair_factory,
2022
)
2123

24+
logger = logging.getLogger(__name__)
25+
2226
initiator_key_pair = create_new_key_pair()
2327

2428
noninitiator_key_pair = create_new_key_pair()
@@ -64,7 +68,7 @@ def get_secured_conn(conn):
6468
return muxed_conn._connection
6569
# Last resort - warn but return the muxed_conn itself for type checking
6670
else:
67-
print(f"Warning: Cannot find secured connection in {type(muxed_conn)}")
71+
logger.warning("Cannot find secured connection in %s", type(muxed_conn))
6872
return muxed_conn
6973

7074
# Get secured connections for both peers

tests/core/stream_muxer/test_multiplexer_selection.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,7 @@
1515
from libp2p.custom_types import TProtocol
1616
from libp2p.peer.peerinfo import PeerInfo
1717

18-
# Enable logging for debugging
19-
logging.basicConfig(level=logging.DEBUG)
18+
logger = logging.getLogger(__name__)
2019

2120

2221
# Fixture to create hosts with a specified muxer preference
@@ -88,7 +87,7 @@ async def echo_handler(stream):
8887
await stream.write(data)
8988
await stream.close()
9089
except Exception as e:
91-
print(f"Error in echo handler: {e}")
90+
logger.error("Error in echo handler: %s", e)
9291

9392
host_a.set_stream_handler(ECHO_PROTOCOL, echo_handler)
9493

@@ -165,7 +164,7 @@ async def echo_handler(stream):
165164
await stream.write(data)
166165
await stream.close()
167166
except Exception as e:
168-
print(f"Error in echo handler: {e}")
167+
logger.error("Error in echo handler: %s", e)
169168

170169
host_a.set_stream_handler(ECHO_PROTOCOL, echo_handler)
171170

@@ -235,7 +234,7 @@ async def echo_handler(stream):
235234
await stream.write(data)
236235
await stream.close()
237236
except Exception as e:
238-
print(f"Error in echo handler: {e}")
237+
logger.error("Error in echo handler: %s", e)
239238

240239
host_a.set_stream_handler(ECHO_PROTOCOL, echo_handler)
241240

tests/core/transport/quic/test_listener.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import logging
12
from unittest.mock import AsyncMock, Mock, patch
23

34
import pytest
@@ -20,6 +21,8 @@
2021
create_quic_multiaddr,
2122
)
2223

24+
logger = logging.getLogger(__name__)
25+
2326

2427
class TestQUICListener:
2528
"""Test suite for QUIC listener functionality."""
@@ -137,7 +140,7 @@ async def test_listener_port_binding(self, listener: QUICListener):
137140

138141
# By the time we get here, the listener and its tasks have been fully
139142
# shut down, allowing the nursery to exit without hanging.
140-
print("TEST COMPLETED SUCCESSFULLY.")
143+
logger.debug("Test completed successfully.")
141144

142145
@pytest.mark.trio
143146
async def test_listener_stats_tracking(self, listener):

tests/core/transport/test_tcp.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -154,10 +154,10 @@ async def ping_stream(i: int):
154154
if response == b"\x01" * PING_LENGTH:
155155
latency_ms = int((trio.current_time() - start) * 1000)
156156
latencies.append(latency_ms)
157-
print(f"[TCP Ping #{i}] Latency: {latency_ms} ms")
157+
logger.debug("[TCP Ping #%d] Latency: %d ms", i, latency_ms)
158158
await stream.close()
159159
except Exception as e:
160-
print(f"[TCP Ping #{i}] Failed: {e}")
160+
logger.warning("[TCP Ping #%d] Failed: %s", i, e)
161161
failures.append(i)
162162
if stream:
163163
try:

0 commit comments

Comments
 (0)