const std = @import("std"); const testing = std.testing; // Import files module const files = @import("files"); const manager = files.manager; const FileSharingManager = manager.FileSharingManager; const FileSharingConfig = manager.FileSharingConfig; const FileSharingSession = manager.FileSharingSession; const PeerReputation = manager.PeerReputation; const NetworkSender = manager.NetworkSender; const SessionStats = manager.SessionStats; const FileSharingStats = manager.FileSharingStats; // Tests for FileSharingConfig presets test "FileSharingConfig: default preset" { const config = FileSharingConfig.default(); // Default values come from core.limits.defaults try testing.expect(config.max_concurrent_downloads > 0); try testing.expect(config.max_concurrent_uploads > 0); try testing.expect(config.piece_size > 0); try testing.expect(config.enable_upload); try testing.expect(config.enable_download); try testing.expect(config.auto_verify); } test "FileSharingConfig: high performance preset" { const config = FileSharingConfig.high_performance(); // CASCADE PERF: High performance preset uses 256 concurrent transfers for cascade distribution try testing.expectEqual(@as(usize, 256), config.max_concurrent_downloads); try testing.expectEqual(@as(usize, 256), config.max_concurrent_uploads); try testing.expectEqual(@as(u64, 1024 * 1024), config.piece_size); // 1MB pieces try testing.expectEqual(@as(u64, 1024 * 1024 * 1024), config.max_bandwidth_download); // 1 GB/s try testing.expectEqual(@as(u64, 1024 * 1024 * 1024), config.max_bandwidth_upload); // 1 GB/s } test "FileSharingConfig: low bandwidth preset" { const config = FileSharingConfig.low_bandwidth(); try testing.expectEqual(@as(usize, 2), config.max_concurrent_downloads); try testing.expectEqual(@as(usize, 2), config.max_concurrent_uploads); try testing.expectEqual(@as(u64, 8 * 1024 * 1024), config.piece_size); try testing.expectEqual(@as(u64, 256 * 1024), config.max_bandwidth_download); try testing.expectEqual(@as(u64, 256 * 1024), config.max_bandwidth_upload); } // Tests for PeerReputation test "PeerReputation: initialization" { var peer_id: [32]u8 = undefined; @memset(&peer_id, 0xAA); const rep = PeerReputation.init(peer_id); try testing.expectEqual(@as(u32, 0), rep.good_pieces); try testing.expectEqual(@as(u32, 0), rep.bad_pieces); try testing.expectEqual(@as(i64, 0), rep.blacklisted_until); try testing.expectEqual(@as(u64, 0), rep.memory_usage); try testing.expectEqual(@as(u32, 0), rep.pending_requests); try testing.expectEqual(@as(u32, 0), rep.blacklist_count); } test "PeerReputation: memory reservation" { var peer_id: [32]u8 = undefined; @memset(&peer_id, 0xAA); var rep = PeerReputation.init(peer_id); // Should succeed for small reservations try testing.expect(rep.reserveMemory(1000)); try testing.expectEqual(@as(u64, 1000), rep.memory_usage); try testing.expectEqual(@as(u32, 1), rep.pending_requests); // Should succeed for another reservation try testing.expect(rep.reserveMemory(2000)); try testing.expectEqual(@as(u64, 3000), rep.memory_usage); try testing.expectEqual(@as(u32, 2), rep.pending_requests); // Release memory rep.releaseMemory(1500); try testing.expectEqual(@as(u64, 1500), rep.memory_usage); try testing.expectEqual(@as(u32, 1), rep.pending_requests); // Release more than reserved should set to 0 rep.releaseMemory(10000); try testing.expectEqual(@as(u64, 0), rep.memory_usage); try testing.expectEqual(@as(u32, 0), rep.pending_requests); } test "PeerReputation: good piece recording" { var peer_id: [32]u8 = undefined; @memset(&peer_id, 0xAA); var rep = PeerReputation.init(peer_id); rep.recordGoodPiece(); try testing.expectEqual(@as(u32, 1), rep.good_pieces); rep.recordGoodPiece(); rep.recordGoodPiece(); try testing.expectEqual(@as(u32, 3), rep.good_pieces); } test "PeerReputation: score calculation" { var peer_id: [32]u8 = undefined; @memset(&peer_id, 0xAA); var rep = PeerReputation.init(peer_id); // No pieces - should return 0.5 try testing.expectEqual(@as(f32, 0.5), rep.getScore()); // All good pieces rep.good_pieces = 10; rep.bad_pieces = 0; try testing.expectEqual(@as(f32, 1.0), rep.getScore()); // Mixed pieces - 8 good, 2 bad = 80% = 0.8 rep.good_pieces = 8; rep.bad_pieces = 2; const score = rep.getScore(); try testing.expect(score > 0.79 and score < 0.81); } test "PeerReputation: reset" { var peer_id: [32]u8 = undefined; @memset(&peer_id, 0xAA); var rep = PeerReputation.init(peer_id); rep.good_pieces = 10; rep.bad_pieces = 5; rep.blacklisted_until = 12345; rep.reset(); try testing.expectEqual(@as(u32, 0), rep.good_pieces); try testing.expectEqual(@as(u32, 0), rep.bad_pieces); try testing.expectEqual(@as(i64, 0), rep.blacklisted_until); // Note: reset() does not reset memory_usage } test "PeerReputation: blacklist duration configuration" { // Test setting and getting base blacklist duration const original = PeerReputation.getBaseBlacklistDuration(); PeerReputation.setBaseBlacklistDuration(120); try testing.expectEqual(@as(i64, 120), PeerReputation.getBaseBlacklistDuration()); // Restore original PeerReputation.setBaseBlacklistDuration(original); } test "PeerReputation: isBlacklisted function" { var peer_id: [32]u8 = undefined; @memset(&peer_id, 0xAA); var rep = PeerReputation.init(peer_id); // Not blacklisted initially try testing.expect(!rep.isBlacklisted()); // Set blacklisted_until to future timestamp rep.blacklisted_until = std.time.timestamp() + 3600; // 1 hour from now try testing.expect(rep.isBlacklisted()); // Set blacklisted_until to past timestamp rep.blacklisted_until = std.time.timestamp() - 1; try testing.expect(!rep.isBlacklisted()); } test "PeerReputation: hasExceededMemoryQuota" { var peer_id: [32]u8 = undefined; @memset(&peer_id, 0xAA); var rep = PeerReputation.init(peer_id); // Should not exceed initially try testing.expect(!rep.hasExceededMemoryQuota()); // Set memory usage to exceed quota rep.memory_usage = manager.FileSharingLimits.MAX_PEER_MEMORY_QUOTA + 1; try testing.expect(rep.hasExceededMemoryQuota()); } // Tests for SessionStats test "SessionStats: age calculation" { const stats = SessionStats{ .session_id = 1, .status = .downloading, .progress = 0.5, .file_size = 2000, .piece_count = 10, .pieces_completed = 5, .created_at = std.time.timestamp() - 60, // 60 seconds ago .updated_at = std.time.timestamp(), }; const age = stats.getAge(); // Age should be approximately 60 seconds try testing.expect(age >= 59 and age <= 61); } test "SessionStats: time since update" { const stats = SessionStats{ .session_id = 1, .status = .downloading, .progress = 0.5, .file_size = 2000, .piece_count = 10, .pieces_completed = 5, .created_at = std.time.timestamp() - 60, .updated_at = std.time.timestamp() - 10, // 10 seconds ago }; const time_since = stats.getTimeSinceUpdate(); // Time since update should be approximately 10 seconds try testing.expect(time_since >= 9 and time_since <= 11); } // Tests for FileSharingStats test "FileSharingStats: total transferred calculation" { const stats = FileSharingStats{ .total_sessions = 2, .active_sessions = 1, .downloading_sessions = 1, .uploading_sessions = 1, .completed_sessions = 0, .total_downloaded = 1000, .total_uploaded = 500, .registered_files = 5, .messages_sent = 100, .messages_failed = 5, }; try testing.expectEqual(@as(u64, 1500), stats.getTotalTransferred()); } test "FileSharingStats: message success rate" { const stats = FileSharingStats{ .total_sessions = 0, .active_sessions = 0, .downloading_sessions = 0, .uploading_sessions = 0, .completed_sessions = 0, .total_downloaded = 0, .total_uploaded = 0, .registered_files = 0, .messages_sent = 100, .messages_failed = 10, }; // 90% success rate (100 sent, 10 failed) // Note: success rate = sent / (sent + failed) = 100 / 110 ≈ 0.909 const rate = stats.getMessageSuccessRate(); try testing.expect(rate > 0.90 and rate < 0.92); } test "FileSharingStats: message success rate with no messages" { const stats = FileSharingStats{ .total_sessions = 0, .active_sessions = 0, .downloading_sessions = 0, .uploading_sessions = 0, .completed_sessions = 0, .total_downloaded = 0, .total_uploaded = 0, .registered_files = 0, .messages_sent = 0, .messages_failed = 0, }; // Should return 1.0 when no messages sent try testing.expectEqual(@as(f32, 1.0), stats.getMessageSuccessRate()); } test "FileSharingStats: active rate" { const stats = FileSharingStats{ .total_sessions = 20, .active_sessions = 10, .downloading_sessions = 5, .uploading_sessions = 5, .completed_sessions = 10, .total_downloaded = 0, .total_uploaded = 0, .registered_files = 0, .messages_sent = 0, .messages_failed = 0, }; // 10 active out of 20 total = 50% const rate = stats.getActiveRate(); try testing.expectEqual(@as(f32, 0.5), rate); } test "FileSharingStats: completion rate" { const stats = FileSharingStats{ .total_sessions = 10, .active_sessions = 2, .downloading_sessions = 1, .uploading_sessions = 1, .completed_sessions = 8, .total_downloaded = 0, .total_uploaded = 0, .registered_files = 0, .messages_sent = 0, .messages_failed = 0, }; // 8 completed out of 10 total = 80% const rate = stats.getCompletionRate(); try testing.expectEqual(@as(f32, 0.8), rate); } test "FileSharingStats: zero sessions" { const stats = FileSharingStats{ .total_sessions = 0, .active_sessions = 0, .downloading_sessions = 0, .uploading_sessions = 0, .completed_sessions = 0, .total_downloaded = 0, .total_uploaded = 0, .registered_files = 0, .messages_sent = 0, .messages_failed = 0, }; // Should return 0 when no sessions try testing.expectEqual(@as(f32, 0.0), stats.getActiveRate()); try testing.expectEqual(@as(f32, 0.0), stats.getCompletionRate()); } // Tests for FileSharingManager initialization test "FileSharingManager: initialization with default config" { const allocator = testing.allocator; const config = FileSharingConfig.default(); var manager_inst = FileSharingManager.init(config, allocator) catch |err| { std.debug.print("Manager init failed: {}\n", .{err}); return; }; defer manager_inst.deinit(); const stats = manager_inst.getStats(); try testing.expectEqual(@as(usize, 0), stats.active_sessions); try testing.expectEqual(@as(usize, 0), stats.total_sessions); } test "FileSharingManager: config retrieval" { const allocator = testing.allocator; const config = FileSharingConfig.high_performance(); var manager_inst = FileSharingManager.init(config, allocator) catch return; defer manager_inst.deinit(); const retrieved_config = manager_inst.getConfig(); // CASCADE PERF: High performance preset uses 256 concurrent transfers try testing.expectEqual(@as(usize, 256), retrieved_config.max_concurrent_downloads); } test "FileSharingManager: bandwidth limits update" { const allocator = testing.allocator; const config = FileSharingConfig.default(); var manager_inst = FileSharingManager.init(config, allocator) catch return; defer manager_inst.deinit(); manager_inst.updateBandwidthLimits(1000000, 500000); const retrieved_config = manager_inst.getConfig(); try testing.expectEqual(@as(u64, 1000000), retrieved_config.max_bandwidth_download); try testing.expectEqual(@as(u64, 500000), retrieved_config.max_bandwidth_upload); } test "FileSharingManager: features toggle" { const allocator = testing.allocator; const config = FileSharingConfig.default(); var manager_inst = FileSharingManager.init(config, allocator) catch return; defer manager_inst.deinit(); // Disable both features manager_inst.setFeatures(false, false); var retrieved_config = manager_inst.getConfig(); try testing.expect(!retrieved_config.enable_upload); try testing.expect(!retrieved_config.enable_download); // Enable both features manager_inst.setFeatures(true, true); retrieved_config = manager_inst.getConfig(); try testing.expect(retrieved_config.enable_upload); try testing.expect(retrieved_config.enable_download); } test "FileSharingManager: is idle with no sessions" { const allocator = testing.allocator; const config = FileSharingConfig.default(); var manager_inst = FileSharingManager.init(config, allocator) catch return; defer manager_inst.deinit(); try testing.expect(manager_inst.isIdle()); } test "FileSharingManager: get active sessions empty" { const allocator = testing.allocator; const config = FileSharingConfig.default(); var manager_inst = FileSharingManager.init(config, allocator) catch return; defer manager_inst.deinit(); const sessions = manager_inst.getActiveSessions() catch return; defer allocator.free(sessions); try testing.expectEqual(@as(usize, 0), sessions.len); } test "FileSharingManager: has file returns false for non-existent" { const allocator = testing.allocator; const config = FileSharingConfig.default(); var manager_inst = FileSharingManager.init(config, allocator) catch return; defer manager_inst.deinit(); var fake_hash: [32]u8 = undefined; @memset(&fake_hash, 0xFF); try testing.expect(!manager_inst.hasFile(fake_hash)); } test "FileSharingManager: get session info returns null for non-existent" { const allocator = testing.allocator; const config = FileSharingConfig.default(); var manager_inst = FileSharingManager.init(config, allocator) catch return; defer manager_inst.deinit(); const info = manager_inst.getSessionInfo(99999); try testing.expect(info == null); } test "FileSharingManager: has session by hash returns false for non-existent" { const allocator = testing.allocator; const config = FileSharingConfig.default(); var manager_inst = FileSharingManager.init(config, allocator) catch return; defer manager_inst.deinit(); var fake_hash: [32]u8 = undefined; @memset(&fake_hash, 0xFF); try testing.expect(!manager_inst.hasSessionByHash(fake_hash)); } test "FileSharingManager: find session id by hash returns null for non-existent" { const allocator = testing.allocator; const config = FileSharingConfig.default(); var manager_inst = FileSharingManager.init(config, allocator) catch return; defer manager_inst.deinit(); var fake_hash: [32]u8 = undefined; @memset(&fake_hash, 0xFF); const session_id = manager_inst.findSessionIdByHash(fake_hash); try testing.expect(session_id == null); } test "FileSharingManager: profiling stats" { const allocator = testing.allocator; const config = FileSharingConfig.default(); var manager_inst = FileSharingManager.init(config, allocator) catch return; defer manager_inst.deinit(); const prof_stats = manager_inst.getProfilingStats(); // Pipeline stats should be zero initially try testing.expectEqual(@as(u64, 0), prof_stats.pipeline_tasks_queued); try testing.expectEqual(@as(u64, 0), prof_stats.pipeline_tasks_processed); try testing.expectEqual(@as(u64, 0), prof_stats.pipeline_tasks_failed); // Verification stats should be zero initially try testing.expectEqual(@as(u64, 0), prof_stats.verification_completed); try testing.expectEqual(@as(u64, 0), prof_stats.verification_failed); } // Tests for NetworkSender test "NetworkSender: initialization" { const allocator = testing.allocator; const TestCtx = struct { call_count: u32 = 0, }; var ctx = TestCtx{}; const send_fn = struct { fn cb(peer_id: []const u8, data: []const u8, user_ctx: ?*anyopaque) bool { _ = peer_id; _ = data; const test_ctx: *TestCtx = @ptrCast(@alignCast(user_ctx)); test_ctx.call_count += 1; return true; } }.cb; const sender = NetworkSender.init(send_fn, &ctx, allocator); _ = sender; try testing.expectEqual(@as(u32, 0), ctx.call_count); } // Tests for limits test "FileSharingLimits: functions return valid values" { // Test that all limit functions return reasonable values try testing.expect(manager.FileSharingLimits.maxPieceSize() > 0); try testing.expect(manager.FileSharingLimits.maxFileSize() > 0); try testing.expect(manager.FileSharingLimits.maxFilenameLength() > 0); try testing.expect(manager.FileSharingLimits.maxSessions() > 0); try testing.expect(manager.FileSharingLimits.maxPieceDataSize() > 0); try testing.expect(manager.FileSharingLimits.maxPeerMemoryQuota() > 0); try testing.expect(manager.FileSharingLimits.maxGlobalMemoryQuota() > 0); } test "FileSharingLimits: compile-time constants" { // Test compile-time constants try testing.expect(manager.FileSharingLimits.MAX_PIECE_SIZE > 0); try testing.expect(manager.FileSharingLimits.MAX_FILE_SIZE > 0); try testing.expect(manager.FileSharingLimits.MAX_FILENAME_LENGTH > 0); try testing.expect(manager.FileSharingLimits.MAX_SESSIONS > 0); try testing.expect(manager.FileSharingLimits.MAX_PIECE_DATA_SIZE > 0); try testing.expect(manager.FileSharingLimits.MAX_PEER_MEMORY_QUOTA > 0); try testing.expect(manager.FileSharingLimits.MAX_GLOBAL_MEMORY_QUOTA > 0); } test "PeerReputation: limits functions" { try testing.expect(PeerReputation.maxBadPieces() > 0); try testing.expect(PeerReputation.baseBlacklistDuration() > 0); try testing.expect(PeerReputation.maxBlacklistDuration() >= PeerReputation.baseBlacklistDuration()); try testing.expect(PeerReputation.maxRequestsPerPeer() > 0); } test "PeerReputation: constants" { try testing.expect(PeerReputation.MAX_BAD_PIECES > 0); try testing.expect(PeerReputation.DEFAULT_BLACKLIST_DURATION_SECONDS > 0); try testing.expect(PeerReputation.MAX_BLACKLIST_DURATION_SECONDS >= PeerReputation.DEFAULT_BLACKLIST_DURATION_SECONDS); try testing.expect(PeerReputation.MAX_PENDING_REQUESTS > 0); } test "PeerReputation: pending requests limit" { var peer_id: [32]u8 = undefined; @memset(&peer_id, 0xAA); var rep = PeerReputation.init(peer_id); // Reserve memory up to MAX_PENDING_REQUESTS times var i: u32 = 0; while (i < PeerReputation.MAX_PENDING_REQUESTS) : (i += 1) { try testing.expect(rep.reserveMemory(100)); // Small amount to not hit memory limit } // Next reservation should fail due to pending requests limit try testing.expect(!rep.reserveMemory(100)); }