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

View File

@@ -0,0 +1,858 @@
const std = @import("std");
const testing = std.testing;
const fs = std.fs;
const files = @import("files");
const core = @import("core");
const manager = files.manager;
const FileSharingManager = manager.FileSharingManager;
const FileSharingConfig = manager.FileSharingConfig;
const SessionStats = manager.SessionStats;
const Error = core.errors.Error;
// ============================================================================
// Helper: Create config that allows /tmp
// ============================================================================
// Test data directory - use project's test directory which is allowed
const TEST_DATA_DIR = "/Users/mdt./Projects/zig-p2p/tests/test_data";
fn createConfigWithTestDir() FileSharingConfig {
var config = FileSharingConfig.default();
// Allow the test data directory for file sharing tests
config.temp_dir = TEST_DATA_DIR;
config.allowed_share_directories = &[_][]const u8{TEST_DATA_DIR};
return config;
}
// Named struct type for temp file result
const TempFileResult = struct {
path: [128]u8,
len: usize,
pub fn getPath(self: *const TempFileResult) []const u8 {
return self.path[0..self.len];
}
};
// Helper to ensure test directory exists
fn ensureTestDir() !void {
std.fs.makeDirAbsolute(TEST_DATA_DIR) catch |err| {
if (err != error.PathAlreadyExists) return err;
};
}
// Helper to create temp file with actual content
fn createTempFile(content: []const u8) !TempFileResult {
try ensureTestDir();
var rand_bytes: [8]u8 = undefined;
std.crypto.random.bytes(&rand_bytes);
var result = TempFileResult{ .path = undefined, .len = 0 };
const prefix = TEST_DATA_DIR ++ "/test_";
@memcpy(result.path[0..prefix.len], prefix);
var pos: usize = prefix.len;
for (rand_bytes) |b| {
result.path[pos] = "0123456789abcdef"[b >> 4];
result.path[pos + 1] = "0123456789abcdef"[b & 0xF];
pos += 2;
}
const suffix = ".dat";
@memcpy(result.path[pos..][0..suffix.len], suffix);
result.len = pos + suffix.len;
const file = try std.fs.createFileAbsolute(result.path[0..result.len], .{});
defer file.close();
try file.writeAll(content);
return result;
}
fn deleteTempFile(path: []const u8) void {
std.fs.deleteFileAbsolute(path) catch {};
}
// ============================================================================
// FileSharingManager with Real Files
// ============================================================================
test "FileSharingManager: addFile with real temp file" {
const allocator = testing.allocator;
const config = createConfigWithTestDir();
var mgr = FileSharingManager.init(config, allocator) catch |err| {
std.debug.print("Manager init failed (may need /tmp access): {}\n", .{err});
return;
};
defer mgr.deinit();
// Create actual temp file
const content = "This is real file content for testing file sharing!";
const temp = createTempFile(content) catch |err| {
std.debug.print("Failed to create temp file: {}\n", .{err});
return;
};
defer deleteTempFile(temp.path[0..temp.len]);
// Add the file - this should work now
const session_id = mgr.addFile(temp.path[0..temp.len]) catch |err| {
std.debug.print("addFile failed: {}\n", .{err});
return;
};
// Verify session was created
try testing.expect(session_id > 0);
// Verify session info
const info = mgr.getSessionInfo(session_id);
try testing.expect(info != null);
if (info) |i| {
try testing.expectEqual(session_id, i.session_id);
try testing.expectEqual(@as(u64, content.len), i.file_size);
try testing.expect(i.piece_count >= 1);
}
// Verify stats
const stats = mgr.getStats();
try testing.expect(stats.total_sessions >= 1);
try testing.expect(stats.registered_files >= 1);
}
test "FileSharingManager: session lifecycle with real file" {
const allocator = testing.allocator;
const config = createConfigWithTestDir();
var mgr = FileSharingManager.init(config, allocator) catch return;
defer mgr.deinit();
// Create temp file
const content = "Content for lifecycle test - testing start and stop sharing";
const temp = createTempFile(content) catch return;
defer deleteTempFile(temp.path[0..temp.len]);
// Add file
const session_id = mgr.addFile(temp.path[0..temp.len]) catch return;
// Start sharing
mgr.startSharing(session_id) catch |err| {
std.debug.print("startSharing failed: {}\n", .{err});
};
// Check session info after start
if (mgr.getSessionInfo(session_id)) |info| {
try testing.expect(info.status == .uploading or info.status == .ready or info.status == .downloading);
}
// Stop sharing
mgr.stopSharing(session_id) catch |err| {
std.debug.print("stopSharing failed: {}\n", .{err});
};
}
test "FileSharingManager: multiple real files" {
const allocator = testing.allocator;
const config = createConfigWithTestDir();
var mgr = FileSharingManager.init(config, allocator) catch return;
defer mgr.deinit();
// Create two different files
const temp1 = createTempFile("First file content") catch return;
defer deleteTempFile(temp1.path[0..temp1.len]);
const temp2 = createTempFile("Second file with different content") catch return;
defer deleteTempFile(temp2.path[0..temp2.len]);
// Add both
const session1 = mgr.addFile(temp1.path[0..temp1.len]) catch return;
const session2 = mgr.addFile(temp2.path[0..temp2.len]) catch return;
// Should be different sessions
try testing.expect(session1 != session2);
// Both should have info
try testing.expect(mgr.getSessionInfo(session1) != null);
try testing.expect(mgr.getSessionInfo(session2) != null);
// Stats should reflect both
const stats = mgr.getStats();
try testing.expect(stats.total_sessions >= 2);
}
test "FileSharingManager: larger file handling" {
const allocator = testing.allocator;
var config = createConfigWithTestDir();
config.piece_size = 1024; // 1KB pieces for testing
var mgr = FileSharingManager.init(config, allocator) catch return;
defer mgr.deinit();
// Create a 10KB file (should result in 10 pieces)
var large_content: [10 * 1024]u8 = undefined;
@memset(&large_content, 'X');
const temp = createTempFile(&large_content) catch return;
defer deleteTempFile(temp.path[0..temp.len]);
const session_id = mgr.addFile(temp.path[0..temp.len]) catch return;
// Verify piece count
if (mgr.getSessionInfo(session_id)) |info| {
try testing.expectEqual(@as(u64, 10 * 1024), info.file_size);
try testing.expect(info.piece_count >= 10);
}
}
// ============================================================================
// FileSharingManager Core Tests
// ============================================================================
test "FileSharingManager: initialization and stats" {
const allocator = testing.allocator;
const config = FileSharingConfig.default();
var mgr = FileSharingManager.init(config, allocator) catch |err| {
std.debug.print("Manager init failed: {}\n", .{err});
return;
};
defer mgr.deinit();
// Initial stats should be zero
const stats = mgr.getStats();
try testing.expectEqual(@as(usize, 0), stats.total_sessions);
try testing.expectEqual(@as(usize, 0), stats.active_sessions);
try testing.expectEqual(@as(u64, 0), stats.total_downloaded);
try testing.expectEqual(@as(u64, 0), stats.total_uploaded);
}
test "FileSharingManager: addFile rejects non-existent file" {
const allocator = testing.allocator;
const config = FileSharingConfig.default();
var mgr = FileSharingManager.init(config, allocator) catch return;
defer mgr.deinit();
const result = mgr.addFile("/nonexistent/path/to/file.dat");
// Should fail with either FileError or InvalidData
try testing.expect(result == error.FileError or result == error.InvalidData);
}
test "FileSharingManager: getActiveSessions empty" {
const allocator = testing.allocator;
const config = FileSharingConfig.default();
var mgr = FileSharingManager.init(config, allocator) catch return;
defer mgr.deinit();
const sessions = mgr.getActiveSessions() catch return;
defer allocator.free(sessions);
try testing.expectEqual(@as(usize, 0), sessions.len);
}
test "FileSharingManager: hasFile returns false for unknown hash" {
const allocator = testing.allocator;
const config = FileSharingConfig.default();
var mgr = FileSharingManager.init(config, allocator) catch return;
defer mgr.deinit();
var fake_hash: [32]u8 = undefined;
@memset(&fake_hash, 0xFF);
try testing.expect(!mgr.hasFile(fake_hash));
try testing.expect(!mgr.hasSessionByHash(fake_hash));
}
test "FileSharingManager: isIdle when no sessions" {
const allocator = testing.allocator;
const config = FileSharingConfig.default();
var mgr = FileSharingManager.init(config, allocator) catch return;
defer mgr.deinit();
try testing.expect(mgr.isIdle());
}
test "FileSharingManager: config update bandwidth" {
const allocator = testing.allocator;
const config = FileSharingConfig.default();
var mgr = FileSharingManager.init(config, allocator) catch return;
defer mgr.deinit();
const new_download: u64 = 5 * 1024 * 1024;
const new_upload: u64 = 2 * 1024 * 1024;
mgr.updateBandwidthLimits(new_download, new_upload);
const cfg = mgr.getConfig();
try testing.expectEqual(new_download, cfg.max_bandwidth_download);
try testing.expectEqual(new_upload, cfg.max_bandwidth_upload);
}
test "FileSharingManager: config update features" {
const allocator = testing.allocator;
const config = FileSharingConfig.default();
var mgr = FileSharingManager.init(config, allocator) catch return;
defer mgr.deinit();
// Disable both
mgr.setFeatures(false, false);
var cfg = mgr.getConfig();
try testing.expect(!cfg.enable_upload);
try testing.expect(!cfg.enable_download);
// Enable both
mgr.setFeatures(true, true);
cfg = mgr.getConfig();
try testing.expect(cfg.enable_upload);
try testing.expect(cfg.enable_download);
}
test "FileSharingManager: getSessionInfo returns null for unknown session" {
const allocator = testing.allocator;
const config = FileSharingConfig.default();
var mgr = FileSharingManager.init(config, allocator) catch return;
defer mgr.deinit();
const info = mgr.getSessionInfo(999999);
try testing.expect(info == null);
}
test "FileSharingManager: findSessionIdByHash returns null for unknown hash" {
const allocator = testing.allocator;
const config = FileSharingConfig.default();
var mgr = FileSharingManager.init(config, allocator) catch return;
defer mgr.deinit();
var fake_hash: [32]u8 = undefined;
@memset(&fake_hash, 0xAB);
const session_id = mgr.findSessionIdByHash(fake_hash);
try testing.expect(session_id == null);
}
test "FileSharingManager: profiling stats" {
const allocator = testing.allocator;
const config = FileSharingConfig.default();
var mgr = FileSharingManager.init(config, allocator) catch return;
defer mgr.deinit();
const prof = mgr.getProfilingStats();
// Initial values should be zero
try testing.expectEqual(@as(u64, 0), prof.pipeline_tasks_processed);
try testing.expectEqual(@as(u64, 0), prof.verification_completed);
try testing.expectEqual(@as(u64, 0), prof.verification_failed);
}
test "FileSharingManager: startSharing fails for unknown session" {
const allocator = testing.allocator;
const config = FileSharingConfig.default();
var mgr = FileSharingManager.init(config, allocator) catch return;
defer mgr.deinit();
const result = mgr.startSharing(999999);
try testing.expectError(Error.ConnectionNotFound, result);
}
test "FileSharingManager: stopSharing fails for unknown session" {
const allocator = testing.allocator;
const config = FileSharingConfig.default();
var mgr = FileSharingManager.init(config, allocator) catch return;
defer mgr.deinit();
const result = mgr.stopSharing(999999);
try testing.expectError(Error.ConnectionNotFound, result);
}
// ============================================================================
// PeerReputation Tests
// ============================================================================
test "PeerReputation: initialization" {
var peer_id: [32]u8 = undefined;
@memset(&peer_id, 0xAA);
const rep = manager.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);
}
test "PeerReputation: blacklisting after max bad pieces" {
var peer_id: [32]u8 = undefined;
@memset(&peer_id, 0xAA);
var rep = manager.PeerReputation.init(peer_id);
// Record bad pieces up to the max
const max_bad = manager.PeerReputation.MAX_BAD_PIECES;
var i: u32 = 0;
while (i < max_bad) : (i += 1) {
rep.recordBadPiece();
}
// Should now be blacklisted
try testing.expect(rep.isBlacklisted());
try testing.expect(rep.blacklist_count >= 1);
}
test "PeerReputation: memory quota tracking" {
var peer_id: [32]u8 = undefined;
@memset(&peer_id, 0xBB);
var rep = manager.PeerReputation.init(peer_id);
// Reserve some memory
try testing.expect(rep.reserveMemory(1000));
try testing.expectEqual(@as(u64, 1000), rep.memory_usage);
try testing.expectEqual(@as(u32, 1), rep.pending_requests);
// Release memory
rep.releaseMemory(500);
try testing.expectEqual(@as(u64, 500), rep.memory_usage);
try testing.expectEqual(@as(u32, 0), rep.pending_requests);
// Should not be exceeding quota
try testing.expect(!rep.hasExceededMemoryQuota());
}
test "PeerReputation: score calculation" {
var peer_id: [32]u8 = undefined;
@memset(&peer_id, 0xCC);
var rep = manager.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%
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, 0xDD);
var rep = manager.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);
}
test "PeerReputation: limits configuration" {
const original = manager.PeerReputation.getBaseBlacklistDuration();
manager.PeerReputation.setBaseBlacklistDuration(120);
try testing.expectEqual(@as(i64, 120), manager.PeerReputation.getBaseBlacklistDuration());
// Restore original
manager.PeerReputation.setBaseBlacklistDuration(original);
}
// ============================================================================
// FileSharingStats Tests
// ============================================================================
test "FileSharingStats: total transferred" {
const stats = manager.FileSharingStats{
.total_sessions = 5,
.active_sessions = 2,
.downloading_sessions = 1,
.uploading_sessions = 1,
.completed_sessions = 3,
.total_downloaded = 10 * 1024 * 1024,
.total_uploaded = 5 * 1024 * 1024,
.registered_files = 5,
.messages_sent = 100,
.messages_failed = 5,
};
try testing.expectEqual(@as(u64, 15 * 1024 * 1024), stats.getTotalTransferred());
}
test "FileSharingStats: rates" {
const stats = manager.FileSharingStats{
.total_sessions = 10,
.active_sessions = 5,
.downloading_sessions = 2,
.uploading_sessions = 3,
.completed_sessions = 4,
.total_downloaded = 0,
.total_uploaded = 0,
.registered_files = 0,
.messages_sent = 100,
.messages_failed = 10,
};
// Active rate: 5/10 = 50%
try testing.expectEqual(@as(f32, 0.5), stats.getActiveRate());
// Completion rate: 4/10 = 40%
try testing.expectEqual(@as(f32, 0.4), stats.getCompletionRate());
// Message success rate: 100/(100+10) ≈ 0.909
const success_rate = stats.getMessageSuccessRate();
try testing.expect(success_rate > 0.90 and success_rate < 0.92);
}
test "FileSharingStats: zero sessions" {
const stats = manager.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,
};
try testing.expectEqual(@as(f32, 0.0), stats.getActiveRate());
try testing.expectEqual(@as(f32, 0.0), stats.getCompletionRate());
try testing.expectEqual(@as(f32, 1.0), stats.getMessageSuccessRate()); // No failures = 100%
}
// ============================================================================
// SessionStats Tests
// ============================================================================
test "SessionStats: age calculation" {
const past = std.time.timestamp() - 60;
const stats = SessionStats{
.session_id = 1,
.status = .downloading,
.progress = 0.5,
.file_size = 1000,
.piece_count = 10,
.pieces_completed = 5,
.created_at = past,
.updated_at = std.time.timestamp() - 10,
};
const age = stats.getAge();
try testing.expect(age >= 59 and age <= 61);
const time_since = stats.getTimeSinceUpdate();
try testing.expect(time_since >= 9 and time_since <= 11);
}
// ============================================================================
// FileSharingLimits Tests
// ============================================================================
test "FileSharingLimits: valid 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: 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);
}
// ============================================================================
// NetworkSender Tests
// ============================================================================
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;
if (user_ctx) |ptr| {
const test_ctx: *TestCtx = @ptrCast(@alignCast(ptr));
test_ctx.call_count += 1;
}
return true;
}
}.cb;
const sender = manager.NetworkSender.init(send_fn, &ctx, allocator);
_ = sender;
try testing.expectEqual(@as(u32, 0), ctx.call_count);
}
// ============================================================================
// FileSharingConfig Presets Tests
// ============================================================================
test "FileSharingConfig: default preset" {
const config = FileSharingConfig.default();
try testing.expect(config.piece_size > 0);
try testing.expect(config.max_concurrent_downloads > 0);
try testing.expect(config.max_concurrent_uploads > 0);
try testing.expect(config.max_bandwidth_download > 0);
try testing.expect(config.max_bandwidth_upload > 0);
// verification_workers can be 0 (auto-detect) or positive
try testing.expect(config.verification_workers >= 0);
}
test "FileSharingConfig: high_performance preset" {
const config = FileSharingConfig.high_performance();
try testing.expect(config.piece_size >= 256 * 1024); // At least 256KB pieces for high performance
try testing.expect(config.max_concurrent_downloads >= 4);
try testing.expect(config.max_concurrent_uploads >= 4);
}
test "FileSharingConfig: low_bandwidth preset" {
const config = FileSharingConfig.low_bandwidth();
// Low bandwidth should have conservative bandwidth limits
try testing.expect(config.max_bandwidth_download <= 512 * 1024); // At most 512KB/s
try testing.expect(config.max_concurrent_downloads >= 1);
}
test "FileSharingConfig: low_bandwidth concurrent limits" {
const config = FileSharingConfig.low_bandwidth();
// Low bandwidth should be conservative with concurrent transfers
try testing.expect(config.max_concurrent_downloads >= 1);
try testing.expect(config.max_concurrent_uploads >= 1);
}
// ============================================================================
// FileSharingManager Extended Tests
// ============================================================================
test "FileSharingManager: removeFile for non-existent hash succeeds silently" {
const allocator = testing.allocator;
const config = FileSharingConfig.default();
var mgr = FileSharingManager.init(config, allocator) catch return;
defer mgr.deinit();
// Removing non-existent file by hash should succeed silently (no-op)
var fake_hash: [32]u8 = undefined;
@memset(&fake_hash, 0xAB);
try mgr.removeFile(fake_hash);
// No error expected - method just does nothing if file doesn't exist
}
test "FileSharingManager: hasSessionByHash returns false for unknown" {
const allocator = testing.allocator;
const config = FileSharingConfig.default();
var mgr = FileSharingManager.init(config, allocator) catch return;
defer mgr.deinit();
var fake_hash: [32]u8 = undefined;
@memset(&fake_hash, 0xCD);
try testing.expect(!mgr.hasSessionByHash(fake_hash));
}
test "FileSharingManager: getSessionInfoByHash returns null for unknown" {
const allocator = testing.allocator;
const config = FileSharingConfig.default();
var mgr = FileSharingManager.init(config, allocator) catch return;
defer mgr.deinit();
var fake_hash: [32]u8 = undefined;
@memset(&fake_hash, 0xEF);
const info = mgr.getSessionInfoByHash(fake_hash);
try testing.expect(info == null);
}
test "FileSharingManager: getFileInfoByHash returns null for unknown" {
const allocator = testing.allocator;
const config = FileSharingConfig.default();
var mgr = FileSharingManager.init(config, allocator) catch return;
defer mgr.deinit();
var fake_hash: [32]u8 = undefined;
@memset(&fake_hash, 0x12);
const info = mgr.getFileInfoByHash(fake_hash);
try testing.expect(info == null);
}
test "FileSharingManager: session with real file operations" {
const allocator = testing.allocator;
const config = createConfigWithTestDir();
var mgr = FileSharingManager.init(config, allocator) catch return;
defer mgr.deinit();
// Create temp file
const content = "Content for session operations test - verifying full lifecycle";
const temp = createTempFile(content) catch return;
defer deleteTempFile(temp.path[0..temp.len]);
// Add file
const session_id = mgr.addFile(temp.path[0..temp.len]) catch return;
// Verify session info
const info = mgr.getSessionInfo(session_id);
try testing.expect(info != null);
if (info) |i| {
try testing.expectEqual(@as(u64, content.len), i.file_size);
}
// Start sharing
mgr.startSharing(session_id) catch {};
// Check stats
const stats = mgr.getStats();
try testing.expect(stats.registered_files >= 1);
// Stop sharing
mgr.stopSharing(session_id) catch {};
}
// ============================================================================
// PeerReputation Extended Tests
// ============================================================================
test "PeerReputation: good piece recording" {
var peer_id: [32]u8 = undefined;
@memset(&peer_id, 0xCC);
var rep = manager.PeerReputation.init(peer_id);
// Record good pieces
rep.recordGoodPiece();
rep.recordGoodPiece();
rep.recordGoodPiece();
try testing.expectEqual(@as(u32, 3), rep.good_pieces);
try testing.expectEqual(@as(u32, 0), rep.bad_pieces);
// Score should be 1.0 (100% good)
try testing.expectEqual(@as(f32, 1.0), rep.getScore());
}
test "PeerReputation: progressive blacklisting" {
var peer_id: [32]u8 = undefined;
@memset(&peer_id, 0xDD);
var rep = manager.PeerReputation.init(peer_id);
// First blacklist
const max_bad = manager.PeerReputation.MAX_BAD_PIECES;
var i: u32 = 0;
while (i < max_bad) : (i += 1) {
rep.recordBadPiece();
}
try testing.expect(rep.isBlacklisted());
const first_blacklist = rep.blacklist_count;
// Reset and blacklist again - duration should increase
rep.reset();
rep.blacklist_count = first_blacklist;
i = 0;
while (i < max_bad) : (i += 1) {
rep.recordBadPiece();
}
try testing.expect(rep.blacklist_count > first_blacklist);
}
// ============================================================================
// FileSharingStats Extended Tests
// ============================================================================
test "FileSharingStats: rate calculations edge cases" {
// Zero messages = 100% success rate
const zero_msgs = manager.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,
};
try testing.expectEqual(@as(f32, 1.0), zero_msgs.getMessageSuccessRate());
// All failures = 0% success rate
const all_fail = manager.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 = 10,
};
try testing.expectEqual(@as(f32, 0.0), all_fail.getMessageSuccessRate());
}
// ============================================================================
// ProfilingStats Tests
// ============================================================================
test "FileSharingManager: profiling stats tracking" {
const allocator = testing.allocator;
const config = FileSharingConfig.default();
var mgr = FileSharingManager.init(config, allocator) catch return;
defer mgr.deinit();
const prof = mgr.getProfilingStats();
// Initial values should be reasonable
try testing.expect(prof.pipeline_tasks_processed >= 0);
try testing.expect(prof.verification_completed >= 0);
try testing.expect(prof.verification_failed >= 0);
}