Files
zigp2p/tests/helpers/test_p2p_pair.zig
2026-02-06 21:03:59 -03:00

289 lines
10 KiB
Zig

//! Test Helper: P2P Pair for Connected Peer Testing
//!
//! This module provides a test harness for creating two P2P instances
//! that connect to each other via localhost TCP. This enables testing
//! of connection success paths, message exchange, and network I/O.
//!
//! Usage:
//! var pair = try TestP2PPair.init(testing.allocator);
//! defer pair.deinit();
//! const peer_id = try pair.connect();
//! // Now pair.server and pair.client are connected
const std = @import("std");
// Re-export mock servers for tests that need them
pub const mock_stun_server = @import("mock_stun_server.zig");
const testing = std.testing;
const mem = std.mem;
const p2p_lib = @import("p2p");
const P2P = p2p_lib.P2P;
const P2PConfig = p2p_lib.P2PConfig;
const P2PState = p2p_lib.P2PState;
const core = @import("core");
const Address = core.Address;
const Error = core.errors.Error;
const network = @import("network");
const PeerId = network.peer.PeerId;
const atomic = std.atomic;
/// Port range for coverage tests (19901-19999)
/// Each test pair uses 2 ports: base and base+1
var next_port = atomic.Value(u16).init(19901);
/// Get next available port pair for testing
fn getNextPortPair() struct { server: u16, client: u16 } {
const server = next_port.fetchAdd(2, .acq_rel);
return .{ .server = server, .client = server + 1 };
}
/// Reset port counter (for test isolation)
pub fn resetPortCounter() void {
next_port.store(19901, .release);
}
/// Test harness for two connected P2P instances
pub const TestP2PPair = struct {
allocator: mem.Allocator,
server: *P2P,
client: *P2P,
server_port: u16,
client_port: u16,
connected_peer_id: ?PeerId,
started: bool,
const Self = @This();
/// Initialize two P2P instances with minimal configuration
pub fn init(allocator: mem.Allocator) Error!Self {
return initWithConfig(allocator, .{}, .{});
}
/// Initialize with custom configuration overrides
pub fn initWithConfig(
allocator: mem.Allocator,
server_overrides: ConfigOverrides,
client_overrides: ConfigOverrides,
) Error!Self {
const ports = getNextPortPair();
// Create server P2P
var server_config = getMinimalConfig();
server_config.network.listen_port = ports.server;
applyOverrides(&server_config, server_overrides);
const server = allocator.create(P2P) catch return Error.OutOfMemory;
errdefer allocator.destroy(server);
server.* = P2P.init(allocator, server_config) catch return Error.InvalidState;
errdefer server.deinit();
// Create client P2P
var client_config = getMinimalConfig();
client_config.network.listen_port = ports.client;
applyOverrides(&client_config, client_overrides);
const client = allocator.create(P2P) catch return Error.OutOfMemory;
errdefer allocator.destroy(client);
client.* = P2P.init(allocator, client_config) catch return Error.InvalidState;
return Self{
.allocator = allocator,
.server = server,
.client = client,
.server_port = ports.server,
.client_port = ports.client,
.connected_peer_id = null,
.started = false,
};
}
/// Cleanup both P2P instances
pub fn deinit(self: *Self) void {
if (self.started) {
// Stop both instances first
self.client.stop() catch {};
self.server.stop() catch {};
}
self.client.deinit();
self.allocator.destroy(self.client);
self.server.deinit();
self.allocator.destroy(self.server);
}
/// Start both P2P instances, have server listen, and client connect
/// Returns the peer ID of the server as seen by the client
pub fn connect(self: *Self) Error!PeerId {
return self.connectWithTimeout(5000);
}
/// Connect with custom timeout
pub fn connectWithTimeout(self: *Self, timeout_ms: u32) Error!PeerId {
// Start both
self.server.start() catch return Error.InvalidState;
self.client.start() catch return Error.InvalidState;
self.started = true;
// Clear initialization events
_ = self.server.processAllEvents();
_ = self.client.processAllEvents();
// Server listens on localhost
var listen_addr = Address.init();
listen_addr.port = self.server_port;
listen_addr.data = .{ .ipv4 = .{ .bytes = .{ 127, 0, 0, 1 } } };
self.server.startListening(listen_addr) catch return Error.SocketBindingFailed;
// Give server time to start listening
std.Thread.sleep(50 * std.time.ns_per_ms);
// Client connects to server
var connect_addr = Address.init();
connect_addr.port = self.server_port;
connect_addr.data = .{ .ipv4 = .{ .bytes = .{ 127, 0, 0, 1 } } };
self.connected_peer_id = self.client.connectToPeer(connect_addr) catch |err| {
std.debug.print("TestP2PPair: Connection failed: {}\n", .{err});
return err;
};
// Wait for connection to be established
self.waitForConnection(timeout_ms) catch |err| {
std.debug.print("TestP2PPair: Connection timeout\n", .{});
return err;
};
return self.connected_peer_id.?;
}
/// Wait for connection to be fully established
pub fn waitForConnection(self: *Self, timeout_ms: u32) Error!void {
const start = std.time.milliTimestamp();
const timeout: i64 = @intCast(timeout_ms);
while (std.time.milliTimestamp() - start < timeout) {
self.server.update() catch {};
self.client.update() catch {};
// Check if server has accepted the connection
if (self.server.getStats().active_connections.load(.acquire) > 0) {
return;
}
std.Thread.sleep(10 * std.time.ns_per_ms);
}
return Error.ConnectionTimeout;
}
/// Run update() on both instances
pub fn updateBoth(self: *Self) Error!void {
self.server.update() catch {};
self.client.update() catch {};
}
/// Run multiple update cycles
pub fn updateBothN(self: *Self, n: usize) void {
for (0..n) |_| {
self.server.update() catch {};
self.client.update() catch {};
std.Thread.sleep(5 * std.time.ns_per_ms);
}
}
/// Get the connected peer ID (client's view of server)
pub fn getPeerId(self: *const Self) ?PeerId {
return self.connected_peer_id;
}
/// Check if both instances are connected
pub fn isConnected(self: *Self) bool {
return self.server.getStats().active_connections.load(.acquire) > 0 and
self.client.getStats().active_connections.load(.acquire) > 0;
}
/// Process all events on both sides
pub fn processAllEvents(self: *Self) void {
_ = self.server.processAllEvents();
_ = self.client.processAllEvents();
}
/// Configuration overrides for testing
pub const ConfigOverrides = struct {
enable_noise: ?bool = null,
enable_rate_limiting: ?bool = null,
enable_dos_protection: ?bool = null,
max_connections: ?u32 = null,
connection_timeout: ?u32 = null,
};
fn applyOverrides(config: *P2PConfig, overrides: ConfigOverrides) void {
if (overrides.enable_noise) |v| config.network.enable_noise_encryption = v;
if (overrides.enable_rate_limiting) |v| config.network.enable_rate_limiting = v;
if (overrides.enable_dos_protection) |v| config.network.enable_dos_protection = v;
if (overrides.max_connections) |v| config.network.max_connections = v;
if (overrides.connection_timeout) |v| config.network.connection_timeout = v;
}
/// Get minimal configuration for fast tests
fn getMinimalConfig() P2PConfig {
var config = P2PConfig.default();
// Disable features that slow down tests
config.network.enable_noise_encryption = false;
config.network.enable_rate_limiting = false;
config.network.enable_dos_protection = false;
config.network.enable_nat_traversal = false;
config.network.turn_enabled = false;
// Fast timeouts for tests
config.network.connection_timeout = 5000;
config.network.idle_timeout_ms = 120000;
config.network.health_check_interval_ms = 30000;
config.network.max_connections = 10;
// Minimal event queue
config.events.max_event_queue = 100;
// Disable auto-start for explicit control
config.library.auto_start = false;
config.library.enable_statistics = true;
// Allow sharing from test data directory
config.file_sharing.allowed_share_directories = &[_][]const u8{"tests/test_data"};
return config;
}
};
// Self-tests for the helper
test "TestP2PPair basic init and deinit" {
var pair = try TestP2PPair.init(testing.allocator);
defer pair.deinit();
// Verify instances were created (pointers are non-null after successful init)
try testing.expect(@intFromPtr(pair.server) != 0);
try testing.expect(@intFromPtr(pair.client) != 0);
try testing.expect(pair.connected_peer_id == null);
try testing.expect(!pair.started);
}
// Note: Connection tests are intentionally skipped here because:
// 1. The 41 tests in test_connected_coverage.zig thoroughly exercise connections
// 2. Blocking operations in a single-threaded test environment can cause hangs
// Connection functionality is validated by the integration test suite.
test "TestP2PPair with noise config (no connection)" {
// Just verify we can create a pair with Noise enabled
var pair = try TestP2PPair.initWithConfig(
testing.allocator,
.{ .enable_noise = true },
.{ .enable_noise = true },
);
defer pair.deinit();
// Verify Noise keys were generated
const server_key = pair.server.getNoisePublicKey();
const client_key = pair.client.getNoisePublicKey();
try testing.expect(server_key != null);
try testing.expect(client_key != null);
}