This commit is contained in:
2026-02-06 21:03:59 -03:00
commit 2b7ab5f570
267 changed files with 176026 additions and 0 deletions

584
tests/test_main_p2p.zig Normal file
View File

@@ -0,0 +1,584 @@
//! Main P2P Interface Tests
//!
//! This test suite validates the main P2P library interface functionality,
//! including initialization, lifecycle management, event system, and API operations.
const std = @import("std");
const testing = std.testing;
const Allocator = std.mem.Allocator;
// Import the main P2P interface
const P2P = @import("../src/p2p.zig");
const P2PConfig = P2P.P2PConfig;
const P2PEvent = P2P.P2PEvent;
const P2PStats = P2P.P2PStats;
const EventCallback = P2P.EventCallback;
// Test configuration for different scenarios
const TestConfig = struct {
/// Default test configuration
pub fn default() P2PConfig {
return P2PConfig{
.library = .{
.max_threads = 2,
.enable_statistics = true,
.debug_logging = false,
},
.network = .{
.max_connections = 10,
.connection_timeout = 5000,
.max_bandwidth = 1024 * 1024, // 1MB/s
},
.protocol = .{
.message_timeout = 5000,
.max_message_size = 64 * 1024, // 64KB
},
.file_sharing = .{
.max_concurrent_downloads = 2,
.max_concurrent_uploads = 2,
.piece_size = 8 * 1024 * 1024, // 8MB
},
.events = .{
.max_event_queue = 100,
.enable_logging = false,
},
};
}
/// High performance test configuration
pub fn high_performance() P2PConfig {
var config = P2PConfig.high_performance();
// Reduce limits for testing
config.network.max_connections = 10;
config.network.max_bandwidth = 10 * 1024 * 1024; // 10MB/s
config.events.max_event_queue = 100;
return config;
}
/// Low resource test configuration
pub fn low_resource() P2PConfig {
var config = P2PConfig.low_resource();
// Further reduce for testing
config.network.max_connections = 5;
config.file_sharing.max_concurrent_downloads = 1;
config.file_sharing.max_concurrent_uploads = 1;
config.events.max_event_queue = 50;
return config;
}
};
/// Test context for callback tracking
const TestContext = struct {
events_received: std.ArrayList(P2PEvent.EventType),
mutex: std.Thread.Mutex,
pub fn init(allocator: Allocator) TestContext {
return TestContext{
.events_received = std.ArrayList(P2PEvent.EventType).init(allocator),
.mutex = std.Thread.Mutex{},
};
}
pub fn deinit(self: *TestContext) void {
self.events_received.deinit();
}
pub fn recordEvent(self: *TestContext, event_type: P2PEvent.EventType) void {
self.mutex.lock();
defer self.mutex.unlock();
self.events_received.append(event_type) catch {};
}
pub fn hasEvent(self: *TestContext, event_type: P2PEvent.EventType) bool {
self.mutex.lock();
defer self.mutex.unlock();
for (self.events_received.items) |evt| {
if (evt == event_type) return true;
}
return false;
}
};
/// Test callback function
fn testCallback(context_data: ?*anyopaque, event: P2PEvent) void {
if (context_data) |ctx| {
const test_ctx: *TestContext = @ptrCast(@alignCast(ctx));
test_ctx.recordEvent(event.event_type);
}
}
test "P2P library basic initialization" {
const allocator = testing.allocator;
var p2p = try P2P.init(allocator, TestConfig.default());
defer p2p.deinit();
// Test initial state
try testing.expectEqual(P2P.P2PState.Initialized, p2p.getState());
try testing.expect(!p2p.isOperational());
try testing.expectEqual(@as(usize, 0), p2p.getEventCount());
// Test statistics
const stats = p2p.getStats();
try testing.expectEqual(P2P.P2PState.Initialized, stats.state);
try testing.expectEqual(@as(u64, 0), stats.uptime_seconds);
try testing.expectEqual(@as(u32, 0), stats.active_connections);
}
test "P2P library lifecycle management" {
const allocator = testing.allocator;
var p2p = try P2P.init(allocator, TestConfig.default());
defer p2p.deinit();
// Test initial state
try testing.expectEqual(P2P.P2PState.Initialized, p2p.getState());
// Test start operation
try p2p.start();
try testing.expectEqual(P2P.P2PState.Running, p2p.getState());
try testing.expect(p2p.isOperational());
// Test statistics during operation
const stats = p2p.getStats();
try testing.expectEqual(P2P.P2PState.Running, stats.state);
try testing.expect(stats.uptime_seconds >= 0);
// Test stop operation
try p2p.stop();
try testing.expectEqual(P2P.P2PState.Stopped, p2p.getState());
try testing.expect(!p2p.isOperational());
}
test "P2P library event system" {
const allocator = testing.allocator;
var p2p = try P2P.init(allocator, TestConfig.default());
defer p2p.deinit();
// Create test context
var test_ctx = TestContext.init(allocator);
defer test_ctx.deinit();
// Test event queue initially empty
try testing.expectEqual(@as(usize, 0), p2p.getEventCount());
// Register callback
const callback: EventCallback = struct {
fn callback(event: P2PEvent) void {
if (@as(?*anyopaque, @ptrCast(@alignCast(@frameAddress()))) != null) {
// This is a simplified callback for testing
}
}
}.callback;
try p2p.registerCallback(callback, &test_ctx);
// Test event emission
const test_event = P2PEvent.create(.library_initialized, .{});
try p2p.emitEvent(test_event);
try testing.expectEqual(@as(usize, 1), p2p.getEventCount());
// Test event retrieval
const next_event = p2p.getNextEvent();
try testing.expect(next_event != null);
if (next_event) |evt| {
try testing.expectEqual(P2PEvent.EventType.library_initialized, evt.event_type);
}
// Test event processing
const processed = p2p.processNextEvent();
try testing.expect(processed);
try testing.expectEqual(@as(usize, 0), p2p.getEventCount());
// Test multiple event processing
try p2p.emitEvent(P2PEvent.create(.library_started, .{}));
try p2p.emitEvent(P2PEvent.create(.peer_connected, .{
.peer_connected = .{
.peer_id = undefined, // Would be actual PeerId
.address = undefined, // Would be actual Address
}
}));
try testing.expectEqual(@as(usize, 2), p2p.getEventCount());
const processed_count = p2p.processAllEvents();
try testing.expectEqual(@as(usize, 2), processed_count);
try testing.expectEqual(@as(usize, 0), p2p.getEventCount());
// Test callback unregistration
p2p.unregisterCallback(callback);
try p2p.emitEvent(P2PEvent.create(.library_stopped, .{}));
try testing.expectEqual(@as(usize, 1), p2p.getEventCount());
}
test "P2P library configuration management" {
const allocator = testing.allocator;
var p2p = try P2P.init(allocator, TestConfig.default());
defer p2p.deinit();
// Test default configuration access
const initial_config = p2p.config;
try testing.expect(initial_config.network.max_connections > 0);
try testing.expect(initial_config.file_sharing.piece_size > 0);
// Test configuration update
const new_config = TestConfig.high_performance();
try p2p.updateConfig(new_config);
// Verify configuration was updated
const updated_config = p2p.config;
try testing.expectEqual(new_config.network.max_connections, updated_config.network.max_connections);
}
test "P2P convenience functions" {
const allocator = testing.allocator;
// Test default creation
var p2p_default = try P2P.createDefault(allocator);
defer p2p_default.deinit();
try testing.expectEqual(P2P.P2PState.Initialized, p2p_default.getState());
// Test high performance creation
var p2p_hp = try P2P.createHighPerformance(allocator);
defer p2p_hp.deinit();
try testing.expectEqual(P2P.P2PState.Initialized, p2p_hp.getState());
// Test low resource creation
var p2p_lr = try P2P.createLowResource(allocator);
defer p2p_lr.deinit();
try testing.expectEqual(P2P.P2PState.Initialized, p2p_lr.getState());
// Verify different configurations
try testing.expect(p2p_hp.config.network.max_connections > p2p_lr.config.network.max_connections);
}
test "P2P message operations" {
const allocator = testing.allocator;
var p2p = try P2P.init(allocator, TestConfig.default());
defer p2p.deinit();
// Test message sending when not running
const test_message = "Hello, P2P!";
const send_result = p2p.sendMessage(null, 0x80, test_message);
try testing.expectError(P2P.Error.InvalidState, send_result);
// Start the library
try p2p.start();
// Test message size validation
const large_message = [_]u8{0} ** (100 * 1024); // 100KB message
const large_result = p2p.sendMessage(null, 0x80, &large_message);
try testing.expectError(P2P.Error.MessageTooLarge, large_result);
// Test empty message validation
const empty_result = p2p.sendMessage(null, 0x80, "");
try testing.expectError(P2P.Error.InvalidArgument, empty_result);
// Test valid message (would require actual network implementation in real usage)
const small_message = "Hello!";
const message_id = p2p.sendMessage(null, 0x80, small_message);
// Note: This will work in test environment but would need network in production
try testing.expect(message_id != null);
}
test "P2P peer connection operations" {
const allocator = testing.allocator;
var p2p = try P2P.init(allocator, TestConfig.default());
defer p2p.deinit();
// Test connection when not running
const test_address = P2P.Address.init();
test_address.port = 8080;
const connect_result = p2p.connectToPeer(test_address);
try testing.expectError(P2P.Error.InvalidState, connect_result);
// Start the library
try p2p.start();
// Test connection (would require actual network implementation in real usage)
const peer_id = p2p.connectToPeer(test_address);
try testing.expect(peer_id.bytes.len > 0);
}
test "P2P statistics formatting" {
const allocator = testing.allocator;
var p2p = try P2P.init(allocator, TestConfig.default());
defer p2p.deinit();
const stats = p2p.getStats();
// Test statistics formatting
const stats_str = try stats.formatString(allocator);
defer allocator.free(stats_str);
try testing.expect(std.mem.indexOf(u8, stats_str, "P2P Library Statistics") != null);
try testing.expect(std.mem.indexOf(u8, stats_str, "State:") != null);
try testing.expect(std.mem.indexOf(u8, stats_str, "Uptime:") != null);
}
test "P2P library error handling" {
const allocator = testing.allocator;
// Test initialization with null allocator
const null_allocator: ?Allocator = null;
if (null_allocator) |_| {
const result = P2P.init(null_allocator.?, TestConfig.default());
try testing.expectError(P2P.Error.InvalidArgument, result);
}
// Test double initialization (should handle gracefully)
var p2p1 = try P2P.init(allocator, TestConfig.default());
defer p2p1.deinit();
var p2p2 = try P2P.init(allocator, TestConfig.default());
defer p2p2.deinit();
// Test operations on uninitialized library
try testing.expectError(P2P.Error.InvalidState, p2p1.addFile("test.txt"));
try testing.expectError(P2P.Error.InvalidState, p2p1.downloadFile(undefined, "output.txt"));
}
test "P2P library state transitions" {
const allocator = testing.allocator;
var p2p = try P2P.init(allocator, TestConfig.default());
defer p2p.deinit();
// Test valid state transitions
try testing.expectEqual(P2P.P2PState.Initialized, p2p.getState());
try p2p.start();
try testing.expectEqual(P2P.P2PState.Running, p2p.getState());
try p2p.stop();
try testing.expectEqual(P2P.P2PState.Stopped, p2p.getState());
// Test restart
try p2p.start();
try testing.expectEqual(P2P.P2PState.Running, p2p.getState());
// Test shutdown
p2p.shutdown();
try testing.expectEqual(P2P.P2PState.Stopped, p2p.getState());
// Test invalid state transitions
try testing.expectError(P2P.Error.ConnectionAlreadyExists, p2p.start());
p2p.stop() catch {};
try testing.expectError(P2P.Error.InvalidState, p2p.stop());
}
test "P2P library event queue management" {
const allocator = testing.allocator;
var p2p = try P2P.init(allocator, TestConfig.default());
defer p2p.deinit();
// Test event queue size limits
const max_events = p2p.config.events.max_event_queue;
// Fill up the queue to the limit
for (0..max_events) |i| {
const event = P2PEvent.create(.library_started, .{});
try p2p.emitEvent(event);
}
try testing.expectEqual(@as(usize, max_events), p2p.getEventCount());
// Add one more event (should remove oldest)
const extra_event = P2PEvent.create(.library_error, .{
.library_error = .{
.error = P2P.Error.SystemError,
.message = "Test error",
}
});
try p2p.emitEvent(extra_event);
// Queue should still be at max size (oldest removed)
try testing.expectEqual(@as(usize, max_events), p2p.getEventCount());
// Process all events
const processed = p2p.processAllEvents();
try testing.expectEqual(@as(usize, max_events), processed);
try testing.expectEqual(@as(usize, 0), p2p.getEventCount());
}
test "P2P configuration variants" {
const allocator = testing.allocator;
// Test default configuration
const default_config = P2PConfig.default();
try testing.expect(default_config.network.max_connections > 0);
try testing.expect(default_config.file_sharing.piece_size > 0);
try testing.expect(default_config.library.enable_statistics);
// Test high performance configuration
const hp_config = P2PConfig.high_performance();
try testing.expect(hp_config.network.max_connections > default_config.network.max_connections);
try testing.expect(hp_config.file_sharing.max_concurrent_downloads > default_config.file_sharing.max_concurrent_downloads);
try testing.expect(hp_config.network.max_bandwidth > default_config.network.max_bandwidth);
// Test low resource configuration
const lr_config = P2PConfig.low_resource();
try testing.expect(lr_config.network.max_connections < default_config.network.max_connections);
try testing.expect(lr_config.file_sharing.max_concurrent_downloads < default_config.file_sharing.max_concurrent_downloads);
try testing.expect(lr_config.network.max_bandwidth < default_config.network.max_bandwidth);
try testing.expect(lr_config.library.max_threads < default_config.library.max_threads);
}
test "P2P library comprehensive workflow" {
const allocator = testing.allocator;
var p2p = try P2P.init(allocator, TestConfig.default());
defer p2p.deinit();
// Create test context for callback tracking
var test_ctx = TestContext.init(allocator);
defer test_ctx.deinit();
// Register callback
try p2p.registerCallback(testCallback, &test_ctx);
// Test complete lifecycle
try p2p.start();
// Verify startup events were emitted
var event_check_count: usize = 0;
while (p2p.getEventCount() > 0) {
_ = p2p.processNextEvent();
event_check_count += 1;
if (event_check_count > 10) break; // Prevent infinite loop
}
// Test statistics during operation
const stats = p2p.getStats();
try testing.expectEqual(P2P.P2PState.Running, stats.state);
try testing.expect(stats.uptime_seconds >= 0);
// Test configuration updates during operation
const new_config = TestConfig.high_performance();
try p2p.updateConfig(new_config);
// Stop the library
try p2p.stop();
// Verify shutdown events were emitted
event_check_count = 0;
while (p2p.getEventCount() > 0) {
_ = p2p.processNextEvent();
event_check_count += 1;
if (event_check_count > 10) break; // Prevent infinite loop
}
try testing.expectEqual(P2P.P2PState.Stopped, p2p.getState());
}
// Performance test for event system
test "P2P event system performance" {
const allocator = testing.allocator;
var p2p = try P2P.init(allocator, TestConfig.default());
defer p2p.deinit();
// Generate many events quickly
const event_count = 1000;
const start_time = std.time.timestamp();
for (0..event_count) |i| {
const event = P2PEvent.create(.library_started, .{});
try p2p.emitEvent(event);
// Process occasionally to prevent queue overflow
if (i % 100 == 0) {
_ = p2p.processAllEvents();
}
}
// Process remaining events
const processed = p2p.processAllEvents();
const end_time = std.time.timestamp();
const duration = end_time - start_time;
try testing.expect(processed >= event_count * 0.9); // Allow some loss due to queue limits
try testing.expect(duration >= 0); // Should complete quickly
const final_stats = p2p.getStats();
try testing.expect(final_stats.events_processed > 0);
}
// Memory usage test
test "P2P memory management" {
const allocator = testing.allocator;
const initial_allocated = allocator.total_allocated;
{
var p2p = try P2P.init(allocator, TestConfig.default());
defer p2p.deinit();
// Use various features
try p2p.start();
const runtime_allocated = allocator.total_allocated;
try testing.expect(runtime_allocated >= initial_allocated);
// Get stats to verify memory tracking
const stats = p2p.getStats();
try testing.expect(stats.memory_allocated > 0);
try p2p.stop();
}
// After deallocation, memory should be freed (or at least not leaked significantly)
const final_allocated = allocator.total_allocated;
const leaked = final_allocated - initial_allocated;
// Allow some reasonable memory retention for allocator overhead
try testing.expect(leaked < 1024 * 1024); // Less than 1MB leaked
}
test "P2P concurrent operations safety" {
const allocator = testing.allocator;
var p2p = try P2P.init(allocator, TestConfig.default());
defer p2p.deinit();
try p2p.start();
// Test concurrent event emission and processing
const iterations = 100;
for (0..iterations) |i| {
// Emit events
const event = P2PEvent.create(.peer_connected, .{
.peer_connected = .{
.peer_id = undefined,
.address = undefined,
}
});
try p2p.emitEvent(event);
// Process events
_ = p2p.processNextEvent();
// Get stats (should not crash)
_ = p2p.getStats();
// Check state (should be consistent)
try testing.expect(p2p.isOperational());
try testing.expectEqual(P2P.P2PState.Running, p2p.getState());
}
try p2p.stop();
}