Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions newsfragments/1207.internal.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Remove ``print`` statements and change it to logging
11 changes: 7 additions & 4 deletions tests/core/bitswap/test_integration.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"""Integration tests for Bitswap file transfer between nodes."""

import logging
from pathlib import Path
import tempfile

Expand All @@ -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."""
Expand Down Expand Up @@ -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 ---"
)

Expand All @@ -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, (
Expand All @@ -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()
Expand Down
9 changes: 6 additions & 3 deletions tests/core/discovery/rendezvous/test_integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
Integration tests for rendezvous discovery functionality.
"""

import logging
import secrets
from unittest.mock import AsyncMock, Mock

Expand All @@ -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."""
Expand Down Expand Up @@ -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


Expand Down Expand Up @@ -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()
Expand Down
8 changes: 5 additions & 3 deletions tests/core/kad_dht/test_kad_dht.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
5 changes: 4 additions & 1 deletion tests/core/pubsub/test_dummyaccount_demo.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from collections.abc import (
Callable,
)
import logging

import pytest
import trio
Expand All @@ -12,6 +13,8 @@
DummyAccountNode,
)

logger = logging.getLogger(__name__)


async def wait_for_convergence(
nodes: tuple[DummyAccountNode, ...],
Expand Down Expand Up @@ -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
Expand Down
22 changes: 14 additions & 8 deletions tests/core/pubsub/test_gossipsub_direct_peers.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import logging

import pytest
import trio

Expand All @@ -14,6 +16,8 @@
PubsubFactory,
)

logger = logging.getLogger(__name__)


@pytest.mark.trio
async def test_attach_peer_records():
Expand All @@ -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


Expand Down Expand Up @@ -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


Expand Down Expand Up @@ -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
6 changes: 5 additions & 1 deletion tests/core/security/test_security_multistream.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import logging

import pytest
import trio

Expand All @@ -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:
Expand Down Expand Up @@ -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
Expand Down
8 changes: 5 additions & 3 deletions tests/core/stream_muxer/test_multiplexer_selection.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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)

Expand Down
5 changes: 4 additions & 1 deletion tests/core/transport/quic/test_listener.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import logging
from unittest.mock import AsyncMock, Mock, patch

import pytest
Expand All @@ -20,6 +21,8 @@
create_quic_multiaddr,
)

logger = logging.getLogger(__name__)


class TestQUICListener:
"""Test suite for QUIC listener functionality."""
Expand Down Expand Up @@ -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):
Expand Down
4 changes: 2 additions & 2 deletions tests/core/transport/test_tcp.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
Loading