Files
zigp2p/tests/network/test_peer.zig
2026-02-06 21:03:59 -03:00

435 lines
15 KiB
Zig

//! Comprehensive tests for peer management system
//!
//! Tests cover peer creation, management, reputation system,
//! and peer manager operations.
const std = @import("std");
const testing = std.testing;
const Allocator = std.mem.Allocator;
const PeerId = @import("../../src/network/peer.zig").PeerId;
const Peer = @import("../../src/network/peer.zig").Peer;
const PeerManager = @import("../../src/network/peer.zig").PeerManager;
const ConnectionState = @import("../../src/network/peer.zig").ConnectionState;
const PeerCapabilities = @import("../../src/network/peer.zig").PeerCapabilities;
const PeerReputation = @import("../../src/network/peer.zig").PeerReputation;
const PeerStats = @import("../../src/network/peer.zig").PeerStats;
const Address = @import("../../src/core/address.zig").Address;
test "PeerId creation and manipulation" {
const peer_id1 = PeerId.init();
const peer_id2 = PeerId.init();
// Different peer IDs should be different
try testing.expect(!std.mem.eql(u8, &peer_id1.bytes, &peer_id2.bytes));
// String conversion and parsing
const str = PeerId.toString(peer_id1);
const parsed = try PeerId.fromString(&str);
try testing.expect(std.mem.eql(u8, &peer_id1.bytes, &parsed.bytes));
}
test "PeerId string conversion edge cases" {
// Test valid hex string
const valid_str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
const peer_id = try PeerId.fromString(valid_str);
const result_str = PeerId.toString(peer_id);
try testing.expectEqualStrings(valid_str, &result_str);
// Test invalid input lengths
try testing.expectError(error.InvalidInput, PeerId.fromString("short"));
try testing.expectError(error.InvalidInput, PeerId.fromString("toolongstringthatshouldfail"));
// Test invalid hex characters
try testing.expectError(error.InvalidInput, PeerId.fromString("gg000000000000000000000000000000000000000000000000000000000000"));
try testing.expectError(error.InvalidInput, PeerId.fromString("0x000000000000000000000000000000000000000000000000000000000000"));
}
test "Peer creation and initialization" {
const peer_id = PeerId.init();
var address = Address.init();
address.port = 8080;
var peer = Peer.init(peer_id, address);
// Check initial state
try testing.expectEqual(ConnectionState.Disconnected, peer.state);
try testing.expectEqual(peer_id, peer.id);
try testing.expectEqual(address, peer.address);
try testing.expect(peer.last_seen > 0);
try testing.expect(peer.created_at > 0);
}
test "Peer connection state management" {
const peer_id = PeerId.init();
var address = Address.init();
var peer = Peer.init(peer_id, address);
// Initial state should be disconnected
try testing.expect(!peer.isConnected());
// Connect peer
peer.setState(.Connected);
try testing.expect(peer.isConnected());
// Update activity
const activity_before = peer.last_seen;
peer.updateActivity();
try testing.expect(peer.last_seen > activity_before);
// Disconnect peer
peer.setState(.Disconnected);
try testing.expect(!peer.isConnected());
}
test "Peer capabilities configuration" {
const peer_id = PeerId.init();
var address = Address.init();
var peer = Peer.init(peer_id, address);
// Test default capabilities
try testing.expect(!peer.capabilities.relay);
try testing.expect(!peer.capabilities.storage);
try testing.expect(peer.capabilities.discovery);
try testing.expect(peer.capabilities.routing);
try testing.expectEqual(@as(u16, 10), peer.capabilities.max_connections);
try testing.expectEqual(@as(u16, 1), peer.capabilities.protocol_version);
// Modify capabilities
peer.capabilities.relay = true;
peer.capabilities.storage = true;
peer.capabilities.max_connections = 50;
try testing.expect(peer.capabilities.relay);
try testing.expect(peer.capabilities.storage);
try testing.expectEqual(@as(u16, 50), peer.capabilities.max_connections);
}
test "Peer reputation system" {
var reputation = PeerReputation{};
// Test initial reputation
try testing.expectEqual(@as(u8, 50), reputation.reliability);
try testing.expectEqual(@as(u8, 50), reputation.integrity);
try testing.expectEqual(@as(u8, 50), reputation.responsiveness);
try testing.expectEqual(@as(u32, 0), reputation.successful_interactions);
try testing.expectEqual(@as(u32, 0), reputation.failed_interactions);
try testing.expectEqual(@as(u8, 50), reputation.getOverallScore());
// Test success updates
reputation.updateSuccess();
try testing.expect(reputation.successful_interactions == 1);
try testing.expect(reputation.reliability > 50);
try testing.expect(reputation.responsiveness > 50);
try testing.expect(reputation.getOverallScore() > 50);
// Test failure updates
reputation.updateFailure();
try testing.expect(reputation.failed_interactions == 1);
try testing.expect(reputation.reliability < 53); // 51 - 2
try testing.expect(reputation.responsiveness < 52); // Previous value after success - 2
// Test boundaries
reputation.reliability = 0;
reputation.updateFailure();
try testing.expectEqual(@as(u8, 0), reputation.reliability); // Should not go below 0
reputation.reliability = 100;
reputation.updateSuccess();
try testing.expectEqual(@as(u8, 100), reputation.reliability); // Should not go above 100
}
test "Peer statistics tracking" {
const peer_id = PeerId.init();
var address = Address.init();
var peer = Peer.init(peer_id, address);
// Test initial stats
try testing.expectEqual(@as(u64, 0), peer.stats.bytes_sent);
try testing.expectEqual(@as(u64, 0), peer.stats.bytes_received);
try testing.expectEqual(@as(u32, 0), peer.stats.messages_sent);
try testing.expectEqual(@as(u32, 0), peer.stats.messages_received);
try testing.expectEqual(@as(u64, 0), peer.stats.connection_duration_ms);
// Update statistics
peer.updateStats(1024, 2048);
try testing.expectEqual(@as(u64, 1024), peer.stats.bytes_sent);
try testing.expectEqual(@as(u64, 2048), peer.stats.bytes_received);
try testing.expectEqual(@as(u32, 1), peer.stats.messages_sent);
// Multiple updates should accumulate
peer.updateStats(512, 1024);
try testing.expectEqual(@as(u64, 1536), peer.stats.bytes_sent); // 1024 + 512
try testing.expectEqual(@as(u64, 3072), peer.stats.bytes_received); // 2048 + 1024
try testing.expectEqual(@as(u32, 2), peer.stats.messages_sent);
}
test "Peer connection capacity checks" {
const peer_id = PeerId.init();
var address = Address.init();
var peer = Peer.init(peer_id, address);
// Initially disconnected, should not accept connections
try testing.expect(!peer.canAcceptConnection());
// Connect peer
peer.setState(.Connected);
try testing.expect(peer.canAcceptConnection());
// Set max connections to 0
peer.capabilities.max_connections = 0;
try testing.expect(!peer.canAcceptConnection());
// Reset and test with some messages
peer.capabilities.max_connections = 10;
peer.stats.messages_received = 5;
try testing.expect(peer.canAcceptConnection());
peer.stats.messages_received = 10;
try testing.expect(!peer.canAcceptConnection()); // At capacity
}
test "PeerManager basic operations" {
const allocator = testing.allocator;
var manager = PeerManager.init(allocator);
defer manager.deinit();
// Test initial state
try testing.expectEqual(@as(usize, 0), manager.getPeerCount());
try testing.expectEqual(@as(usize, 0), manager.getConnectedCount());
// Add first peer
var address1 = Address.init();
address1.port = 8080;
const peer1 = try manager.addPeer(address1);
try testing.expectEqual(@as(usize, 1), manager.getPeerCount());
try testing.expectEqual(@as(usize, 0), manager.getConnectedCount());
// Add second peer
var address2 = Address.init();
address2.port = 9090;
const peer2 = try manager.addPeer(address2);
try testing.expectEqual(@as(usize, 2), manager.getPeerCount());
// Test peer retrieval
const found_peer1 = manager.getPeerByAddress(address1);
try testing.expect(found_peer1 != null);
try testing.expectEqual(peer1, found_peer1.?);
const found_peer2 = manager.getPeerByAddress(address2);
try testing.expect(found_peer2 != null);
try testing.expectEqual(peer2, found_peer2.?);
// Test peer retrieval by ID
const found_by_id1 = manager.getPeerById(peer1.id);
try testing.expect(found_by_id1 != null);
try testing.expectEqual(peer1, found_by_id1.?);
const found_by_id2 = manager.getPeerById(peer2.id);
try testing.expect(found_by_id2 != null);
try testing.expectEqual(peer2, found_by_id2.?);
}
test "PeerManager connection state tracking" {
const allocator = testing.allocator;
var manager = PeerManager.init(allocator);
defer manager.deinit();
var address = Address.init();
address.port = 8080;
const peer = try manager.addPeer(address);
// Initially disconnected
try testing.expectEqual(@as(usize, 0), manager.getConnectedCount());
// Connect peer
peer.setState(.Connected);
try testing.expectEqual(@as(usize, 1), manager.getConnectedCount());
// Disconnect peer
peer.setState(.Disconnecting);
try testing.expectEqual(@as(usize, 0), manager.getConnectedCount());
}
test "PeerManager peer removal" {
const allocator = testing.allocator;
var manager = PeerManager.init(allocator);
defer manager.deinit();
var address = Address.init();
address.port = 8080;
const peer = try manager.addPeer(address);
try testing.expectEqual(@as(usize, 1), manager.getPeerCount());
// Remove peer
const removed = try manager.removePeerByAddress(address);
try testing.expect(removed);
try testing.expectEqual(@as(usize, 0), manager.getPeerCount());
// Try to remove non-existent peer
const not_removed = try manager.removePeerByAddress(address);
try testing.expect(!not_removed);
}
test "PeerManager getConnectedPeers" {
const allocator = testing.allocator;
var manager = PeerManager.init(allocator);
defer manager.deinit();
// Add multiple peers with different states
var address1 = Address.init();
address1.port = 8080;
const peer1 = try manager.addPeer(address1);
peer1.setState(.Connected);
var address2 = Address.init();
address2.port = 9090;
const peer2 = try manager.addPeer(address2);
peer2.setState(.Disconnected);
var address3 = Address.init();
address3.port = 7070;
const peer3 = try manager.addPeer(address3);
peer3.setState(.Connected);
const connected_peers = try manager.getConnectedPeers();
defer connected_peers.deinit();
try testing.expectEqual(@as(usize, 2), connected_peers.items.len);
// Check that both connected peers are in the list
var found_peer1 = false;
var found_peer3 = false;
for (connected_peers.items) |p| {
if (p == peer1) found_peer1 = true;
if (p == peer3) found_peer3 = true;
}
try testing.expect(found_peer1);
try testing.expect(found_peer3);
try testing.expect(!found_peer3 or found_peer1); // Both should be found
}
test "PeerManager edge cases" {
const allocator = testing.allocator;
var manager = PeerManager.init(allocator);
defer manager.deinit();
// Test with same address (should create different peers with different IDs)
var address = Address.init();
address.port = 8080;
const peer1 = try manager.addPeer(address);
const peer2 = try manager.addPeer(address);
try testing.expect(peer1 != peer2);
try testing.expect(!std.mem.eql(u8, &peer1.id.bytes, &peer2.id.bytes));
try testing.expectEqual(@as(usize, 2), manager.getPeerCount());
// Both should be retrievable
try testing.expect(manager.getPeerById(peer1.id) != null);
try testing.expect(manager.getPeerById(peer2.id) != null);
}
test "PeerManager memory management" {
const allocator = testing.allocator;
var manager = PeerManager.init(allocator);
// Add and remove many peers to test memory management
for (0..100) |i| {
var address = Address.init();
address.port = @as(u16, 8000 + i);
const peer = try manager.addPeer(address);
// Connect and disconnect
peer.setState(.Connected);
peer.setState(.Disconnected);
// Remove peer
_ = try manager.removePeerByAddress(address);
}
try testing.expectEqual(@as(usize, 0), manager.getPeerCount());
// Cleanup
manager.deinit();
}
test "Performance test - many peers" {
const allocator = testing.allocator;
var manager = PeerManager.init(allocator);
defer manager.deinit();
const peer_count = 1000;
// Add many peers
for (0..peer_count) |i| {
var address = Address.init();
address.port = @as(u16, 8000 + i);
const peer = try manager.addPeer(address);
// Randomly set connection states
if (i % 3 == 0) {
peer.setState(.Connected);
}
}
try testing.expectEqual(peer_count, manager.getPeerCount());
// Test retrieval performance
const start_time = std.time.timestamp();
for (0..peer_count) |i| {
var address = Address.init();
address.port = @as(u16, 8000 + i);
_ = manager.getPeerByAddress(address);
}
const end_time = std.time.timestamp();
// Should be able to retrieve all peers quickly
try testing.expect(end_time - start_time < 5); // Less than 5 seconds
// Test connected count
const connected_count = manager.getConnectedCount();
try testing.expect(connected_count > 0);
try testing.expect(connected_count <= peer_count / 3); // Roughly 1/3 should be connected
}
test "Thread safety considerations" {
// This test verifies that peer data structures are properly separated
// and don't have shared mutable state that could cause race conditions
const allocator = testing.allocator;
var manager = PeerManager.init(allocator);
defer manager.deinit();
var address = Address.init();
address.port = 8080;
const peer = try manager.addPeer(address);
// Each peer should have its own reputation and stats
peer.reputation.updateSuccess();
peer.updateStats(100, 200);
// Add another peer to ensure no cross-contamination
var address2 = Address.init();
address2.port = 9090;
const peer2 = try manager.addPeer(address2);
// peer2 should have default values
try testing.expectEqual(@as(u8, 50), peer2.reputation.getOverallScore());
try testing.expectEqual(@as(u64, 0), peer2.stats.bytes_sent);
// peer1 should have its modified values
try testing.expect(peer1.reputation.getOverallScore() > 50);
try testing.expectEqual(@as(u64, 100), peer1.stats.bytes_sent);
}