Files
zigp2p/tests/integration/test_error_handling.zig

263 lines
9.8 KiB
Zig

//! Comprehensive error handling tests
//!
//! This test suite verifies that:
//! 1. Errors are properly logged with context
//! 2. Error metrics are accurately recorded
//! 3. Broadcast operations return accurate counts
//! 4. Cleanup routines handle OOM conditions gracefully
//! 5. No silent error swallowing occurs
const std = @import("std");
const testing = std.testing;
const core = @import("core");
const protocol = @import("protocol");
const network = @import("network");
const Error = core.errors.Error;
const ErrorMetrics = core.errors.ErrorMetrics;
const ErrorStats = core.errors.ErrorStats;
test "ErrorMetrics records errors correctly" {
var metrics = ErrorMetrics.init(testing.allocator);
defer metrics.deinit();
// Record various error types
metrics.recordError(Error.ConnectionRefused);
metrics.recordError(Error.ConnectionRefused);
metrics.recordError(Error.NetworkError);
metrics.recordError(Error.OutOfMemory);
const snapshot = metrics.getSnapshot();
try testing.expectEqual(@as(u64, 4), snapshot.total_errors);
try testing.expectEqual(@as(usize, 3), snapshot.unique_error_types);
// Verify individual counts
try testing.expectEqual(@as(u64, 2), metrics.getErrorCount(Error.ConnectionRefused));
try testing.expectEqual(@as(u64, 1), metrics.getErrorCount(Error.NetworkError));
try testing.expectEqual(@as(u64, 1), metrics.getErrorCount(Error.OutOfMemory));
try testing.expectEqual(@as(u64, 0), metrics.getErrorCount(Error.InvalidData));
}
test "ErrorStats atomic operations" {
var stats = ErrorStats.init();
// Record errors from multiple "threads" (simulated)
stats.record(Error.ConnectionRefused);
stats.record(Error.ConnectionRefused);
stats.record(Error.NetworkError);
try testing.expectEqual(@as(u64, 3), stats.getTotal());
try testing.expectEqual(@as(u64, 2), stats.getCount(Error.ConnectionRefused));
try testing.expectEqual(@as(u64, 1), stats.getCount(Error.NetworkError));
}
test "logError actually logs the error" {
// This test verifies that logError now uses the format string
const err = core.errors.logError(Error.ConnectionRefused, "Failed to connect to peer {s}", .{"peer123"});
try testing.expectEqual(Error.ConnectionRefused, err);
// Note: The actual logging to stderr is tested by observing output during test runs
}
test "unexpected logs expected and actual values" {
const err = core.errors.unexpected("expected_value", "actual_value");
try testing.expectEqual(Error.Unexpected, err);
// Note: The actual logging to stderr is tested by observing output during test runs
}
test "router cleanup handles allocation failures" {
const allocator = testing.allocator;
// IMP-CRIT-2: Use test local_node_id
const test_local_id: protocol.message.NodeId = .{0xFF} ** 32;
var router = protocol.router.MessageRouter.init(allocator, test_local_id);
defer router.deinit();
// Add some routes (add as neighbors first to allow unsigned routes)
var dest1: protocol.message.NodeId = .{0} ** protocol.protocol.Network.NODE_ID_SIZE;
dest1[0] = 1;
var dest2: protocol.message.NodeId = .{0} ** protocol.protocol.Network.NODE_ID_SIZE;
dest2[0] = 2;
try router.addNeighbor(dest1);
try router.addNeighbor(dest2);
try router.addRoute(dest1, dest1, 1);
try router.addRoute(dest2, dest2, 1);
// Cleanup should work even with potential allocation failures
router.cleanupExpiredRoutes(0); // Make all routes appear expired
// Should have invalidated routes
try testing.expect(!router.isReachable(dest1));
try testing.expect(!router.isReachable(dest2));
}
test "replay protection cleanup handles allocation failures" {
var protector = protocol.replay_protection.ReplayProtector.init(testing.allocator);
defer protector.deinit();
const current_time = std.time.timestamp();
const old_time = current_time - 7200; // 2 hours ago
const peer_id = [_]u8{1} ** 32;
// Add some old messages that should be cleaned up
try protector.checkMessage(1, old_time, 1000, 0, peer_id, 0);
try protector.checkMessage(2, old_time, 1001, 0, peer_id, 0);
// Force cleanup - should handle any allocation failures gracefully
protector.forceCleanup();
// Verify cleanup occurred (old messages should be removed)
const stats = protector.getStats();
try testing.expectEqual(@as(usize, 0), stats.tracked_messages);
try testing.expectEqual(@as(usize, 0), stats.tracked_nonces);
}
test "rate limiter cleanup handles allocation failures" {
const allocator = testing.allocator;
var limiter = core.rate_limiter.ConnectionRateLimiter.init(
allocator,
.{ .tokens_per_second = 10, .burst_size = 10 },
.{ .tokens_per_second = 5, .burst_size = 5 },
);
defer limiter.deinit();
// Accept some connections
_ = limiter.tryAcceptConnection("192.168.1.1");
_ = limiter.tryAcceptConnection("192.168.1.2");
// Brief pause then cleanup (test verifies cleanup runs without errors)
std.time.sleep(10 * std.time.ns_per_ms);
// Cleanup should work even with potential allocation failures
limiter.cleanup();
// After cleanup, stale limiters should be removed (if enough time passed)
}
test "network manager broadcast returns accurate counts" {
const allocator = testing.allocator;
// Create a simple test setup
var connections = std.AutoHashMap(network.peer.PeerId, *core.socket.Socket).init(allocator);
defer connections.deinit();
var manager = network.network_manager.NetworkManager.init(allocator, &connections);
defer manager.deinit();
const test_data = "test message";
// Test broadcasting with no connections
const result1 = try manager.broadcastMessage(test_data);
try testing.expectEqual(@as(usize, 0), result1.sent_count);
try testing.expectEqual(@as(usize, 0), result1.failed_count);
try testing.expectEqual(@as(usize, 0), result1.total_peers);
// Note: Testing with actual connections would require mock sockets
// which is complex. The important thing is that we return a struct
// with counts instead of silently ignoring failures.
}
test "handler metrics track failures correctly" {
var metrics = protocol.handler.HandlerMetrics.init();
// Record some successes and failures
metrics.recordMessageProcessed(0.1);
metrics.recordMessageProcessed(0.2);
metrics.recordMessageFailed();
metrics.recordMessageProcessed(0.15);
metrics.recordMessageFailed();
// Verify counts using atomic loads
try testing.expectEqual(@as(u64, 3), metrics.messages_processed.load(.monotonic));
try testing.expectEqual(@as(u64, 2), metrics.messages_failed.load(.monotonic));
// Verify success rate
const success_rate = metrics.getSuccessRate();
try testing.expect(success_rate > 0.5); // 3/5 = 60%
try testing.expect(success_rate < 0.7);
}
test "global error stats recording" {
var stats = ErrorStats.init();
core.errors.setGlobalErrorStats(&stats);
defer core.errors.setGlobalErrorStats(null);
// Record errors globally
core.errors.recordGlobalError(Error.ConnectionRefused);
core.errors.recordGlobalError(Error.NetworkError);
core.errors.recordGlobalError(Error.ConnectionRefused);
try testing.expectEqual(@as(u64, 3), stats.getTotal());
try testing.expectEqual(@as(u64, 2), stats.getCount(Error.ConnectionRefused));
try testing.expectEqual(@as(u64, 1), stats.getCount(Error.NetworkError));
}
test "cleanup operations with extreme memory pressure" {
// Use a failing allocator to simulate OOM conditions
var failing_allocator = testing.FailingAllocator.init(testing.allocator, .{ .fail_index = 1 });
const allocator = failing_allocator.allocator();
// Test router cleanup under OOM
{
// IMP-CRIT-2: Use test local_node_id
const test_local_id: protocol.message.NodeId = .{0xFF} ** 32;
var router = protocol.router.MessageRouter.init(allocator, test_local_id);
defer router.deinit();
// This should handle allocation failures gracefully
router.cleanupExpiredRoutes(0);
}
// Test replay protection cleanup under OOM
{
failing_allocator.reset();
var protector = protocol.replay_protection.ReplayProtector.init(allocator);
defer protector.deinit();
// This should handle allocation failures gracefully
const current_time = std.time.timestamp();
protector.cleanup(current_time);
}
}
test "error context operations" {
var context = core.errors.ErrorContext.init("connect", "network");
context = context.withPeerId("peer123");
context = context.withConnectionId("conn456");
try testing.expectEqualSlices(u8, "connect", context.operation);
try testing.expectEqualSlices(u8, "network", context.component);
try testing.expectEqualSlices(u8, "peer123", context.peer_id.?);
try testing.expectEqualSlices(u8, "conn456", context.connection_id.?);
}
test "error result creation with context" {
const context = core.errors.ErrorContext.init("send", "network")
.withPeerId("peer789");
const result = try core.errors.ErrorResult.create(
Error.ConnectionRefused,
"Connection refused by peer",
context,
"test.zig",
100,
"testFunction",
testing.allocator,
);
defer testing.allocator.free(result.info.context);
try testing.expectEqual(Error.ConnectionRefused, result.err);
try testing.expect(result.info.context.len > 0);
}
test "broadcast result structure" {
const result = network.network_manager.NetworkManager.BroadcastResult{
.sent_count = 5,
.failed_count = 2,
.total_peers = 7,
};
try testing.expectEqual(@as(usize, 5), result.sent_count);
try testing.expectEqual(@as(usize, 2), result.failed_count);
try testing.expectEqual(@as(usize, 7), result.total_peers);
}