1007 lines
37 KiB
Zig
1007 lines
37 KiB
Zig
//! FileSharingManager Session Tests
|
|
//!
|
|
//! Tests that require real file operations to create valid sessions,
|
|
//! then exercise handler and session management code paths.
|
|
//!
|
|
//! Uses real temp files because PathValidator requires actual filesystem access.
|
|
|
|
const std = @import("std");
|
|
const testing = std.testing;
|
|
const mem = std.mem;
|
|
const fs = std.fs;
|
|
|
|
const files = @import("files");
|
|
const FileSharingManager = files.manager.FileSharingManager;
|
|
const FileSharingConfig = files.manager.FileSharingConfig;
|
|
const FileSharingSession = files.manager.FileSharingSession;
|
|
const FileMetadata = files.file.FileMetadata;
|
|
const FileChunker = files.file.FileChunker;
|
|
const NetworkSender = files.manager.NetworkSender;
|
|
const PeerReputation = files.manager.PeerReputation;
|
|
|
|
const core = @import("core");
|
|
const Error = core.errors.Error;
|
|
|
|
// ============================================================================
|
|
// Test Utilities
|
|
// ============================================================================
|
|
|
|
const TEST_DIR = "tests/test_data";
|
|
|
|
// Static array for allowed_share_directories to avoid stack lifetime issues
|
|
const ALLOWED_DIRS: []const []const u8 = &[_][]const u8{TEST_DIR};
|
|
|
|
fn ensureTestDir() void {
|
|
fs.cwd().makePath(TEST_DIR) catch {};
|
|
}
|
|
|
|
/// Creates a test file and writes the path to the provided buffer.
|
|
/// Returns the slice of the path within the buffer.
|
|
fn createTestFileInBuf(path_buf: []u8, name: []const u8, content: []const u8) ![]const u8 {
|
|
ensureTestDir();
|
|
|
|
const path = std.fmt.bufPrint(path_buf, "{s}/{s}", .{ TEST_DIR, name }) catch return error.Overflow;
|
|
|
|
var file = fs.cwd().createFile(path, .{}) catch return error.FileNotFound;
|
|
defer file.close();
|
|
file.writeAll(content) catch return error.FileNotFound;
|
|
|
|
return path;
|
|
}
|
|
|
|
fn deleteTestFile(name: []const u8) void {
|
|
var path_buf: [256]u8 = undefined;
|
|
const path = std.fmt.bufPrint(&path_buf, "{s}/{s}", .{ TEST_DIR, name }) catch return;
|
|
fs.cwd().deleteFile(path) catch {};
|
|
}
|
|
|
|
fn createTestConfig() FileSharingConfig {
|
|
var config = FileSharingConfig.default();
|
|
config.temp_dir = TEST_DIR;
|
|
config.allowed_share_directories = ALLOWED_DIRS;
|
|
config.piece_size = 1024; // Small pieces for testing
|
|
config.enable_upload = true;
|
|
config.enable_download = true;
|
|
config.auto_verify = true;
|
|
config.max_concurrent_downloads = 10;
|
|
config.max_concurrent_uploads = 10;
|
|
return config;
|
|
}
|
|
|
|
// Mock network sender that captures sent messages
|
|
const MockNetworkSender = struct {
|
|
sent_count: usize = 0,
|
|
last_peer_id: ?[32]u8 = null,
|
|
fail_next: bool = false,
|
|
|
|
fn sendCallback(peer_id: []const u8, data: []const u8, context: ?*anyopaque) bool {
|
|
_ = data;
|
|
if (context) |ctx| {
|
|
const self: *MockNetworkSender = @ptrCast(@alignCast(ctx));
|
|
if (self.fail_next) {
|
|
self.fail_next = false;
|
|
return false;
|
|
}
|
|
self.sent_count += 1;
|
|
if (peer_id.len == 32) {
|
|
self.last_peer_id = peer_id[0..32].*;
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
};
|
|
|
|
// ============================================================================
|
|
// Session Creation Tests
|
|
// ============================================================================
|
|
|
|
test "FileSharingManager: addFile creates valid session" {
|
|
ensureTestDir();
|
|
const config = createTestConfig();
|
|
|
|
var manager = FileSharingManager.initForTesting(config, testing.allocator) catch return error.SkipZigTest;
|
|
defer manager.deinit();
|
|
|
|
// Create a test file - use stack buffer that stays valid
|
|
const test_content = "Hello, World! This is test content for the file sharing manager.";
|
|
var path_buf: [256]u8 = undefined;
|
|
const file_path = createTestFileInBuf(&path_buf, "test_add_file.txt", test_content) catch return error.SkipZigTest;
|
|
defer deleteTestFile("test_add_file.txt");
|
|
|
|
// Add the file
|
|
const session_id = manager.addFile(file_path) catch |err| {
|
|
std.debug.print("addFile error: {}\n", .{err});
|
|
return error.SkipZigTest;
|
|
};
|
|
|
|
// Verify session was created
|
|
try testing.expect(session_id > 0);
|
|
|
|
// Get session info
|
|
const info = manager.getSessionInfo(session_id);
|
|
try testing.expect(info != null);
|
|
|
|
if (info) |session_info| {
|
|
try testing.expect(session_info.file_size == test_content.len);
|
|
try testing.expect(session_info.piece_count > 0);
|
|
}
|
|
|
|
// Verify stats updated
|
|
const stats = manager.getStats();
|
|
try testing.expect(stats.total_sessions >= 1);
|
|
}
|
|
|
|
test "FileSharingManager: addFile twice returns error" {
|
|
ensureTestDir();
|
|
const config = createTestConfig();
|
|
|
|
var manager = FileSharingManager.initForTesting(config, testing.allocator) catch return error.SkipZigTest;
|
|
defer manager.deinit();
|
|
|
|
const test_content = "Duplicate file test content";
|
|
var path_buf: [256]u8 = undefined;
|
|
const file_path = createTestFileInBuf(&path_buf, "test_duplicate.txt", test_content) catch return error.SkipZigTest;
|
|
defer deleteTestFile("test_duplicate.txt");
|
|
|
|
// Add file first time
|
|
_ = manager.addFile(file_path) catch return error.SkipZigTest;
|
|
|
|
// Add same file again - should fail
|
|
const result = manager.addFile(file_path);
|
|
try testing.expectError(Error.ConnectionAlreadyExists, result);
|
|
}
|
|
|
|
test "FileSharingManager: addFile with invalid path" {
|
|
const config = createTestConfig();
|
|
|
|
var manager = FileSharingManager.initForTesting(config, testing.allocator) catch return error.SkipZigTest;
|
|
defer manager.deinit();
|
|
|
|
// Try to add non-existent file
|
|
const result = manager.addFile("/nonexistent/path/to/file.txt");
|
|
try testing.expectError(Error.InvalidData, result);
|
|
}
|
|
|
|
test "FileSharingManager: getActiveSessions returns session IDs" {
|
|
ensureTestDir();
|
|
const config = createTestConfig();
|
|
|
|
var manager = FileSharingManager.initForTesting(config, testing.allocator) catch return error.SkipZigTest;
|
|
defer manager.deinit();
|
|
|
|
// Create multiple test files - need separate buffers since paths are used simultaneously
|
|
const content1 = "File one content";
|
|
const content2 = "File two content - different";
|
|
var path_buf1: [256]u8 = undefined;
|
|
var path_buf2: [256]u8 = undefined;
|
|
const path1 = createTestFileInBuf(&path_buf1, "active_test1.txt", content1) catch return error.SkipZigTest;
|
|
defer deleteTestFile("active_test1.txt");
|
|
const path2 = createTestFileInBuf(&path_buf2, "active_test2.txt", content2) catch return error.SkipZigTest;
|
|
defer deleteTestFile("active_test2.txt");
|
|
|
|
const session1 = manager.addFile(path1) catch return error.SkipZigTest;
|
|
const session2 = manager.addFile(path2) catch return error.SkipZigTest;
|
|
|
|
// Get active sessions
|
|
const sessions = manager.getActiveSessions() catch return error.SkipZigTest;
|
|
defer testing.allocator.free(sessions);
|
|
|
|
try testing.expect(sessions.len >= 2);
|
|
|
|
// Verify our sessions are in the list
|
|
var found1 = false;
|
|
var found2 = false;
|
|
for (sessions) |id| {
|
|
if (id == session1) found1 = true;
|
|
if (id == session2) found2 = true;
|
|
}
|
|
try testing.expect(found1);
|
|
try testing.expect(found2);
|
|
}
|
|
|
|
// ============================================================================
|
|
// Session Control Tests
|
|
// ============================================================================
|
|
|
|
test "FileSharingManager: startSharing and stopSharing" {
|
|
ensureTestDir();
|
|
const config = createTestConfig();
|
|
|
|
var manager = FileSharingManager.initForTesting(config, testing.allocator) catch return error.SkipZigTest;
|
|
defer manager.deinit();
|
|
|
|
const test_content = "Start/stop sharing test content that is long enough";
|
|
var path_buf: [256]u8 = undefined;
|
|
const file_path = createTestFileInBuf(&path_buf, "start_stop_test.txt", test_content) catch return error.SkipZigTest;
|
|
defer deleteTestFile("start_stop_test.txt");
|
|
|
|
const session_id = manager.addFile(file_path) catch return error.SkipZigTest;
|
|
|
|
// Start sharing
|
|
manager.startSharing(session_id) catch |err| {
|
|
// May fail if download manager isn't set up - that's ok
|
|
if (err != Error.OperationNotSupported) {
|
|
std.debug.print("startSharing unexpected error: {}\n", .{err});
|
|
}
|
|
};
|
|
|
|
// Verify session exists before stop
|
|
const info_before = manager.getSessionInfo(session_id);
|
|
try testing.expect(info_before != null);
|
|
|
|
// Stop sharing - this removes the session
|
|
manager.stopSharing(session_id) catch |err| {
|
|
if (err != Error.OperationNotSupported and err != Error.ConnectionNotFound) {
|
|
std.debug.print("stopSharing unexpected error: {}\n", .{err});
|
|
}
|
|
};
|
|
|
|
// Session should be removed after stopSharing
|
|
const info_after = manager.getSessionInfo(session_id);
|
|
try testing.expect(info_after == null);
|
|
}
|
|
|
|
// ============================================================================
|
|
// Handler Tests with Valid Sessions
|
|
// ============================================================================
|
|
|
|
test "FileSharingManager: handlePieceRequest with valid session" {
|
|
ensureTestDir();
|
|
const config = createTestConfig();
|
|
|
|
var manager = FileSharingManager.initForTesting(config, testing.allocator) catch return error.SkipZigTest;
|
|
defer manager.deinit();
|
|
|
|
// Create file and session
|
|
const test_content = "A" ** 2048; // 2KB file
|
|
var path_buf: [256]u8 = undefined;
|
|
const file_path = createTestFileInBuf(&path_buf, "piece_request_test.txt", test_content) catch return error.SkipZigTest;
|
|
defer deleteTestFile("piece_request_test.txt");
|
|
|
|
const session_id = manager.addFile(file_path) catch return error.SkipZigTest;
|
|
|
|
// Get session info to find content hash
|
|
const info = manager.getSessionInfo(session_id) orelse return error.SkipZigTest;
|
|
_ = info;
|
|
|
|
// Get file metadata to get content hash
|
|
const metadata = manager.getFileMetadataBySessionId(session_id, testing.allocator) catch return error.SkipZigTest;
|
|
if (metadata == null) return error.SkipZigTest;
|
|
defer {
|
|
if (metadata) |m| {
|
|
testing.allocator.free(m.name);
|
|
testing.allocator.free(m.piece_hashes);
|
|
}
|
|
}
|
|
|
|
// Build piece request with session's content hash
|
|
var peer_id: [32]u8 = undefined;
|
|
@memset(&peer_id, 0xAA);
|
|
|
|
// We need the content hash from the session
|
|
// Since we can't easily get it, let's use withSessionResult
|
|
const content_hash = manager.withSessionResult(session_id, [32]u8, struct {
|
|
fn callback(session: *FileSharingSession) [32]u8 {
|
|
return session.content_hash;
|
|
}
|
|
}.callback);
|
|
|
|
if (content_hash == null) return error.SkipZigTest;
|
|
|
|
// Build payload: content_hash(32) + piece_index(4) + offset(4) = 40 bytes
|
|
var payload: [40]u8 = undefined;
|
|
@memcpy(payload[0..32], &content_hash.?);
|
|
std.mem.writeInt(u32, payload[32..36], 0, .big); // piece_index = 0
|
|
std.mem.writeInt(u32, payload[36..40], 0, .big); // offset = 0
|
|
|
|
// Should execute without crashing (might fail due to upload manager setup)
|
|
manager.handlePieceRequest(peer_id, &payload) catch |err| {
|
|
// OperationNotSupported is expected if upload manager not set up
|
|
try testing.expect(err == Error.OperationNotSupported or err == Error.FileError);
|
|
};
|
|
}
|
|
|
|
test "FileSharingManager: handleBitfield with valid session" {
|
|
ensureTestDir();
|
|
const config = createTestConfig();
|
|
|
|
var manager = FileSharingManager.initForTesting(config, testing.allocator) catch return error.SkipZigTest;
|
|
defer manager.deinit();
|
|
|
|
// Create file and session
|
|
const test_content = "B" ** 4096; // 4KB file
|
|
var path_buf: [256]u8 = undefined;
|
|
const file_path = createTestFileInBuf(&path_buf, "bitfield_test.txt", test_content) catch return error.SkipZigTest;
|
|
defer deleteTestFile("bitfield_test.txt");
|
|
|
|
const session_id = manager.addFile(file_path) catch return error.SkipZigTest;
|
|
|
|
// Get content hash from session
|
|
const content_hash = manager.withSessionResult(session_id, [32]u8, struct {
|
|
fn callback(session: *FileSharingSession) [32]u8 {
|
|
return session.content_hash;
|
|
}
|
|
}.callback);
|
|
|
|
if (content_hash == null) return error.SkipZigTest;
|
|
|
|
var peer_id: [32]u8 = undefined;
|
|
@memset(&peer_id, 0xBB);
|
|
|
|
// Build bitfield payload: content_hash(32) + bitfield data
|
|
var payload: [40]u8 = undefined;
|
|
@memcpy(payload[0..32], &content_hash.?);
|
|
@memset(payload[32..40], 0xFF); // All pieces available
|
|
|
|
// Handle bitfield - should update peer's piece availability
|
|
manager.handleBitfield(peer_id, &payload) catch |err| {
|
|
// May log warning but shouldn't crash
|
|
std.debug.print("handleBitfield error (expected for non-downloading session): {}\n", .{err});
|
|
};
|
|
}
|
|
|
|
test "FileSharingManager: handleHave with valid session" {
|
|
ensureTestDir();
|
|
const config = createTestConfig();
|
|
|
|
var manager = FileSharingManager.initForTesting(config, testing.allocator) catch return error.SkipZigTest;
|
|
defer manager.deinit();
|
|
|
|
// Create file and session
|
|
const test_content = "C" ** 3000;
|
|
var path_buf: [256]u8 = undefined;
|
|
const file_path = createTestFileInBuf(&path_buf, "have_test.txt", test_content) catch return error.SkipZigTest;
|
|
defer deleteTestFile("have_test.txt");
|
|
|
|
const session_id = manager.addFile(file_path) catch return error.SkipZigTest;
|
|
|
|
const content_hash = manager.withSessionResult(session_id, [32]u8, struct {
|
|
fn callback(session: *FileSharingSession) [32]u8 {
|
|
return session.content_hash;
|
|
}
|
|
}.callback);
|
|
|
|
if (content_hash == null) return error.SkipZigTest;
|
|
|
|
var peer_id: [32]u8 = undefined;
|
|
@memset(&peer_id, 0xCC);
|
|
|
|
// Build have payload: content_hash(32) + piece_index(4)
|
|
var payload: [36]u8 = undefined;
|
|
@memcpy(payload[0..32], &content_hash.?);
|
|
std.mem.writeInt(u32, payload[32..36], 0, .big); // piece_index = 0
|
|
|
|
// Handle have
|
|
manager.handleHave(peer_id, &payload) catch |err| {
|
|
std.debug.print("handleHave error (expected): {}\n", .{err});
|
|
};
|
|
}
|
|
|
|
// ============================================================================
|
|
// Network Sender Integration Tests
|
|
// ============================================================================
|
|
|
|
test "FileSharingManager: network sender callback" {
|
|
ensureTestDir();
|
|
const config = createTestConfig();
|
|
|
|
var manager = FileSharingManager.initForTesting(config, testing.allocator) catch return error.SkipZigTest;
|
|
defer manager.deinit();
|
|
|
|
var mock_sender = MockNetworkSender{};
|
|
var sender = NetworkSender.init(&MockNetworkSender.sendCallback, @ptrCast(&mock_sender), testing.allocator);
|
|
|
|
manager.setNetworkSender(&sender);
|
|
defer manager.clearNetworkSender();
|
|
|
|
// Create a session
|
|
const test_content = "D" ** 1500;
|
|
var path_buf: [256]u8 = undefined;
|
|
const file_path = createTestFileInBuf(&path_buf, "network_test.txt", test_content) catch return error.SkipZigTest;
|
|
defer deleteTestFile("network_test.txt");
|
|
|
|
_ = manager.addFile(file_path) catch return error.SkipZigTest;
|
|
|
|
// The network sender is set - operations that send messages will use it
|
|
try testing.expect(manager.network_sender != null);
|
|
}
|
|
|
|
// ============================================================================
|
|
// downloadFile Tests
|
|
// ============================================================================
|
|
|
|
test "FileSharingManager: downloadFile creates download session" {
|
|
const config = createTestConfig();
|
|
|
|
var manager = FileSharingManager.initForTesting(config, testing.allocator) catch return error.SkipZigTest;
|
|
defer manager.deinit();
|
|
|
|
// Create metadata for a file we want to download
|
|
const piece_hash: [32]u8 = [_]u8{0xAB} ** 32;
|
|
const piece_hashes = testing.allocator.alloc([32]u8, 1) catch return error.SkipZigTest;
|
|
defer testing.allocator.free(piece_hashes);
|
|
piece_hashes[0] = piece_hash;
|
|
|
|
const name = testing.allocator.dupe(u8, "download_test.txt") catch return error.SkipZigTest;
|
|
defer testing.allocator.free(name);
|
|
|
|
const metadata = FileMetadata{
|
|
.name = name,
|
|
.size = 1024,
|
|
.piece_count = 1,
|
|
.piece_hashes = piece_hashes,
|
|
.created_at = std.time.timestamp(),
|
|
.modified_at = std.time.timestamp(),
|
|
};
|
|
|
|
// Create output path
|
|
var output_path_buf: [256]u8 = undefined;
|
|
const output_path = std.fmt.bufPrint(&output_path_buf, "{s}/downloaded_file.txt", .{TEST_DIR}) catch return error.SkipZigTest;
|
|
|
|
// Start download
|
|
const session_id = manager.downloadFile(metadata, output_path) catch |err| {
|
|
std.debug.print("downloadFile error: {}\n", .{err});
|
|
return error.SkipZigTest;
|
|
};
|
|
defer {
|
|
// Clean up output file if it was created
|
|
fs.cwd().deleteFile(output_path) catch {};
|
|
}
|
|
|
|
// Verify session was created
|
|
try testing.expect(session_id > 0);
|
|
|
|
const info = manager.getSessionInfo(session_id);
|
|
try testing.expect(info != null);
|
|
|
|
if (info) |session_info| {
|
|
try testing.expect(session_info.file_size == 1024);
|
|
}
|
|
}
|
|
|
|
// ============================================================================
|
|
// Peer Reputation Integration Tests
|
|
// ============================================================================
|
|
|
|
test "FileSharingManager: peer reputation tracking via handlers" {
|
|
const config = createTestConfig();
|
|
|
|
var manager = FileSharingManager.initForTesting(config, testing.allocator) catch return error.SkipZigTest;
|
|
defer manager.deinit();
|
|
|
|
var peer_id: [32]u8 = undefined;
|
|
@memset(&peer_id, 0xDD);
|
|
|
|
// Initially no reputation
|
|
try testing.expect(manager.getPeerReputation(peer_id) == null);
|
|
|
|
// After handling messages from peer, reputation may be created
|
|
// (depends on handler implementation)
|
|
|
|
// Test direct reputation access
|
|
const rep = PeerReputation.init(peer_id);
|
|
try testing.expectEqual(@as(u32, 0), rep.bad_pieces);
|
|
try testing.expectEqual(@as(u32, 0), rep.good_pieces);
|
|
}
|
|
|
|
// ============================================================================
|
|
// Session State Tests
|
|
// ============================================================================
|
|
|
|
test "FileSharingManager: withSession callback execution" {
|
|
ensureTestDir();
|
|
const config = createTestConfig();
|
|
|
|
var manager = FileSharingManager.initForTesting(config, testing.allocator) catch return error.SkipZigTest;
|
|
defer manager.deinit();
|
|
|
|
var path_buf: [256]u8 = undefined;
|
|
const test_content = "E" ** 500;
|
|
const file_path = createTestFileInBuf(&path_buf, "with_session_test.txt", test_content) catch return error.SkipZigTest;
|
|
defer deleteTestFile("with_session_test.txt");
|
|
|
|
const session_id = manager.addFile(file_path) catch return error.SkipZigTest;
|
|
|
|
// Use withSession to access session - should not return error
|
|
manager.withSession(session_id, struct {
|
|
fn callback(_: *FileSharingSession) Error!void {
|
|
// Just verify we can access the session
|
|
}
|
|
}.callback) catch |err| {
|
|
std.debug.print("withSession error: {}\n", .{err});
|
|
return err;
|
|
};
|
|
}
|
|
|
|
test "FileSharingManager: withSessionResult returns value" {
|
|
ensureTestDir();
|
|
const config = createTestConfig();
|
|
|
|
var manager = FileSharingManager.initForTesting(config, testing.allocator) catch return error.SkipZigTest;
|
|
defer manager.deinit();
|
|
|
|
var path_buf: [256]u8 = undefined;
|
|
const test_content = "F" ** 800;
|
|
const file_path = createTestFileInBuf(&path_buf, "with_result_test.txt", test_content) catch return error.SkipZigTest;
|
|
defer deleteTestFile("with_result_test.txt");
|
|
|
|
const session_id = manager.addFile(file_path) catch return error.SkipZigTest;
|
|
|
|
// Use withSessionResult to get a value from session
|
|
const file_size = manager.withSessionResult(session_id, u64, struct {
|
|
fn callback(session: *FileSharingSession) u64 {
|
|
return session.file_metadata.size;
|
|
}
|
|
}.callback);
|
|
|
|
try testing.expect(file_size != null);
|
|
if (file_size) |size| {
|
|
try testing.expectEqual(@as(u64, 800), size);
|
|
}
|
|
}
|
|
|
|
// ============================================================================
|
|
// processSessions and processVerificationResults Tests
|
|
// ============================================================================
|
|
|
|
test "FileSharingManager: processSessions with active sessions" {
|
|
ensureTestDir();
|
|
const config = createTestConfig();
|
|
|
|
var manager = FileSharingManager.initForTesting(config, testing.allocator) catch return error.SkipZigTest;
|
|
defer manager.deinit();
|
|
|
|
// Create a session
|
|
var path_buf: [256]u8 = undefined;
|
|
const test_content = "G" ** 1000;
|
|
const file_path = createTestFileInBuf(&path_buf, "process_test.txt", test_content) catch return error.SkipZigTest;
|
|
defer deleteTestFile("process_test.txt");
|
|
|
|
_ = manager.addFile(file_path) catch return error.SkipZigTest;
|
|
|
|
// Process sessions - should not crash with active sessions
|
|
manager.processSessions() catch |err| {
|
|
std.debug.print("processSessions error (may be expected): {}\n", .{err});
|
|
};
|
|
}
|
|
|
|
test "FileSharingManager: processVerificationResults" {
|
|
const config = createTestConfig();
|
|
|
|
var manager = FileSharingManager.initForTesting(config, testing.allocator) catch return error.SkipZigTest;
|
|
defer manager.deinit();
|
|
|
|
// Process verification - should not crash even without active verifications
|
|
manager.processVerificationResults();
|
|
}
|
|
|
|
// ============================================================================
|
|
// Resource Limit Tests
|
|
// ============================================================================
|
|
|
|
test "FileSharingManager: session limit enforcement" {
|
|
var config = createTestConfig();
|
|
// Note: We can't easily test session limits without creating many files
|
|
// This test verifies the config is respected
|
|
|
|
config.max_concurrent_downloads = 2;
|
|
config.max_concurrent_uploads = 2;
|
|
|
|
var manager = FileSharingManager.initForTesting(config, testing.allocator) catch return error.SkipZigTest;
|
|
defer manager.deinit();
|
|
|
|
try testing.expectEqual(@as(usize, 2), manager.config.max_concurrent_downloads);
|
|
try testing.expectEqual(@as(usize, 2), manager.config.max_concurrent_uploads);
|
|
}
|
|
|
|
// ============================================================================
|
|
// File Metadata Tests
|
|
// ============================================================================
|
|
|
|
test "FileSharingManager: getFileMetadataByHash" {
|
|
ensureTestDir();
|
|
const config = createTestConfig();
|
|
|
|
var manager = FileSharingManager.initForTesting(config, testing.allocator) catch return error.SkipZigTest;
|
|
defer manager.deinit();
|
|
|
|
var path_buf: [256]u8 = undefined;
|
|
const test_content = "H" ** 600;
|
|
const file_path = createTestFileInBuf(&path_buf, "metadata_hash_test.txt", test_content) catch return error.SkipZigTest;
|
|
defer deleteTestFile("metadata_hash_test.txt");
|
|
|
|
const session_id = manager.addFile(file_path) catch return error.SkipZigTest;
|
|
|
|
// Get content hash from session
|
|
const content_hash = manager.withSessionResult(session_id, [32]u8, struct {
|
|
fn callback(session: *FileSharingSession) [32]u8 {
|
|
return session.content_hash;
|
|
}
|
|
}.callback);
|
|
|
|
if (content_hash) |hash| {
|
|
// Try to get metadata by hash
|
|
const metadata = manager.getFileMetadataByHash(hash, testing.allocator) catch return error.SkipZigTest;
|
|
if (metadata) |m| {
|
|
defer {
|
|
testing.allocator.free(m.name);
|
|
testing.allocator.free(m.piece_hashes);
|
|
}
|
|
try testing.expect(m.size == 600);
|
|
}
|
|
}
|
|
}
|
|
|
|
test "FileSharingManager: getSessionInfoByHash" {
|
|
ensureTestDir();
|
|
const config = createTestConfig();
|
|
|
|
var manager = FileSharingManager.initForTesting(config, testing.allocator) catch return error.SkipZigTest;
|
|
defer manager.deinit();
|
|
|
|
var path_buf: [256]u8 = undefined;
|
|
const test_content = "I" ** 700;
|
|
const file_path = createTestFileInBuf(&path_buf, "info_hash_test.txt", test_content) catch return error.SkipZigTest;
|
|
defer deleteTestFile("info_hash_test.txt");
|
|
|
|
const session_id = manager.addFile(file_path) catch return error.SkipZigTest;
|
|
|
|
// Get content hash from session
|
|
const content_hash = manager.withSessionResult(session_id, [32]u8, struct {
|
|
fn callback(session: *FileSharingSession) [32]u8 {
|
|
return session.content_hash;
|
|
}
|
|
}.callback);
|
|
|
|
if (content_hash) |hash| {
|
|
const info = manager.getSessionInfoByHash(hash);
|
|
try testing.expect(info != null);
|
|
if (info) |session_info| {
|
|
try testing.expect(session_info.file_size == 700);
|
|
}
|
|
}
|
|
}
|
|
|
|
// ============================================================================
|
|
// Full Session Workflow Tests
|
|
// ============================================================================
|
|
|
|
test "FileSharingManager: full sharing workflow addFile->startSharing->stopSharing" {
|
|
ensureTestDir();
|
|
const config = createTestConfig();
|
|
|
|
var manager = FileSharingManager.initForTesting(config, testing.allocator) catch return error.SkipZigTest;
|
|
defer manager.deinit();
|
|
|
|
var path_buf: [256]u8 = undefined;
|
|
const test_content = "Full workflow test content " ** 100;
|
|
const file_path = createTestFileInBuf(&path_buf, "full_workflow.txt", test_content) catch return error.SkipZigTest;
|
|
defer deleteTestFile("full_workflow.txt");
|
|
|
|
// Step 1: Add file
|
|
const session_id = manager.addFile(file_path) catch return error.SkipZigTest;
|
|
try testing.expect(session_id > 0);
|
|
|
|
// Verify initial state
|
|
var info = manager.getSessionInfo(session_id);
|
|
try testing.expect(info != null);
|
|
|
|
// Step 2: Start sharing (upload mode)
|
|
manager.startSharing(session_id) catch |err| {
|
|
// May fail if no peers, which is expected
|
|
if (err != Error.ConnectionNotFound) {
|
|
std.debug.print("startSharing unexpected error: {}\n", .{err});
|
|
}
|
|
};
|
|
|
|
// Step 3: Stop sharing
|
|
manager.stopSharing(session_id) catch {};
|
|
|
|
// Session should be removed
|
|
info = manager.getSessionInfo(session_id);
|
|
try testing.expect(info == null);
|
|
}
|
|
|
|
test "FileSharingManager: multiple concurrent sessions" {
|
|
ensureTestDir();
|
|
const config = createTestConfig();
|
|
|
|
var manager = FileSharingManager.initForTesting(config, testing.allocator) catch return error.SkipZigTest;
|
|
defer manager.deinit();
|
|
|
|
// Create multiple test files
|
|
var path_buf1: [256]u8 = undefined;
|
|
var path_buf2: [256]u8 = undefined;
|
|
var path_buf3: [256]u8 = undefined;
|
|
|
|
const path1 = createTestFileInBuf(&path_buf1, "concurrent1.txt", "Content 1 " ** 50) catch return error.SkipZigTest;
|
|
defer deleteTestFile("concurrent1.txt");
|
|
const path2 = createTestFileInBuf(&path_buf2, "concurrent2.txt", "Content 2 " ** 60) catch return error.SkipZigTest;
|
|
defer deleteTestFile("concurrent2.txt");
|
|
const path3 = createTestFileInBuf(&path_buf3, "concurrent3.txt", "Content 3 " ** 70) catch return error.SkipZigTest;
|
|
defer deleteTestFile("concurrent3.txt");
|
|
|
|
// Add all files
|
|
const session1 = manager.addFile(path1) catch return error.SkipZigTest;
|
|
const session2 = manager.addFile(path2) catch return error.SkipZigTest;
|
|
const session3 = manager.addFile(path3) catch return error.SkipZigTest;
|
|
|
|
// Verify all sessions exist
|
|
try testing.expect(manager.getSessionInfo(session1) != null);
|
|
try testing.expect(manager.getSessionInfo(session2) != null);
|
|
try testing.expect(manager.getSessionInfo(session3) != null);
|
|
|
|
// Stop sessions one by one
|
|
manager.stopSharing(session1) catch {};
|
|
try testing.expect(manager.getSessionInfo(session1) == null);
|
|
try testing.expect(manager.getSessionInfo(session2) != null);
|
|
try testing.expect(manager.getSessionInfo(session3) != null);
|
|
|
|
manager.stopSharing(session2) catch {};
|
|
try testing.expect(manager.getSessionInfo(session2) == null);
|
|
try testing.expect(manager.getSessionInfo(session3) != null);
|
|
|
|
manager.stopSharing(session3) catch {};
|
|
try testing.expect(manager.getSessionInfo(session3) == null);
|
|
}
|
|
|
|
test "FileSharingManager: stopSharing non-existent session returns error" {
|
|
const config = createTestConfig();
|
|
|
|
var manager = FileSharingManager.initForTesting(config, testing.allocator) catch return error.SkipZigTest;
|
|
defer manager.deinit();
|
|
|
|
// Try to stop a session that doesn't exist
|
|
const result = manager.stopSharing(999999);
|
|
try testing.expectError(Error.ConnectionNotFound, result);
|
|
}
|
|
|
|
test "FileSharingManager: startSharing on non-existent session returns error" {
|
|
const config = createTestConfig();
|
|
|
|
var manager = FileSharingManager.initForTesting(config, testing.allocator) catch return error.SkipZigTest;
|
|
defer manager.deinit();
|
|
|
|
// Try to start sharing for a session that doesn't exist
|
|
const result = manager.startSharing(999999);
|
|
try testing.expectError(Error.ConnectionNotFound, result);
|
|
}
|
|
|
|
test "FileSharingManager: getSessionInfo on non-existent session returns null" {
|
|
const config = createTestConfig();
|
|
|
|
var manager = FileSharingManager.initForTesting(config, testing.allocator) catch return error.SkipZigTest;
|
|
defer manager.deinit();
|
|
|
|
const info = manager.getSessionInfo(999999);
|
|
try testing.expect(info == null);
|
|
}
|
|
|
|
test "FileSharingManager: session piece count calculation" {
|
|
ensureTestDir();
|
|
const config = createTestConfig();
|
|
|
|
var manager = FileSharingManager.initForTesting(config, testing.allocator) catch return error.SkipZigTest;
|
|
defer manager.deinit();
|
|
|
|
// Create file exactly 2 pieces worth (2048 bytes with 1024 piece size)
|
|
var path_buf: [256]u8 = undefined;
|
|
const test_content = "X" ** 2048;
|
|
const file_path = createTestFileInBuf(&path_buf, "piece_count.txt", test_content) catch return error.SkipZigTest;
|
|
defer deleteTestFile("piece_count.txt");
|
|
|
|
const session_id = manager.addFile(file_path) catch return error.SkipZigTest;
|
|
|
|
const info = manager.getSessionInfo(session_id);
|
|
try testing.expect(info != null);
|
|
if (info) |session_info| {
|
|
// With 1024 piece size, 2048 bytes = 2 pieces
|
|
try testing.expectEqual(@as(u32, 2), session_info.piece_count);
|
|
}
|
|
}
|
|
|
|
test "FileSharingManager: session with small file (single piece)" {
|
|
ensureTestDir();
|
|
const config = createTestConfig();
|
|
|
|
var manager = FileSharingManager.initForTesting(config, testing.allocator) catch return error.SkipZigTest;
|
|
defer manager.deinit();
|
|
|
|
// Create file smaller than piece size
|
|
var path_buf: [256]u8 = undefined;
|
|
const test_content = "Small" ** 10; // 50 bytes
|
|
const file_path = createTestFileInBuf(&path_buf, "small_file.txt", test_content) catch return error.SkipZigTest;
|
|
defer deleteTestFile("small_file.txt");
|
|
|
|
const session_id = manager.addFile(file_path) catch return error.SkipZigTest;
|
|
|
|
const info = manager.getSessionInfo(session_id);
|
|
try testing.expect(info != null);
|
|
if (info) |session_info| {
|
|
try testing.expectEqual(@as(u32, 1), session_info.piece_count);
|
|
try testing.expectEqual(@as(u64, 50), session_info.file_size);
|
|
}
|
|
}
|
|
|
|
test "FileSharingManager: session with large file (many pieces)" {
|
|
ensureTestDir();
|
|
const config = createTestConfig();
|
|
|
|
var manager = FileSharingManager.initForTesting(config, testing.allocator) catch return error.SkipZigTest;
|
|
defer manager.deinit();
|
|
|
|
// Create file with multiple pieces (10KB with 1024 piece size = 10 pieces)
|
|
var path_buf: [256]u8 = undefined;
|
|
const test_content = "Y" ** 10240;
|
|
const file_path = createTestFileInBuf(&path_buf, "large_file.txt", test_content) catch return error.SkipZigTest;
|
|
defer deleteTestFile("large_file.txt");
|
|
|
|
const session_id = manager.addFile(file_path) catch return error.SkipZigTest;
|
|
|
|
const info = manager.getSessionInfo(session_id);
|
|
try testing.expect(info != null);
|
|
if (info) |session_info| {
|
|
try testing.expectEqual(@as(u32, 10), session_info.piece_count);
|
|
try testing.expectEqual(@as(u64, 10240), session_info.file_size);
|
|
}
|
|
}
|
|
|
|
test "FileSharingManager: getStats returns valid statistics" {
|
|
ensureTestDir();
|
|
const config = createTestConfig();
|
|
|
|
var manager = FileSharingManager.initForTesting(config, testing.allocator) catch return error.SkipZigTest;
|
|
defer manager.deinit();
|
|
|
|
// Get initial stats
|
|
var stats = manager.getStats();
|
|
const initial_sessions = stats.total_sessions;
|
|
|
|
// Add a session
|
|
var path_buf: [256]u8 = undefined;
|
|
const test_content = "Stats test " ** 50;
|
|
const file_path = createTestFileInBuf(&path_buf, "stats_test.txt", test_content) catch return error.SkipZigTest;
|
|
defer deleteTestFile("stats_test.txt");
|
|
|
|
_ = manager.addFile(file_path) catch return error.SkipZigTest;
|
|
|
|
// Stats should be updated
|
|
stats = manager.getStats();
|
|
try testing.expect(stats.total_sessions >= initial_sessions + 1);
|
|
}
|
|
|
|
test "FileSharingManager: session content hash is deterministic" {
|
|
ensureTestDir();
|
|
const config = createTestConfig();
|
|
|
|
var manager = FileSharingManager.initForTesting(config, testing.allocator) catch return error.SkipZigTest;
|
|
defer manager.deinit();
|
|
|
|
// Create file
|
|
var path_buf: [256]u8 = undefined;
|
|
const test_content = "Deterministic hash test content";
|
|
const file_path = createTestFileInBuf(&path_buf, "hash_test.txt", test_content) catch return error.SkipZigTest;
|
|
defer deleteTestFile("hash_test.txt");
|
|
|
|
const session_id = manager.addFile(file_path) catch return error.SkipZigTest;
|
|
|
|
// Get content hash
|
|
const hash1 = manager.withSessionResult(session_id, [32]u8, struct {
|
|
fn callback(session: *FileSharingSession) [32]u8 {
|
|
return session.content_hash;
|
|
}
|
|
}.callback);
|
|
|
|
try testing.expect(hash1 != null);
|
|
|
|
// Verify hash is not all zeros
|
|
if (hash1) |h| {
|
|
var all_zero = true;
|
|
for (h) |byte| {
|
|
if (byte != 0) {
|
|
all_zero = false;
|
|
break;
|
|
}
|
|
}
|
|
try testing.expect(!all_zero);
|
|
}
|
|
}
|
|
|
|
test "FileSharingManager: handlePieceRequest rejects short payload" {
|
|
ensureTestDir();
|
|
const config = createTestConfig();
|
|
|
|
var manager = FileSharingManager.initForTesting(config, testing.allocator) catch return error.SkipZigTest;
|
|
defer manager.deinit();
|
|
|
|
var peer_id: [32]u8 = undefined;
|
|
@memset(&peer_id, 0xAA);
|
|
|
|
// Request with payload too short (less than 40 bytes required)
|
|
const short_payload = [_]u8{0} ** 20;
|
|
const result = manager.handlePieceRequest(peer_id, &short_payload);
|
|
try testing.expectError(Error.InvalidData, result);
|
|
}
|
|
|
|
test "FileSharingManager: handlePieceRequest rejects unknown content hash" {
|
|
ensureTestDir();
|
|
const config = createTestConfig();
|
|
|
|
var manager = FileSharingManager.initForTesting(config, testing.allocator) catch return error.SkipZigTest;
|
|
defer manager.deinit();
|
|
|
|
var peer_id: [32]u8 = undefined;
|
|
@memset(&peer_id, 0xBB);
|
|
|
|
// Construct payload with unknown content hash
|
|
var payload: [40]u8 = undefined;
|
|
@memset(payload[0..32], 0xFF); // content_hash (unknown)
|
|
std.mem.writeInt(u32, payload[32..36], 0, .big); // piece_index
|
|
std.mem.writeInt(u32, payload[36..40], 0, .big); // offset
|
|
|
|
const result = manager.handlePieceRequest(peer_id, &payload);
|
|
// Should return FileError since no session has this content hash
|
|
try testing.expectError(Error.FileError, result);
|
|
}
|
|
|
|
test "FileSharingManager: cleanup releases all resources" {
|
|
ensureTestDir();
|
|
const config = createTestConfig();
|
|
|
|
var manager = FileSharingManager.initForTesting(config, testing.allocator) catch return error.SkipZigTest;
|
|
|
|
// Add some sessions
|
|
var path_buf1: [256]u8 = undefined;
|
|
var path_buf2: [256]u8 = undefined;
|
|
|
|
const path1 = createTestFileInBuf(&path_buf1, "cleanup1.txt", "Cleanup 1") catch return error.SkipZigTest;
|
|
defer deleteTestFile("cleanup1.txt");
|
|
const path2 = createTestFileInBuf(&path_buf2, "cleanup2.txt", "Cleanup 2") catch return error.SkipZigTest;
|
|
defer deleteTestFile("cleanup2.txt");
|
|
|
|
_ = manager.addFile(path1) catch return error.SkipZigTest;
|
|
_ = manager.addFile(path2) catch return error.SkipZigTest;
|
|
|
|
// Verify sessions exist
|
|
const sessions = manager.getActiveSessions() catch return error.SkipZigTest;
|
|
defer testing.allocator.free(sessions);
|
|
try testing.expect(sessions.len >= 2);
|
|
|
|
// Cleanup should not leak (deinit is called by defer)
|
|
manager.deinit();
|
|
}
|
|
|
|
test "FileSharingManager: session status transitions" {
|
|
ensureTestDir();
|
|
const config = createTestConfig();
|
|
|
|
var manager = FileSharingManager.initForTesting(config, testing.allocator) catch return error.SkipZigTest;
|
|
defer manager.deinit();
|
|
|
|
var path_buf: [256]u8 = undefined;
|
|
const test_content = "Status transition test " ** 50;
|
|
const file_path = createTestFileInBuf(&path_buf, "status_test.txt", test_content) catch return error.SkipZigTest;
|
|
defer deleteTestFile("status_test.txt");
|
|
|
|
const session_id = manager.addFile(file_path) catch return error.SkipZigTest;
|
|
|
|
// Get initial status via withSessionResult
|
|
const initial_active = manager.withSessionResult(session_id, bool, struct {
|
|
fn callback(session: *FileSharingSession) bool {
|
|
return session.status != .cancelled;
|
|
}
|
|
}.callback);
|
|
try testing.expect(initial_active != null);
|
|
try testing.expect(initial_active.?);
|
|
|
|
// Start sharing
|
|
manager.startSharing(session_id) catch {};
|
|
|
|
// Stop sharing
|
|
manager.stopSharing(session_id) catch {};
|
|
|
|
// Session should be removed after stopSharing
|
|
const info = manager.getSessionInfo(session_id);
|
|
try testing.expect(info == null);
|
|
}
|