1618 lines
54 KiB
Zig
1618 lines
54 KiB
Zig
//! Manager Coverage Tests
|
|
//!
|
|
//! Targeted tests for files/manager.zig to improve coverage.
|
|
//! Tests FileSharingLimits, PeerReputation, FileSharingConfig, NetworkSender, and stats.
|
|
|
|
const std = @import("std");
|
|
const testing = std.testing;
|
|
const mem = std.mem;
|
|
|
|
const files = @import("files");
|
|
const FileSharingLimits = files.manager.FileSharingLimits;
|
|
const PeerReputation = files.manager.PeerReputation;
|
|
const FileSharingConfig = files.manager.FileSharingConfig;
|
|
const FileSharingSession = files.manager.FileSharingSession;
|
|
const FileSharingManager = files.manager.FileSharingManager;
|
|
const FileSharingStats = files.manager.FileSharingStats;
|
|
const NetworkSender = files.manager.NetworkSender;
|
|
const SessionStats = files.manager.SessionStats;
|
|
const SelectionStrategy = files.piece.SelectionStrategy;
|
|
|
|
const core = @import("core");
|
|
const Error = core.errors.Error;
|
|
|
|
// ============================================================================
|
|
// FileSharingLimits Tests
|
|
// ============================================================================
|
|
|
|
test "FileSharingLimits: maxPieceSize" {
|
|
const max = FileSharingLimits.maxPieceSize();
|
|
try testing.expect(max > 0);
|
|
try testing.expect(max <= std.math.maxInt(u32));
|
|
}
|
|
|
|
test "FileSharingLimits: maxFileSize" {
|
|
const max = FileSharingLimits.maxFileSize();
|
|
try testing.expect(max > 0);
|
|
try testing.expect(max >= FileSharingLimits.maxPieceSize());
|
|
}
|
|
|
|
test "FileSharingLimits: maxFilenameLength" {
|
|
const max = FileSharingLimits.maxFilenameLength();
|
|
try testing.expect(max > 0);
|
|
try testing.expect(max <= 1024);
|
|
}
|
|
|
|
test "FileSharingLimits: maxSessions" {
|
|
const max = FileSharingLimits.maxSessions();
|
|
try testing.expect(max > 0);
|
|
}
|
|
|
|
test "FileSharingLimits: maxPieceDataSize" {
|
|
const max = FileSharingLimits.maxPieceDataSize();
|
|
try testing.expect(max > 0);
|
|
}
|
|
|
|
test "FileSharingLimits: maxPeerMemoryQuota" {
|
|
const max = FileSharingLimits.maxPeerMemoryQuota();
|
|
try testing.expect(max > 0);
|
|
}
|
|
|
|
test "FileSharingLimits: maxGlobalMemoryQuota" {
|
|
const max = FileSharingLimits.maxGlobalMemoryQuota();
|
|
try testing.expect(max > 0);
|
|
try testing.expect(max >= FileSharingLimits.maxPeerMemoryQuota());
|
|
}
|
|
|
|
test "FileSharingLimits: compile time constants" {
|
|
try testing.expectEqual(@as(u64, 64 * 1024 * 1024), FileSharingLimits.MAX_PIECE_SIZE);
|
|
try testing.expectEqual(@as(u64, 10 * 1024 * 1024 * 1024), FileSharingLimits.MAX_FILE_SIZE);
|
|
try testing.expectEqual(@as(usize, 255), FileSharingLimits.MAX_FILENAME_LENGTH);
|
|
try testing.expectEqual(@as(usize, 1000), FileSharingLimits.MAX_SESSIONS);
|
|
try testing.expectEqual(@as(usize, 32 * 1024 * 1024), FileSharingLimits.MAX_PIECE_DATA_SIZE);
|
|
try testing.expectEqual(@as(u64, 128 * 1024 * 1024), FileSharingLimits.MAX_PEER_MEMORY_QUOTA);
|
|
try testing.expectEqual(@as(u64, 2 * 1024 * 1024 * 1024), FileSharingLimits.MAX_GLOBAL_MEMORY_QUOTA);
|
|
}
|
|
|
|
// ============================================================================
|
|
// PeerReputation Tests
|
|
// ============================================================================
|
|
|
|
test "PeerReputation: init" {
|
|
const peer_id = [_]u8{0xAA} ** 32;
|
|
const rep = PeerReputation.init(peer_id);
|
|
|
|
try testing.expectEqualSlices(u8, &peer_id, &rep.peer_id);
|
|
try testing.expectEqual(@as(u32, 0), rep.bad_pieces);
|
|
try testing.expectEqual(@as(u32, 0), rep.good_pieces);
|
|
try testing.expectEqual(@as(i64, 0), rep.last_bad_piece_time);
|
|
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: constants" {
|
|
try testing.expectEqual(@as(u32, 3), PeerReputation.MAX_BAD_PIECES);
|
|
try testing.expectEqual(@as(i64, 300), PeerReputation.DEFAULT_BLACKLIST_DURATION_SECONDS);
|
|
try testing.expectEqual(@as(i64, 86400), PeerReputation.MAX_BLACKLIST_DURATION_SECONDS);
|
|
try testing.expectEqual(@as(u32, 64), PeerReputation.MAX_PENDING_REQUESTS);
|
|
}
|
|
|
|
test "PeerReputation: maxBadPieces runtime accessor" {
|
|
const max = PeerReputation.maxBadPieces();
|
|
try testing.expect(max > 0);
|
|
}
|
|
|
|
test "PeerReputation: baseBlacklistDuration runtime accessor" {
|
|
const duration = PeerReputation.baseBlacklistDuration();
|
|
try testing.expect(duration > 0);
|
|
}
|
|
|
|
test "PeerReputation: maxBlacklistDuration runtime accessor" {
|
|
const max = PeerReputation.maxBlacklistDuration();
|
|
try testing.expect(max > 0);
|
|
}
|
|
|
|
test "PeerReputation: maxRequestsPerPeer runtime accessor" {
|
|
const max = PeerReputation.maxRequestsPerPeer();
|
|
try testing.expect(max > 0);
|
|
}
|
|
|
|
test "PeerReputation: setBaseBlacklistDuration and getBaseBlacklistDuration" {
|
|
// Save original
|
|
const original = PeerReputation.getBaseBlacklistDuration();
|
|
|
|
// Set new value
|
|
PeerReputation.setBaseBlacklistDuration(600);
|
|
try testing.expectEqual(@as(i64, 600), PeerReputation.getBaseBlacklistDuration());
|
|
|
|
// Restore original
|
|
PeerReputation.setBaseBlacklistDuration(original);
|
|
}
|
|
|
|
test "PeerReputation: setBaseBlacklistDuration ignores invalid values" {
|
|
const original = PeerReputation.getBaseBlacklistDuration();
|
|
|
|
// Try setting zero (should be ignored)
|
|
PeerReputation.setBaseBlacklistDuration(0);
|
|
try testing.expectEqual(original, PeerReputation.getBaseBlacklistDuration());
|
|
|
|
// Try setting negative (should be ignored)
|
|
PeerReputation.setBaseBlacklistDuration(-1);
|
|
try testing.expectEqual(original, PeerReputation.getBaseBlacklistDuration());
|
|
|
|
// Try setting over max (should be ignored)
|
|
PeerReputation.setBaseBlacklistDuration(PeerReputation.MAX_BLACKLIST_DURATION_SECONDS + 1);
|
|
try testing.expectEqual(original, PeerReputation.getBaseBlacklistDuration());
|
|
}
|
|
|
|
test "PeerReputation: hasExceededMemoryQuota" {
|
|
var rep = PeerReputation.init([_]u8{0} ** 32);
|
|
|
|
// Under quota
|
|
rep.memory_usage = 0;
|
|
try testing.expect(!rep.hasExceededMemoryQuota());
|
|
|
|
// At quota boundary
|
|
rep.memory_usage = FileSharingLimits.MAX_PEER_MEMORY_QUOTA;
|
|
try testing.expect(!rep.hasExceededMemoryQuota());
|
|
|
|
// Over quota
|
|
rep.memory_usage = FileSharingLimits.MAX_PEER_MEMORY_QUOTA + 1;
|
|
try testing.expect(rep.hasExceededMemoryQuota());
|
|
}
|
|
|
|
test "PeerReputation: reserveMemory success" {
|
|
var rep = PeerReputation.init([_]u8{0} ** 32);
|
|
|
|
const result = rep.reserveMemory(1024);
|
|
try testing.expect(result);
|
|
try testing.expectEqual(@as(u64, 1024), rep.memory_usage);
|
|
try testing.expectEqual(@as(u32, 1), rep.pending_requests);
|
|
}
|
|
|
|
test "PeerReputation: reserveMemory fails when over quota" {
|
|
var rep = PeerReputation.init([_]u8{0} ** 32);
|
|
rep.memory_usage = FileSharingLimits.MAX_PEER_MEMORY_QUOTA;
|
|
|
|
const result = rep.reserveMemory(1);
|
|
try testing.expect(!result);
|
|
}
|
|
|
|
test "PeerReputation: reserveMemory fails when too many pending requests" {
|
|
var rep = PeerReputation.init([_]u8{0} ** 32);
|
|
rep.pending_requests = PeerReputation.MAX_PENDING_REQUESTS;
|
|
|
|
const result = rep.reserveMemory(1024);
|
|
try testing.expect(!result);
|
|
}
|
|
|
|
test "PeerReputation: releaseMemory" {
|
|
var rep = PeerReputation.init([_]u8{0} ** 32);
|
|
_ = rep.reserveMemory(1024);
|
|
_ = rep.reserveMemory(1024);
|
|
|
|
try testing.expectEqual(@as(u64, 2048), rep.memory_usage);
|
|
try testing.expectEqual(@as(u32, 2), rep.pending_requests);
|
|
|
|
rep.releaseMemory(1024);
|
|
|
|
try testing.expectEqual(@as(u64, 1024), rep.memory_usage);
|
|
try testing.expectEqual(@as(u32, 1), rep.pending_requests);
|
|
}
|
|
|
|
test "PeerReputation: releaseMemory handles underflow" {
|
|
var rep = PeerReputation.init([_]u8{0} ** 32);
|
|
rep.memory_usage = 100;
|
|
rep.pending_requests = 1;
|
|
|
|
// Release more than we have
|
|
rep.releaseMemory(200);
|
|
|
|
// Should clamp to 0
|
|
try testing.expectEqual(@as(u64, 0), rep.memory_usage);
|
|
try testing.expectEqual(@as(u32, 0), rep.pending_requests);
|
|
}
|
|
|
|
test "PeerReputation: recordBadPiece" {
|
|
var rep = PeerReputation.init([_]u8{0} ** 32);
|
|
|
|
rep.recordBadPiece();
|
|
try testing.expectEqual(@as(u32, 1), rep.bad_pieces);
|
|
try testing.expect(rep.last_bad_piece_time > 0);
|
|
}
|
|
|
|
test "PeerReputation: recordBadPiece triggers blacklist" {
|
|
var rep = PeerReputation.init([_]u8{0} ** 32);
|
|
|
|
// Record enough bad pieces to trigger blacklist
|
|
for (0..PeerReputation.MAX_BAD_PIECES) |_| {
|
|
rep.recordBadPiece();
|
|
}
|
|
|
|
try testing.expect(rep.blacklisted_until > 0);
|
|
try testing.expect(rep.blacklist_count > 0);
|
|
}
|
|
|
|
test "PeerReputation: recordGoodPiece" {
|
|
var rep = PeerReputation.init([_]u8{0} ** 32);
|
|
|
|
rep.recordGoodPiece();
|
|
try testing.expectEqual(@as(u32, 1), rep.good_pieces);
|
|
}
|
|
|
|
test "PeerReputation: isBlacklisted" {
|
|
var rep = PeerReputation.init([_]u8{0} ** 32);
|
|
|
|
// Initially not blacklisted
|
|
try testing.expect(!rep.isBlacklisted());
|
|
|
|
// Set future blacklist time
|
|
rep.blacklisted_until = std.time.timestamp() + 1000;
|
|
try testing.expect(rep.isBlacklisted());
|
|
|
|
// Set past blacklist time
|
|
rep.blacklisted_until = std.time.timestamp() - 1000;
|
|
try testing.expect(!rep.isBlacklisted());
|
|
}
|
|
|
|
test "PeerReputation: getScore" {
|
|
var rep = PeerReputation.init([_]u8{0} ** 32);
|
|
|
|
// Default score
|
|
const default_score = rep.getScore();
|
|
try testing.expect(default_score >= 0.0);
|
|
try testing.expect(default_score <= 1.0);
|
|
|
|
// With good pieces
|
|
rep.good_pieces = 100;
|
|
const good_score = rep.getScore();
|
|
try testing.expect(good_score > default_score);
|
|
|
|
// With bad pieces
|
|
rep.bad_pieces = 50;
|
|
const mixed_score = rep.getScore();
|
|
try testing.expect(mixed_score < good_score);
|
|
}
|
|
|
|
test "PeerReputation: reset" {
|
|
var rep = PeerReputation.init([_]u8{0xAA} ** 32);
|
|
rep.bad_pieces = 10;
|
|
rep.good_pieces = 20;
|
|
rep.blacklisted_until = 999;
|
|
rep.memory_usage = 1024;
|
|
rep.pending_requests = 5;
|
|
rep.blacklist_count = 3;
|
|
|
|
rep.reset();
|
|
|
|
// reset() only clears bad_pieces, good_pieces, and blacklisted_until
|
|
try testing.expectEqual(@as(u32, 0), rep.bad_pieces);
|
|
try testing.expectEqual(@as(u32, 0), rep.good_pieces);
|
|
try testing.expectEqual(@as(i64, 0), rep.blacklisted_until);
|
|
// memory_usage, pending_requests, and blacklist_count are preserved
|
|
try testing.expectEqual(@as(u64, 1024), rep.memory_usage);
|
|
try testing.expectEqual(@as(u32, 5), rep.pending_requests);
|
|
try testing.expectEqual(@as(u32, 3), rep.blacklist_count);
|
|
}
|
|
|
|
// ============================================================================
|
|
// FileSharingConfig Tests
|
|
// ============================================================================
|
|
|
|
test "FileSharingConfig: default" {
|
|
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.enable_upload);
|
|
try testing.expect(config.enable_download);
|
|
try testing.expect(config.auto_verify);
|
|
try testing.expectEqualStrings("tests/test_data/temp", config.temp_dir);
|
|
try testing.expect(!config.allow_symlinks);
|
|
}
|
|
|
|
test "FileSharingConfig: high_performance" {
|
|
const config = FileSharingConfig.high_performance();
|
|
|
|
// CASCADE PERF: High performance config uses 256 concurrent transfers
|
|
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 * 1024), config.max_bandwidth_download); // 1 GB/s
|
|
try testing.expectEqual(@as(u64, 1024 * 1024 * 1024), config.max_bandwidth_upload); // 1 GB/s
|
|
try testing.expectEqual(@as(u64, 1024 * 1024), config.piece_size); // 1MB pieces
|
|
try testing.expectEqual(SelectionStrategy.balanced, config.selection_strategy);
|
|
}
|
|
|
|
test "FileSharingConfig: low_bandwidth" {
|
|
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, 256 * 1024), config.max_bandwidth_download);
|
|
try testing.expectEqual(@as(u64, 256 * 1024), config.max_bandwidth_upload);
|
|
try testing.expectEqual(@as(u64, 8 * 1024 * 1024), config.piece_size);
|
|
try testing.expectEqual(SelectionStrategy.sequential, config.selection_strategy);
|
|
}
|
|
|
|
test "FileSharingConfig: selection strategies" {
|
|
const strategies = [_]SelectionStrategy{
|
|
.rarest_first,
|
|
.sequential,
|
|
.balanced,
|
|
.random,
|
|
};
|
|
|
|
for (strategies) |s| {
|
|
var config = FileSharingConfig.default();
|
|
config.selection_strategy = s;
|
|
try testing.expectEqual(s, config.selection_strategy);
|
|
}
|
|
}
|
|
|
|
// ============================================================================
|
|
// SessionStats Tests
|
|
// ============================================================================
|
|
|
|
test "SessionStats: getAge" {
|
|
const now = std.time.timestamp();
|
|
const stats = SessionStats{
|
|
.session_id = 0,
|
|
.status = .initializing,
|
|
.progress = 0.0,
|
|
.created_at = now - 100,
|
|
.updated_at = now,
|
|
.file_size = 0,
|
|
.piece_count = 0,
|
|
.pieces_completed = 0,
|
|
};
|
|
|
|
const age = stats.getAge();
|
|
try testing.expect(age >= 100);
|
|
try testing.expect(age < 200);
|
|
}
|
|
|
|
test "SessionStats: getTimeSinceUpdate" {
|
|
const now = std.time.timestamp();
|
|
const stats = SessionStats{
|
|
.session_id = 0,
|
|
.status = .initializing,
|
|
.progress = 0.0,
|
|
.created_at = now - 200,
|
|
.updated_at = now - 50,
|
|
.file_size = 0,
|
|
.piece_count = 0,
|
|
.pieces_completed = 0,
|
|
};
|
|
|
|
const time_since = stats.getTimeSinceUpdate();
|
|
try testing.expect(time_since >= 50);
|
|
try testing.expect(time_since < 100);
|
|
}
|
|
|
|
// ============================================================================
|
|
// FileSharingStats Tests
|
|
// ============================================================================
|
|
|
|
test "FileSharingStats: getTotalTransferred" {
|
|
const stats = FileSharingStats{
|
|
.total_sessions = 0,
|
|
.active_sessions = 0,
|
|
.downloading_sessions = 0,
|
|
.uploading_sessions = 0,
|
|
.completed_sessions = 0,
|
|
.total_downloaded = 1000,
|
|
.total_uploaded = 500,
|
|
.registered_files = 0,
|
|
.messages_sent = 0,
|
|
.messages_failed = 0,
|
|
};
|
|
|
|
try testing.expectEqual(@as(u64, 1500), stats.getTotalTransferred());
|
|
}
|
|
|
|
test "FileSharingStats: getMessageSuccessRate 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,
|
|
};
|
|
|
|
try testing.expectEqual(@as(f32, 1.0), stats.getMessageSuccessRate());
|
|
}
|
|
|
|
test "FileSharingStats: getMessageSuccessRate with 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 = 90,
|
|
.messages_failed = 10,
|
|
};
|
|
|
|
const rate = stats.getMessageSuccessRate();
|
|
try testing.expect(rate >= 0.89);
|
|
try testing.expect(rate <= 0.91);
|
|
}
|
|
|
|
test "FileSharingStats: getActiveRate with no 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,
|
|
};
|
|
|
|
try testing.expectEqual(@as(f32, 0.0), stats.getActiveRate());
|
|
}
|
|
|
|
test "FileSharingStats: getActiveRate with sessions" {
|
|
const stats = FileSharingStats{
|
|
.total_sessions = 20,
|
|
.active_sessions = 5,
|
|
.downloading_sessions = 3,
|
|
.uploading_sessions = 2,
|
|
.completed_sessions = 10,
|
|
.total_downloaded = 0,
|
|
.total_uploaded = 0,
|
|
.registered_files = 0,
|
|
.messages_sent = 0,
|
|
.messages_failed = 0,
|
|
};
|
|
|
|
const rate = stats.getActiveRate();
|
|
try testing.expect(rate >= 0.24); // 5/20 = 0.25
|
|
try testing.expect(rate <= 0.26);
|
|
}
|
|
|
|
test "FileSharingStats: getCompletionRate with no 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,
|
|
};
|
|
|
|
try testing.expectEqual(@as(f32, 0.0), stats.getCompletionRate());
|
|
}
|
|
|
|
test "FileSharingStats: getCompletionRate with completed sessions" {
|
|
const stats = FileSharingStats{
|
|
.total_sessions = 20,
|
|
.active_sessions = 0,
|
|
.downloading_sessions = 0,
|
|
.uploading_sessions = 0,
|
|
.completed_sessions = 15,
|
|
.total_downloaded = 0,
|
|
.total_uploaded = 0,
|
|
.registered_files = 0,
|
|
.messages_sent = 0,
|
|
.messages_failed = 0,
|
|
};
|
|
|
|
const rate = stats.getCompletionRate();
|
|
try testing.expect(rate >= 0.74); // 15/20 = 0.75
|
|
try testing.expect(rate <= 0.76);
|
|
}
|
|
|
|
// ============================================================================
|
|
// FileSharingSession.SessionStatus Tests
|
|
// ============================================================================
|
|
|
|
test "SessionStatus: enum values" {
|
|
try testing.expectEqual(@as(u8, 1), @intFromEnum(FileSharingSession.SessionStatus.initializing));
|
|
try testing.expectEqual(@as(u8, 2), @intFromEnum(FileSharingSession.SessionStatus.ready));
|
|
try testing.expectEqual(@as(u8, 3), @intFromEnum(FileSharingSession.SessionStatus.downloading));
|
|
try testing.expectEqual(@as(u8, 4), @intFromEnum(FileSharingSession.SessionStatus.uploading));
|
|
try testing.expectEqual(@as(u8, 5), @intFromEnum(FileSharingSession.SessionStatus.completed));
|
|
try testing.expectEqual(@as(u8, 6), @intFromEnum(FileSharingSession.SessionStatus.failed));
|
|
try testing.expectEqual(@as(u8, 7), @intFromEnum(FileSharingSession.SessionStatus.cancelled));
|
|
}
|
|
|
|
// ============================================================================
|
|
// NetworkSender Tests
|
|
// ============================================================================
|
|
|
|
fn mockSendSuccess(peer_id: []const u8, data: []const u8, context: ?*anyopaque) bool {
|
|
_ = peer_id;
|
|
_ = data;
|
|
_ = context;
|
|
return true;
|
|
}
|
|
|
|
fn mockSendFailure(peer_id: []const u8, data: []const u8, context: ?*anyopaque) bool {
|
|
_ = peer_id;
|
|
_ = data;
|
|
_ = context;
|
|
return false;
|
|
}
|
|
|
|
test "NetworkSender: init" {
|
|
const sender = NetworkSender.init(&mockSendSuccess, null, testing.allocator);
|
|
try testing.expect(sender.send_fn == &mockSendSuccess);
|
|
try testing.expect(sender.context == null);
|
|
}
|
|
|
|
test "NetworkSender: init with context" {
|
|
var context_value: u32 = 42;
|
|
const sender = NetworkSender.init(&mockSendSuccess, @ptrCast(&context_value), testing.allocator);
|
|
try testing.expect(sender.context != null);
|
|
}
|
|
|
|
// ============================================================================
|
|
// FileSharingSession Status Tests
|
|
// ============================================================================
|
|
|
|
test "FileSharingSession: isActive for different statuses" {
|
|
// Test each status through SessionStats
|
|
const active_statuses = [_]FileSharingSession.SessionStatus{
|
|
.initializing,
|
|
.ready,
|
|
.downloading,
|
|
.uploading,
|
|
};
|
|
|
|
for (active_statuses) |status| {
|
|
const stats = SessionStats{
|
|
.session_id = 1,
|
|
.status = status,
|
|
.progress = 0.0,
|
|
.created_at = std.time.timestamp(),
|
|
.updated_at = std.time.timestamp(),
|
|
.file_size = 100,
|
|
.piece_count = 10,
|
|
.pieces_completed = 0,
|
|
};
|
|
// Active statuses have enum values 1-4
|
|
try testing.expect(@intFromEnum(stats.status) <= 4);
|
|
}
|
|
|
|
const inactive_statuses = [_]FileSharingSession.SessionStatus{
|
|
.completed,
|
|
.failed,
|
|
.cancelled,
|
|
};
|
|
|
|
for (inactive_statuses) |status| {
|
|
const stats = SessionStats{
|
|
.session_id = 1,
|
|
.status = status,
|
|
.progress = 0.0,
|
|
.created_at = std.time.timestamp(),
|
|
.updated_at = std.time.timestamp(),
|
|
.file_size = 100,
|
|
.piece_count = 10,
|
|
.pieces_completed = 0,
|
|
};
|
|
// Inactive statuses have enum values 5-7
|
|
try testing.expect(@intFromEnum(stats.status) >= 5);
|
|
}
|
|
}
|
|
|
|
// ============================================================================
|
|
// Additional PeerReputation Edge Case Tests
|
|
// ============================================================================
|
|
|
|
test "PeerReputation: multiple recordBadPiece cycles" {
|
|
var rep = PeerReputation.init([_]u8{0} ** 32);
|
|
|
|
// First blacklist cycle
|
|
for (0..PeerReputation.MAX_BAD_PIECES) |_| {
|
|
rep.recordBadPiece();
|
|
}
|
|
try testing.expect(rep.blacklist_count == 1);
|
|
|
|
// Reset and trigger second cycle
|
|
rep.bad_pieces = 0;
|
|
for (0..PeerReputation.MAX_BAD_PIECES) |_| {
|
|
rep.recordBadPiece();
|
|
}
|
|
try testing.expect(rep.blacklist_count == 2);
|
|
}
|
|
|
|
test "PeerReputation: getScore edge cases" {
|
|
var rep = PeerReputation.init([_]u8{0} ** 32);
|
|
|
|
// No pieces - neutral score
|
|
try testing.expectEqual(@as(f32, 0.5), rep.getScore());
|
|
|
|
// Only good pieces - perfect score
|
|
rep.good_pieces = 100;
|
|
rep.bad_pieces = 0;
|
|
try testing.expectEqual(@as(f32, 1.0), rep.getScore());
|
|
|
|
// Only bad pieces - zero score
|
|
rep.good_pieces = 0;
|
|
rep.bad_pieces = 100;
|
|
try testing.expectEqual(@as(f32, 0.0), rep.getScore());
|
|
|
|
// Mixed - should be ratio
|
|
rep.good_pieces = 75;
|
|
rep.bad_pieces = 25;
|
|
const score = rep.getScore();
|
|
try testing.expect(score >= 0.74);
|
|
try testing.expect(score <= 0.76);
|
|
}
|
|
|
|
test "PeerReputation: blacklist duration with high count" {
|
|
var rep = PeerReputation.init([_]u8{0} ** 32);
|
|
rep.blacklist_count = 10; // High count for exponential backoff
|
|
|
|
// Trigger blacklist
|
|
rep.bad_pieces = PeerReputation.MAX_BAD_PIECES - 1;
|
|
rep.recordBadPiece();
|
|
|
|
// Blacklist should be set with capped duration
|
|
try testing.expect(rep.blacklisted_until > std.time.timestamp());
|
|
}
|
|
|
|
// ============================================================================
|
|
// FileSharingConfig Edge Cases
|
|
// ============================================================================
|
|
|
|
test "FileSharingConfig: field accessors" {
|
|
const config = FileSharingConfig.default();
|
|
|
|
try testing.expectEqualStrings("tests/test_data/temp", config.temp_dir);
|
|
try testing.expect(config.max_registry_files > 0);
|
|
try testing.expect(config.max_reputation_peers > 0);
|
|
try testing.expect(config.buffer_pool_size > 0);
|
|
try testing.expect(config.pipeline_workers > 0);
|
|
try testing.expect(config.verification_workers > 0);
|
|
}
|
|
|
|
test "FileSharingConfig: compare presets" {
|
|
const default = FileSharingConfig.default();
|
|
const high_perf = FileSharingConfig.high_performance();
|
|
const low_bw = FileSharingConfig.low_bandwidth();
|
|
|
|
// All configs have valid concurrency limits
|
|
try testing.expect(high_perf.max_concurrent_downloads > 0);
|
|
try testing.expect(default.max_concurrent_downloads > 0);
|
|
try testing.expect(low_bw.max_concurrent_downloads > 0);
|
|
|
|
// High performance has higher bandwidth than low bandwidth
|
|
try testing.expect(high_perf.max_bandwidth_download >= low_bw.max_bandwidth_download);
|
|
|
|
// All have valid piece sizes
|
|
try testing.expect(high_perf.piece_size > 0);
|
|
try testing.expect(default.piece_size > 0);
|
|
try testing.expect(low_bw.piece_size > 0);
|
|
}
|
|
|
|
// ============================================================================
|
|
// SessionStats Edge Cases
|
|
// ============================================================================
|
|
|
|
test "SessionStats: all fields initialized" {
|
|
const now = std.time.timestamp();
|
|
const stats = SessionStats{
|
|
.session_id = 12345,
|
|
.status = .downloading,
|
|
.progress = 0.5,
|
|
.created_at = now - 1000,
|
|
.updated_at = now - 100,
|
|
.file_size = 1024 * 1024,
|
|
.piece_count = 10,
|
|
.pieces_completed = 5,
|
|
};
|
|
|
|
try testing.expectEqual(@as(u64, 12345), stats.session_id);
|
|
try testing.expectEqual(FileSharingSession.SessionStatus.downloading, stats.status);
|
|
try testing.expect(stats.progress >= 0.49);
|
|
try testing.expect(stats.progress <= 0.51);
|
|
try testing.expectEqual(@as(u64, 1024 * 1024), stats.file_size);
|
|
try testing.expectEqual(@as(u32, 10), stats.piece_count);
|
|
try testing.expectEqual(@as(u32, 5), stats.pieces_completed);
|
|
}
|
|
|
|
test "SessionStats: getAge with zero created_at" {
|
|
const stats = SessionStats{
|
|
.session_id = 0,
|
|
.status = .initializing,
|
|
.progress = 0.0,
|
|
.created_at = 0, // Unix epoch
|
|
.updated_at = 0,
|
|
.file_size = 0,
|
|
.piece_count = 0,
|
|
.pieces_completed = 0,
|
|
};
|
|
|
|
const age = stats.getAge();
|
|
// Should be > 50 years since epoch
|
|
try testing.expect(age > 50 * 365 * 24 * 3600);
|
|
}
|
|
|
|
// ============================================================================
|
|
// FileSharingStats Edge Cases
|
|
// ============================================================================
|
|
|
|
test "FileSharingStats: all zero fields" {
|
|
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,
|
|
};
|
|
|
|
try testing.expectEqual(@as(u64, 0), stats.getTotalTransferred());
|
|
try testing.expectEqual(@as(f32, 1.0), stats.getMessageSuccessRate());
|
|
try testing.expectEqual(@as(f32, 0.0), stats.getActiveRate());
|
|
try testing.expectEqual(@as(f32, 0.0), stats.getCompletionRate());
|
|
}
|
|
|
|
test "FileSharingStats: high values" {
|
|
const stats = FileSharingStats{
|
|
.total_sessions = 1000000,
|
|
.active_sessions = 500000,
|
|
.downloading_sessions = 250000,
|
|
.uploading_sessions = 250000,
|
|
.completed_sessions = 400000,
|
|
.total_downloaded = 1024 * 1024 * 1024 * 100, // 100GB
|
|
.total_uploaded = 1024 * 1024 * 1024 * 50, // 50GB
|
|
.registered_files = 10000,
|
|
.messages_sent = 1000000,
|
|
.messages_failed = 100,
|
|
};
|
|
|
|
const total = stats.getTotalTransferred();
|
|
try testing.expect(total == 1024 * 1024 * 1024 * 150);
|
|
|
|
const success_rate = stats.getMessageSuccessRate();
|
|
try testing.expect(success_rate > 0.99);
|
|
|
|
const active_rate = stats.getActiveRate();
|
|
try testing.expect(active_rate >= 0.49);
|
|
try testing.expect(active_rate <= 0.51);
|
|
|
|
const completion_rate = stats.getCompletionRate();
|
|
try testing.expect(completion_rate >= 0.39);
|
|
try testing.expect(completion_rate <= 0.41);
|
|
}
|
|
|
|
// ============================================================================
|
|
// FileSharingManager Session Operations Tests
|
|
// ============================================================================
|
|
|
|
test "FileSharingManager: getActiveSessions empty" {
|
|
var config = FileSharingConfig.default();
|
|
config.temp_dir = "/tmp";
|
|
|
|
var manager = FileSharingManager.initForTesting(config, testing.allocator) catch return error.SkipZigTest;
|
|
defer manager.deinit();
|
|
|
|
const sessions = manager.getActiveSessions() catch return error.SkipZigTest;
|
|
defer testing.allocator.free(sessions);
|
|
|
|
try testing.expectEqual(@as(usize, 0), sessions.len);
|
|
}
|
|
|
|
test "FileSharingManager: getSessionInfo with invalid id" {
|
|
var config = FileSharingConfig.default();
|
|
config.temp_dir = "/tmp";
|
|
|
|
var manager = FileSharingManager.initForTesting(config, testing.allocator) catch return error.SkipZigTest;
|
|
defer manager.deinit();
|
|
|
|
// Non-existent session
|
|
const info = manager.getSessionInfo(999999);
|
|
try testing.expect(info == null);
|
|
}
|
|
|
|
test "FileSharingManager: getFileInfoByHash with unknown hash" {
|
|
var config = FileSharingConfig.default();
|
|
config.temp_dir = "/tmp";
|
|
|
|
var manager = FileSharingManager.initForTesting(config, testing.allocator) catch return error.SkipZigTest;
|
|
defer manager.deinit();
|
|
|
|
var unknown_hash: [32]u8 = undefined;
|
|
@memset(&unknown_hash, 0x99);
|
|
|
|
const info = manager.getFileInfoByHash(unknown_hash);
|
|
try testing.expect(info == null);
|
|
}
|
|
|
|
test "FileSharingManager: startSharing with invalid session" {
|
|
var config = FileSharingConfig.default();
|
|
config.temp_dir = "/tmp";
|
|
|
|
var manager = FileSharingManager.initForTesting(config, testing.allocator) catch return error.SkipZigTest;
|
|
defer manager.deinit();
|
|
|
|
// Try to start sharing non-existent session
|
|
const result = manager.startSharing(999999);
|
|
try testing.expectError(Error.ConnectionNotFound, result);
|
|
}
|
|
|
|
test "FileSharingManager: stopSharing with invalid session" {
|
|
var config = FileSharingConfig.default();
|
|
config.temp_dir = "/tmp";
|
|
|
|
var manager = FileSharingManager.initForTesting(config, testing.allocator) catch return error.SkipZigTest;
|
|
defer manager.deinit();
|
|
|
|
// Try to stop sharing non-existent session
|
|
const result = manager.stopSharing(999999);
|
|
try testing.expectError(Error.ConnectionNotFound, result);
|
|
}
|
|
|
|
test "FileSharingManager: processSessions when empty" {
|
|
var config = FileSharingConfig.default();
|
|
config.temp_dir = "/tmp";
|
|
|
|
var manager = FileSharingManager.initForTesting(config, testing.allocator) catch return error.SkipZigTest;
|
|
defer manager.deinit();
|
|
|
|
// Should complete without error when no sessions
|
|
manager.processSessions() catch {};
|
|
}
|
|
|
|
test "FileSharingManager: processVerificationResults when empty" {
|
|
var config = FileSharingConfig.default();
|
|
config.temp_dir = "/tmp";
|
|
|
|
var manager = FileSharingManager.initForTesting(config, testing.allocator) catch return error.SkipZigTest;
|
|
defer manager.deinit();
|
|
|
|
// Should complete without error
|
|
manager.processVerificationResults();
|
|
}
|
|
|
|
test "FileSharingManager: getStats" {
|
|
var config = FileSharingConfig.default();
|
|
config.temp_dir = "/tmp";
|
|
|
|
var manager = FileSharingManager.initForTesting(config, testing.allocator) catch return error.SkipZigTest;
|
|
defer manager.deinit();
|
|
|
|
const stats = manager.getStats();
|
|
try testing.expectEqual(@as(u64, 0), stats.total_sessions);
|
|
try testing.expectEqual(@as(u64, 0), stats.active_sessions);
|
|
try testing.expectEqual(@as(u64, 0), stats.registered_files);
|
|
}
|
|
|
|
test "FileSharingManager: setNetworkSender and clearNetworkSender" {
|
|
var config = FileSharingConfig.default();
|
|
config.temp_dir = "/tmp";
|
|
|
|
var manager = FileSharingManager.initForTesting(config, testing.allocator) catch return error.SkipZigTest;
|
|
defer manager.deinit();
|
|
|
|
// Create a mock sender with correct callback signature
|
|
var sender = NetworkSender.init(&mockSendSuccess, null, testing.allocator);
|
|
|
|
manager.setNetworkSender(&sender);
|
|
|
|
// Clear it
|
|
manager.clearNetworkSender();
|
|
}
|
|
|
|
// ============================================================================
|
|
// FileSharingManager Handler Coverage Tests
|
|
// ============================================================================
|
|
|
|
test "FileSharingManager: handlePieceData with short payload" {
|
|
var config = FileSharingConfig.default();
|
|
config.temp_dir = "/tmp";
|
|
|
|
var manager = FileSharingManager.initForTesting(config, testing.allocator) catch return error.SkipZigTest;
|
|
defer manager.deinit();
|
|
|
|
var peer_id: [32]u8 = undefined;
|
|
@memset(&peer_id, 0xAA);
|
|
|
|
// Too short payload
|
|
var short_payload: [10]u8 = undefined;
|
|
@memset(&short_payload, 0);
|
|
|
|
const result = manager.handlePieceData(peer_id, &short_payload);
|
|
try testing.expectError(Error.InvalidData, result);
|
|
}
|
|
|
|
test "FileSharingManager: handlePieceResponse with short payload" {
|
|
var config = FileSharingConfig.default();
|
|
config.temp_dir = "/tmp";
|
|
|
|
var manager = FileSharingManager.initForTesting(config, testing.allocator) catch return error.SkipZigTest;
|
|
defer manager.deinit();
|
|
|
|
var peer_id: [32]u8 = undefined;
|
|
@memset(&peer_id, 0xBB);
|
|
|
|
// Too short payload (needs piece_index(4) + available(1) + request_id(4) = 9 bytes min)
|
|
var short_payload: [5]u8 = undefined;
|
|
@memset(&short_payload, 0);
|
|
|
|
const result = manager.handlePieceResponse(peer_id, &short_payload);
|
|
try testing.expectError(Error.InvalidData, result);
|
|
}
|
|
|
|
test "FileSharingManager: handleBitfield with empty payload" {
|
|
var config = FileSharingConfig.default();
|
|
config.temp_dir = "/tmp";
|
|
|
|
var manager = FileSharingManager.initForTesting(config, testing.allocator) catch return error.SkipZigTest;
|
|
defer manager.deinit();
|
|
|
|
var peer_id: [32]u8 = undefined;
|
|
@memset(&peer_id, 0xCC);
|
|
|
|
// Empty payload
|
|
var empty_payload: [0]u8 = undefined;
|
|
|
|
const result = manager.handleBitfield(peer_id, &empty_payload);
|
|
try testing.expectError(Error.InvalidData, result);
|
|
}
|
|
|
|
test "FileSharingManager: handleHave with short payload" {
|
|
var config = FileSharingConfig.default();
|
|
config.temp_dir = "/tmp";
|
|
|
|
var manager = FileSharingManager.initForTesting(config, testing.allocator) catch return error.SkipZigTest;
|
|
defer manager.deinit();
|
|
|
|
var peer_id: [32]u8 = undefined;
|
|
@memset(&peer_id, 0xDD);
|
|
|
|
// Too short (need 4 bytes for piece_index)
|
|
var short_payload: [2]u8 = undefined;
|
|
@memset(&short_payload, 0);
|
|
|
|
const result = manager.handleHave(peer_id, &short_payload);
|
|
try testing.expectError(Error.InvalidData, result);
|
|
}
|
|
|
|
test "FileSharingManager: handlePieceRequest with short payload" {
|
|
var config = FileSharingConfig.default();
|
|
config.temp_dir = "/tmp";
|
|
|
|
var manager = FileSharingManager.initForTesting(config, testing.allocator) catch return error.SkipZigTest;
|
|
defer manager.deinit();
|
|
|
|
var peer_id: [32]u8 = undefined;
|
|
@memset(&peer_id, 0xEE);
|
|
|
|
// Too short (needs content_hash(32) + piece_index(4) + offset(4) = 40 bytes)
|
|
var short_payload: [20]u8 = undefined;
|
|
@memset(&short_payload, 0);
|
|
|
|
const result = manager.handlePieceRequest(peer_id, &short_payload);
|
|
try testing.expectError(Error.InvalidData, result);
|
|
}
|
|
|
|
test "FileSharingManager: handleBatchPieceRequest with short payload" {
|
|
var config = FileSharingConfig.default();
|
|
config.temp_dir = "/tmp";
|
|
|
|
var manager = FileSharingManager.initForTesting(config, testing.allocator) catch return error.SkipZigTest;
|
|
defer manager.deinit();
|
|
|
|
var peer_id: [32]u8 = undefined;
|
|
@memset(&peer_id, 0xFF);
|
|
|
|
// Too short (needs content_hash(32) + count(2) + at least one index(4))
|
|
var short_payload: [30]u8 = undefined;
|
|
@memset(&short_payload, 0);
|
|
|
|
const result = manager.handleBatchPieceRequest(peer_id, &short_payload);
|
|
try testing.expectError(Error.InvalidData, result);
|
|
}
|
|
|
|
// ============================================================================
|
|
// FileSharingManager Peer Reputation Tests
|
|
// ============================================================================
|
|
|
|
test "FileSharingManager: getPeerReputation for unknown peer returns null" {
|
|
var config = FileSharingConfig.default();
|
|
config.temp_dir = "/tmp";
|
|
|
|
var manager = FileSharingManager.initForTesting(config, testing.allocator) catch return error.SkipZigTest;
|
|
defer manager.deinit();
|
|
|
|
var peer_id: [32]u8 = undefined;
|
|
@memset(&peer_id, 0x11);
|
|
|
|
// Unknown peer has no reputation entry
|
|
const rep = manager.getPeerReputation(peer_id);
|
|
try testing.expect(rep == null);
|
|
}
|
|
|
|
test "FileSharingManager: getPeerReputation returns reputation data" {
|
|
var config = FileSharingConfig.default();
|
|
config.temp_dir = "/tmp";
|
|
|
|
var manager = FileSharingManager.initForTesting(config, testing.allocator) catch return error.SkipZigTest;
|
|
defer manager.deinit();
|
|
|
|
// getPeerReputation returns a copy, so we test the basic API
|
|
var peer_id: [32]u8 = undefined;
|
|
@memset(&peer_id, 0x22);
|
|
|
|
// Verify it returns null for unknown
|
|
const rep = manager.getPeerReputation(peer_id);
|
|
try testing.expect(rep == null);
|
|
}
|
|
|
|
test "PeerReputation: direct recordBadPiece" {
|
|
var rep = PeerReputation.init([_]u8{0x33} ** 32);
|
|
|
|
// Initially no bad pieces
|
|
try testing.expectEqual(@as(u32, 0), rep.bad_pieces);
|
|
|
|
// Record a bad piece
|
|
rep.recordBadPiece();
|
|
try testing.expectEqual(@as(u32, 1), rep.bad_pieces);
|
|
try testing.expect(rep.last_bad_piece_time > 0);
|
|
}
|
|
|
|
test "PeerReputation: direct recordGoodPiece" {
|
|
var rep = PeerReputation.init([_]u8{0x44} ** 32);
|
|
|
|
// Initially no good pieces
|
|
try testing.expectEqual(@as(u32, 0), rep.good_pieces);
|
|
|
|
// Record a good piece
|
|
rep.recordGoodPiece();
|
|
try testing.expectEqual(@as(u32, 1), rep.good_pieces);
|
|
}
|
|
|
|
test "PeerReputation: blacklist after multiple bad pieces" {
|
|
var rep = PeerReputation.init([_]u8{0x55} ** 32);
|
|
|
|
// Record enough bad pieces to trigger blacklist
|
|
const max_bad = PeerReputation.maxBadPieces();
|
|
for (0..max_bad) |_| {
|
|
rep.recordBadPiece();
|
|
}
|
|
|
|
// Peer should now be blacklisted
|
|
try testing.expect(rep.isBlacklisted());
|
|
try testing.expect(rep.blacklist_count > 0);
|
|
}
|
|
|
|
// ============================================================================
|
|
// FileSharingManager withSession Tests
|
|
// ============================================================================
|
|
|
|
test "FileSharingManager: withSession with invalid id" {
|
|
var config = FileSharingConfig.default();
|
|
config.temp_dir = "/tmp";
|
|
|
|
var manager = FileSharingManager.initForTesting(config, testing.allocator) catch return error.SkipZigTest;
|
|
defer manager.deinit();
|
|
|
|
// Try to access non-existent session - should return error
|
|
const result = manager.withSession(999999, struct {
|
|
fn callback(_: *FileSharingSession) Error!void {}
|
|
}.callback);
|
|
|
|
// Should return ConnectionNotFound error for non-existent session
|
|
try testing.expectError(Error.ConnectionNotFound, result);
|
|
}
|
|
|
|
test "FileSharingManager: withSessionResult with invalid id" {
|
|
var config = FileSharingConfig.default();
|
|
config.temp_dir = "/tmp";
|
|
|
|
var manager = FileSharingManager.initForTesting(config, testing.allocator) catch return error.SkipZigTest;
|
|
defer manager.deinit();
|
|
|
|
// Try to access non-existent session
|
|
const result = manager.withSessionResult(999999, u32, struct {
|
|
fn callback(_: *FileSharingSession) u32 {
|
|
return 42;
|
|
}
|
|
}.callback);
|
|
|
|
// Should return null for non-existent session
|
|
try testing.expect(result == null);
|
|
}
|
|
|
|
// ============================================================================
|
|
// FileSharingManager Pool Operations Tests
|
|
// ============================================================================
|
|
|
|
test "FileSharingManager: startVerificationPool and stopVerificationPool" {
|
|
var config = FileSharingConfig.default();
|
|
config.temp_dir = "/tmp";
|
|
|
|
var manager = FileSharingManager.initForTesting(config, testing.allocator) catch return error.SkipZigTest;
|
|
defer manager.deinit();
|
|
|
|
// Start the pool
|
|
manager.startVerificationPool() catch {
|
|
// May fail in test environment - that's ok
|
|
return;
|
|
};
|
|
|
|
// Stop the pool
|
|
manager.stopVerificationPool();
|
|
}
|
|
|
|
test "FileSharingManager: startPiecePipeline and stopPiecePipeline" {
|
|
var config = FileSharingConfig.default();
|
|
config.temp_dir = "/tmp";
|
|
|
|
var manager = FileSharingManager.initForTesting(config, testing.allocator) catch return error.SkipZigTest;
|
|
defer manager.deinit();
|
|
|
|
// Start the pipeline
|
|
manager.startPiecePipeline() catch {
|
|
// May fail in test environment - that's ok
|
|
return;
|
|
};
|
|
|
|
// Stop the pipeline
|
|
manager.stopPiecePipeline();
|
|
}
|
|
|
|
// ============================================================================
|
|
// FileSharingManager Handler Tests with Valid Data
|
|
// ============================================================================
|
|
|
|
test "FileSharingManager: handleMetadataResponse with valid payload" {
|
|
var config = FileSharingConfig.default();
|
|
config.temp_dir = "/tmp";
|
|
|
|
var manager = FileSharingManager.initForTesting(config, testing.allocator) catch return error.SkipZigTest;
|
|
defer manager.deinit();
|
|
|
|
var peer_id: [32]u8 = undefined;
|
|
@memset(&peer_id, 0xAA);
|
|
|
|
// Build valid metadata response payload
|
|
// Format: name_len(2) + name(8) + size(8) + piece_count(4) + created_at(8) + modified_at(8) + piece_hashes(32)
|
|
// Total: 2 + 8 + 8 + 4 + 8 + 8 + 32 = 70 bytes
|
|
var payload: [70]u8 = undefined;
|
|
var offset: usize = 0;
|
|
|
|
// Name length = 8 ("testfile")
|
|
std.mem.writeInt(u16, payload[offset..][0..2], 8, .big);
|
|
offset += 2;
|
|
|
|
// Name = "testfile"
|
|
@memcpy(payload[offset..][0..8], "testfile");
|
|
offset += 8;
|
|
|
|
// Size = 1024
|
|
std.mem.writeInt(u64, payload[offset..][0..8], 1024, .big);
|
|
offset += 8;
|
|
|
|
// Piece count = 1
|
|
std.mem.writeInt(u32, payload[offset..][0..4], 1, .big);
|
|
offset += 4;
|
|
|
|
// Created at = 0
|
|
std.mem.writeInt(i64, payload[offset..][0..8], 0, .big);
|
|
offset += 8;
|
|
|
|
// Modified at = 0
|
|
std.mem.writeInt(i64, payload[offset..][0..8], 0, .big);
|
|
offset += 8;
|
|
|
|
// One piece hash (32 bytes)
|
|
@memset(payload[offset..][0..32], 0xBB);
|
|
|
|
// This should succeed (or hit the session limit path)
|
|
const result = manager.handleMetadataResponse(peer_id, &payload);
|
|
// Either success or PoolExhausted are acceptable
|
|
if (result) |_| {
|
|
// Success - session was created
|
|
} else |err| {
|
|
try testing.expect(err == Error.PoolExhausted or err == Error.SystemError);
|
|
}
|
|
}
|
|
|
|
test "FileSharingManager: handlePieceRequest with valid format but unknown session" {
|
|
var config = FileSharingConfig.default();
|
|
config.temp_dir = "/tmp";
|
|
|
|
var manager = FileSharingManager.initForTesting(config, testing.allocator) catch return error.SkipZigTest;
|
|
defer manager.deinit();
|
|
|
|
var peer_id: [32]u8 = undefined;
|
|
@memset(&peer_id, 0xCC);
|
|
|
|
// Build valid piece request payload
|
|
// Format: content_hash(32) + piece_index(4) + offset(4) + length(4) = 44 bytes
|
|
var payload: [44]u8 = undefined;
|
|
|
|
// Content hash
|
|
@memset(payload[0..32], 0xDD);
|
|
|
|
// Piece index = 0
|
|
std.mem.writeInt(u32, payload[32..36], 0, .big);
|
|
|
|
// Offset = 0
|
|
std.mem.writeInt(u32, payload[36..40], 0, .big);
|
|
|
|
// Length = 1024
|
|
std.mem.writeInt(u32, payload[40..44], 1024, .big);
|
|
|
|
// Should not return error even for unknown session (just logs warning)
|
|
const result = manager.handlePieceRequest(peer_id, &payload);
|
|
// Either success or error is acceptable - we're exercising the code path
|
|
_ = result catch {};
|
|
}
|
|
|
|
test "FileSharingManager: handlePieceData with valid header but unknown session" {
|
|
var config = FileSharingConfig.default();
|
|
config.temp_dir = "/tmp";
|
|
|
|
var manager = FileSharingManager.initForTesting(config, testing.allocator) catch return error.SkipZigTest;
|
|
defer manager.deinit();
|
|
|
|
var peer_id: [32]u8 = undefined;
|
|
@memset(&peer_id, 0xEE);
|
|
|
|
// Build valid piece data payload
|
|
// Format: content_hash(32) + piece_index(4) + offset(4) + data
|
|
var payload: [50]u8 = undefined;
|
|
|
|
// Content hash
|
|
@memset(payload[0..32], 0xFF);
|
|
|
|
// Piece index = 0
|
|
std.mem.writeInt(u32, payload[32..36], 0, .big);
|
|
|
|
// Offset = 0
|
|
std.mem.writeInt(u32, payload[36..40], 0, .big);
|
|
|
|
// Data (10 bytes)
|
|
@memset(payload[40..50], 0x42);
|
|
|
|
// Should not crash even for unknown session
|
|
const result = manager.handlePieceData(peer_id, &payload);
|
|
// Either success or error is acceptable
|
|
_ = result catch {};
|
|
}
|
|
|
|
test "FileSharingManager: handleBitfield with valid header but unknown session" {
|
|
var config = FileSharingConfig.default();
|
|
config.temp_dir = "/tmp";
|
|
|
|
var manager = FileSharingManager.initForTesting(config, testing.allocator) catch return error.SkipZigTest;
|
|
defer manager.deinit();
|
|
|
|
var peer_id: [32]u8 = undefined;
|
|
@memset(&peer_id, 0x11);
|
|
|
|
// Build valid bitfield payload
|
|
// Format: content_hash(32) + bitfield data
|
|
var payload: [40]u8 = undefined;
|
|
|
|
// Content hash
|
|
@memset(payload[0..32], 0x22);
|
|
|
|
// Bitfield (8 bytes - represents 64 pieces)
|
|
@memset(payload[32..40], 0xFF);
|
|
|
|
// Should not crash for unknown session
|
|
const result = manager.handleBitfield(peer_id, &payload);
|
|
_ = result catch {};
|
|
}
|
|
|
|
test "FileSharingManager: handleHave with valid format but unknown session" {
|
|
var config = FileSharingConfig.default();
|
|
config.temp_dir = "/tmp";
|
|
|
|
var manager = FileSharingManager.initForTesting(config, testing.allocator) catch return error.SkipZigTest;
|
|
defer manager.deinit();
|
|
|
|
var peer_id: [32]u8 = undefined;
|
|
@memset(&peer_id, 0x33);
|
|
|
|
// Build valid have payload
|
|
// Format: content_hash(32) + piece_index(4)
|
|
var payload: [36]u8 = undefined;
|
|
|
|
// Content hash
|
|
@memset(payload[0..32], 0x44);
|
|
|
|
// Piece index = 5
|
|
std.mem.writeInt(u32, payload[32..36], 5, .big);
|
|
|
|
// Should not crash for unknown session
|
|
const result = manager.handleHave(peer_id, &payload);
|
|
_ = result catch {};
|
|
}
|
|
|
|
test "FileSharingManager: handlePieceResponse with valid format" {
|
|
var config = FileSharingConfig.default();
|
|
config.temp_dir = "/tmp";
|
|
|
|
var manager = FileSharingManager.initForTesting(config, testing.allocator) catch return error.SkipZigTest;
|
|
defer manager.deinit();
|
|
|
|
var peer_id: [32]u8 = undefined;
|
|
@memset(&peer_id, 0x55);
|
|
|
|
// Build valid piece response payload
|
|
// Format: piece_index(4) + available(1) + request_id(4) = 9 bytes
|
|
var payload: [9]u8 = undefined;
|
|
|
|
// Piece index = 0
|
|
std.mem.writeInt(u32, payload[0..4], 0, .big);
|
|
|
|
// Available = 1 (true)
|
|
payload[4] = 1;
|
|
|
|
// Request ID = 123
|
|
std.mem.writeInt(u32, payload[5..9], 123, .big);
|
|
|
|
// Should not crash
|
|
const result = manager.handlePieceResponse(peer_id, &payload);
|
|
_ = result catch {};
|
|
}
|
|
|
|
test "FileSharingManager: handlePieceResponse with unavailable piece" {
|
|
var config = FileSharingConfig.default();
|
|
config.temp_dir = "/tmp";
|
|
|
|
var manager = FileSharingManager.initForTesting(config, testing.allocator) catch return error.SkipZigTest;
|
|
defer manager.deinit();
|
|
|
|
var peer_id: [32]u8 = undefined;
|
|
@memset(&peer_id, 0x66);
|
|
|
|
// Build piece response payload with available = false
|
|
var payload: [9]u8 = undefined;
|
|
|
|
// Piece index = 0
|
|
std.mem.writeInt(u32, payload[0..4], 0, .big);
|
|
|
|
// Available = 0 (false)
|
|
payload[4] = 0;
|
|
|
|
// Request ID = 456
|
|
std.mem.writeInt(u32, payload[5..9], 456, .big);
|
|
|
|
// Should return early without error when piece is unavailable
|
|
manager.handlePieceResponse(peer_id, &payload) catch {};
|
|
}
|
|
|
|
// ============================================================================
|
|
// FileSharingManager Config Edge Cases
|
|
// ============================================================================
|
|
|
|
test "FileSharingManager: init with minimal config" {
|
|
var config = FileSharingConfig.default();
|
|
config.temp_dir = "/tmp";
|
|
config.max_concurrent_downloads = 1;
|
|
config.max_concurrent_uploads = 1;
|
|
|
|
var manager = FileSharingManager.initForTesting(config, testing.allocator) catch return error.SkipZigTest;
|
|
defer manager.deinit();
|
|
|
|
try testing.expect(manager.config.max_concurrent_downloads == 1);
|
|
try testing.expect(manager.config.max_concurrent_uploads == 1);
|
|
}
|
|
|
|
test "FileSharingManager: getConfig returns config" {
|
|
var config = FileSharingConfig.default();
|
|
config.temp_dir = "/tmp";
|
|
config.max_concurrent_downloads = 5;
|
|
|
|
var manager = FileSharingManager.initForTesting(config, testing.allocator) catch return error.SkipZigTest;
|
|
defer manager.deinit();
|
|
|
|
const retrieved_config = manager.getConfig();
|
|
try testing.expectEqual(@as(usize, 5), retrieved_config.max_concurrent_downloads);
|
|
}
|
|
|
|
test "FileSharingManager: getProfilingStats" {
|
|
var config = FileSharingConfig.default();
|
|
config.temp_dir = "/tmp";
|
|
|
|
var manager = FileSharingManager.initForTesting(config, testing.allocator) catch return error.SkipZigTest;
|
|
defer manager.deinit();
|
|
|
|
const profiling_stats = manager.getProfilingStats();
|
|
// Verify profiling stats fields exist and have reasonable values
|
|
try testing.expect(profiling_stats.pipeline_tasks_queued >= 0);
|
|
try testing.expect(profiling_stats.verification_completed >= 0);
|
|
}
|
|
|
|
// ============================================================================
|
|
// Additional FileSharingStats Coverage
|
|
// ============================================================================
|
|
|
|
test "FileSharingStats: high message failure rate" {
|
|
const stats = FileSharingStats{
|
|
.total_sessions = 10,
|
|
.active_sessions = 5,
|
|
.downloading_sessions = 3,
|
|
.uploading_sessions = 2,
|
|
.completed_sessions = 3,
|
|
.total_downloaded = 1000,
|
|
.total_uploaded = 500,
|
|
.registered_files = 5,
|
|
.messages_sent = 100,
|
|
.messages_failed = 900, // 10% success rate: 100 / (100 + 900) = 0.1
|
|
};
|
|
|
|
const success_rate = stats.getMessageSuccessRate();
|
|
try testing.expect(success_rate >= 0.09);
|
|
try testing.expect(success_rate <= 0.11);
|
|
}
|
|
|
|
test "FileSharingStats: all messages failed" {
|
|
const stats = FileSharingStats{
|
|
.total_sessions = 1,
|
|
.active_sessions = 1,
|
|
.downloading_sessions = 1,
|
|
.uploading_sessions = 0,
|
|
.completed_sessions = 0,
|
|
.total_downloaded = 0,
|
|
.total_uploaded = 0,
|
|
.registered_files = 0,
|
|
.messages_sent = 0,
|
|
.messages_failed = 100,
|
|
};
|
|
|
|
// When messages_sent is 0 but messages_failed > 0, rate = 0 / (0 + 100) = 0.0
|
|
const success_rate = stats.getMessageSuccessRate();
|
|
try testing.expect(success_rate == 0.0);
|
|
}
|
|
|
|
// ============================================================================
|
|
// Additional Coverage Tests
|
|
// ============================================================================
|
|
|
|
test "FileSharingManager: handleBatchPieceRequest with too short payload" {
|
|
var config = FileSharingConfig.default();
|
|
config.temp_dir = "/tmp";
|
|
|
|
var manager = FileSharingManager.initForTesting(config, testing.allocator) catch return error.SkipZigTest;
|
|
defer manager.deinit();
|
|
|
|
var peer_id: [32]u8 = undefined;
|
|
@memset(&peer_id, 0x77);
|
|
|
|
// Less than minimum 34 bytes (content_hash(32) + count(2))
|
|
var payload: [20]u8 = undefined;
|
|
@memset(&payload, 0);
|
|
|
|
const result = manager.handleBatchPieceRequest(peer_id, &payload);
|
|
try testing.expectError(Error.InvalidData, result);
|
|
}
|
|
|
|
test "FileSharingManager: handleBatchPieceRequest with valid header but zero count" {
|
|
var config = FileSharingConfig.default();
|
|
config.temp_dir = "/tmp";
|
|
|
|
var manager = FileSharingManager.initForTesting(config, testing.allocator) catch return error.SkipZigTest;
|
|
defer manager.deinit();
|
|
|
|
var peer_id: [32]u8 = undefined;
|
|
@memset(&peer_id, 0x88);
|
|
|
|
// content_hash(32) + count(2) = 34 bytes, but count = 0
|
|
var payload: [34]u8 = undefined;
|
|
@memset(payload[0..32], 0xAA); // content_hash
|
|
std.mem.writeInt(u16, payload[32..34], 0, .big); // count = 0
|
|
|
|
const result = manager.handleBatchPieceRequest(peer_id, &payload);
|
|
// Should return InvalidData for count = 0
|
|
try testing.expectError(Error.InvalidData, result);
|
|
}
|
|
|
|
// Note: getStatusString has a comptime issue with tuple indexing, skipping test
|
|
|
|
test "PeerReputation: reserveMemory and releaseMemory sequence" {
|
|
var rep = PeerReputation.init([_]u8{0x99} ** 32);
|
|
|
|
// Reserve multiple times
|
|
try testing.expect(rep.reserveMemory(1000));
|
|
try testing.expect(rep.reserveMemory(2000));
|
|
try testing.expect(rep.reserveMemory(3000));
|
|
|
|
try testing.expectEqual(@as(u64, 6000), rep.memory_usage);
|
|
try testing.expectEqual(@as(u32, 3), rep.pending_requests);
|
|
|
|
// Release all
|
|
rep.releaseMemory(1000);
|
|
rep.releaseMemory(2000);
|
|
rep.releaseMemory(3000);
|
|
|
|
try testing.expectEqual(@as(u64, 0), rep.memory_usage);
|
|
try testing.expectEqual(@as(u32, 0), rep.pending_requests);
|
|
}
|
|
|
|
test "FileSharingConfig: verify defaults have sane values" {
|
|
const config = FileSharingConfig.default();
|
|
|
|
// Check all default fields have reasonable values
|
|
try testing.expect(config.piece_size >= 1024); // At least 1KB
|
|
try testing.expect(config.piece_size <= 64 * 1024 * 1024); // At most 64MB
|
|
try testing.expect(config.max_concurrent_downloads >= 1);
|
|
try testing.expect(config.max_concurrent_uploads >= 1);
|
|
try testing.expect(config.max_registry_files >= 1);
|
|
try testing.expect(config.max_reputation_peers >= 1);
|
|
}
|
|
|
|
test "FileSharingManager: multiple getSessionInfo calls" {
|
|
var config = FileSharingConfig.default();
|
|
config.temp_dir = "/tmp";
|
|
|
|
var manager = FileSharingManager.initForTesting(config, testing.allocator) catch return error.SkipZigTest;
|
|
defer manager.deinit();
|
|
|
|
// Multiple calls to getSessionInfo with invalid IDs should return null
|
|
try testing.expect(manager.getSessionInfo(1) == null);
|
|
try testing.expect(manager.getSessionInfo(999) == null);
|
|
try testing.expect(manager.getSessionInfo(std.math.maxInt(u64)) == null);
|
|
}
|
|
|
|
test "FileSharingManager: getSessionInfoByHash with unknown hash" {
|
|
var config = FileSharingConfig.default();
|
|
config.temp_dir = "/tmp";
|
|
|
|
var manager = FileSharingManager.initForTesting(config, testing.allocator) catch return error.SkipZigTest;
|
|
defer manager.deinit();
|
|
|
|
var unknown_hash: [32]u8 = undefined;
|
|
@memset(&unknown_hash, 0xAB);
|
|
|
|
const info = manager.getSessionInfoByHash(unknown_hash);
|
|
try testing.expect(info == null);
|
|
}
|
|
|
|
test "FileSharingManager: getFileMetadataBySessionId with invalid id" {
|
|
var config = FileSharingConfig.default();
|
|
config.temp_dir = "/tmp";
|
|
|
|
var manager = FileSharingManager.initForTesting(config, testing.allocator) catch return error.SkipZigTest;
|
|
defer manager.deinit();
|
|
|
|
const metadata = manager.getFileMetadataBySessionId(999999, testing.allocator) catch return error.SkipZigTest;
|
|
try testing.expect(metadata == null);
|
|
}
|
|
|
|
test "FileSharingManager: getFileMetadataByHash with unknown hash" {
|
|
var config = FileSharingConfig.default();
|
|
config.temp_dir = "/tmp";
|
|
|
|
var manager = FileSharingManager.initForTesting(config, testing.allocator) catch return error.SkipZigTest;
|
|
defer manager.deinit();
|
|
|
|
var unknown_hash: [32]u8 = undefined;
|
|
@memset(&unknown_hash, 0xCD);
|
|
|
|
const metadata = manager.getFileMetadataByHash(unknown_hash, testing.allocator) catch return error.SkipZigTest;
|
|
try testing.expect(metadata == null);
|
|
}
|