//! Comprehensive tests for download management //! Tests initialization, piece selection strategies, verification, progress tracking, //! concurrent operations, error handling, and resume functionality const std = @import("std"); const testing = std.testing; const files = @import("files"); const core = @import("core"); const Error = core.errors.Error; test "download: initialization with valid parameters" { const allocator = testing.allocator; var manager = try files.download.DownloadManager.init( 10000, // total_size 10, // piece_count .rarest_first, 1000, // piece_size allocator, ); defer manager.deinit(); try testing.expectEqual(@as(u64, 10000), manager.total_size); try testing.expectEqual(@as(u32, 10), manager.state.piece_count); try testing.expectEqual(@as(u64, 1000), manager.piece_size); } test "download: piece selection sequential strategy" { const allocator = testing.allocator; var manager = try files.download.DownloadManager.init( 5000, 5, .sequential, 1000, allocator, ); defer manager.deinit(); // Add all pieces as available var i: u32 = 0; while (i < 5) : (i += 1) { try manager.selector.addPiece(i, 1); try manager.selector.setPriority(i, .normal); } const pieces = try manager.getNeededPieces(3); defer allocator.free(pieces); // Sequential should return in order try testing.expectEqual(@as(usize, 3), pieces.len); try testing.expectEqual(@as(u32, 0), pieces[0]); try testing.expectEqual(@as(u32, 1), pieces[1]); try testing.expectEqual(@as(u32, 2), pieces[2]); } test "download: piece selection rarest first strategy" { const allocator = testing.allocator; var manager = try files.download.DownloadManager.init( 5000, 5, .rarest_first, 1000, allocator, ); defer manager.deinit(); // Add pieces with different availabilities try manager.selector.addPiece(0, 5); // Common try manager.selector.addPiece(1, 1); // Rarest try manager.selector.addPiece(2, 3); // Medium try manager.selector.addPiece(3, 1); // Rarest try manager.selector.addPiece(4, 4); // Common const pieces = try manager.getNeededPieces(2); defer allocator.free(pieces); // Should get rarest pieces (1 and 3, both with availability 1) try testing.expectEqual(@as(usize, 2), pieces.len); try testing.expect((pieces[0] == 1 and pieces[1] == 3) or (pieces[0] == 3 and pieces[1] == 1)); } test "download: piece selection random strategy" { const allocator = testing.allocator; var manager = try files.download.DownloadManager.init( 5000, 5, .random, 1000, allocator, ); defer manager.deinit(); var i: u32 = 0; while (i < 5) : (i += 1) { try manager.selector.addPiece(i, 1); } const pieces = try manager.getNeededPieces(5); defer allocator.free(pieces); // Should get all pieces (order is random) try testing.expectEqual(@as(usize, 5), pieces.len); } test "download: piece verification with correct hash" { const allocator = testing.allocator; var manager = try files.download.DownloadManager.init( 1000, 1, .sequential, 1000, allocator, ); defer manager.deinit(); const test_file = "test_download_verify.bin"; try manager.setOutputFile(test_file); defer std.fs.cwd().deleteFile(test_file) catch {}; const test_data = "Test piece data for verification"; const piece_hash = try files.hash.HashUtils.sha256(test_data); try manager.selector.addPiece(0, 1); try manager.handlePieceData(0, test_data, piece_hash); // Piece should be marked as completed try testing.expectEqual(@as(u32, 1), manager.state.completed_pieces.load(.monotonic)); } test "download: piece verification with incorrect hash" { const allocator = testing.allocator; var manager = try files.download.DownloadManager.init( 1000, 1, .sequential, 1000, allocator, ); defer manager.deinit(); const test_file = "test_download_bad_hash.bin"; try manager.setOutputFile(test_file); defer std.fs.cwd().deleteFile(test_file) catch {}; const test_data = "Test piece data"; const wrong_hash = [_]u8{0xFF} ** 32; // Wrong hash try manager.selector.addPiece(0, 1); const result = manager.handlePieceData(0, test_data, wrong_hash); try testing.expectError(Error.InvalidData, result); // Piece should be marked as failed try testing.expectEqual(@as(u32, 1), manager.state.failed_pieces.load(.monotonic)); } test "download: progress tracking" { const allocator = testing.allocator; const total_size: u64 = 10000; var manager = try files.download.DownloadManager.init( total_size, 10, .sequential, 1000, allocator, ); defer manager.deinit(); try testing.expectEqual(@as(f32, 0.0), manager.state.getProgress()); // Simulate downloading half the data manager.state.addDownloadedBytes(5000); try testing.expectEqual(@as(f32, 0.5), manager.state.getProgress()); // Simulate downloading all data manager.state.addDownloadedBytes(5000); try testing.expectEqual(@as(f32, 1.0), manager.state.getProgress()); } test "download: concurrent piece downloads" { const allocator = testing.allocator; var manager = try files.download.DownloadManager.init( 5000, 5, .sequential, 1000, allocator, ); defer manager.deinit(); // Add pieces var i: u32 = 0; while (i < 5) : (i += 1) { try manager.selector.addPiece(i, 1); } // Request multiple pieces concurrently try manager.requestPiece(0, .high, "peer1"); try manager.requestPiece(1, .normal, "peer2"); try manager.requestPiece(2, .normal, "peer3"); try testing.expectEqual(@as(usize, 3), manager.pending_requests.items.len); // Process requests with max concurrent = 2 try manager.processRequests(2); // Should have 2 active downloads try testing.expectEqual(@as(usize, 2), manager.active_downloads.count()); try testing.expectEqual(@as(usize, 1), manager.pending_requests.items.len); } test "download: request expiration cleanup" { const allocator = testing.allocator; var manager = try files.download.DownloadManager.init( 1000, 1, .sequential, 1000, allocator, ); defer manager.deinit(); try manager.selector.addPiece(0, 1); // Create request with old timestamp var request = files.download.DownloadRequest.create(0, 0, 1000, .normal, "peer1"); request.requested_at = std.time.timestamp() - 100; // 100 seconds ago try manager.pending_requests.append(allocator, request); // Set timeout to 30 seconds manager.request_timeout = 30; // Process requests should clean up expired try manager.processRequests(5); try testing.expectEqual(@as(usize, 0), manager.pending_requests.items.len); } test "download: disk full handling simulation" { const allocator = testing.allocator; var manager = try files.download.DownloadManager.init( 1000, 1, .sequential, 1000, allocator, ); defer manager.deinit(); // Try to set output file to invalid path (simulates disk issues) const invalid_path = "/nonexistent/path/to/file.bin"; const result = manager.setOutputFile(invalid_path); // Should fail gracefully try testing.expectError(Error.InvalidData, result); } test "download: update peer availability" { const allocator = testing.allocator; var manager = try files.download.DownloadManager.init( 3000, 3, .rarest_first, 1000, allocator, ); defer manager.deinit(); try manager.selector.addPiece(0, 1); // Update availability try manager.updatePeerAvailability("peer1", 0, true); const piece_info = manager.selector.availability_map.get(0).?; try testing.expectEqual(@as(u32, 2), piece_info.available_peers); // Decrease availability try manager.updatePeerAvailability("peer1", 0, false); const updated_info = manager.selector.availability_map.get(0).?; try testing.expectEqual(@as(u32, 1), updated_info.available_peers); } test "download: set piece priority" { const allocator = testing.allocator; var manager = try files.download.DownloadManager.init( 3000, 3, .sequential, 1000, allocator, ); defer manager.deinit(); try manager.selector.addPiece(0, 1); try manager.setPiecePriority(0, .urgent); const piece_info = manager.selector.availability_map.get(0).?; try testing.expectEqual(files.piece.PieceAvailability.Priority.urgent, piece_info.priority); } test "download: completion check" { const allocator = testing.allocator; var manager = try files.download.DownloadManager.init( 3000, 3, .sequential, 1000, allocator, ); defer manager.deinit(); try testing.expect(!manager.isComplete()); // Mark all pieces as completed manager.state.markPieceCompleted(); manager.state.markPieceCompleted(); manager.state.markPieceCompleted(); try testing.expect(manager.isComplete()); } test "download: download stats accuracy" { const allocator = testing.allocator; var manager = try files.download.DownloadManager.init( 10000, 10, .sequential, 1000, allocator, ); defer manager.deinit(); // Add some downloaded bytes manager.state.addDownloadedBytes(2500); manager.state.markPieceCompleted(); manager.state.markPieceCompleted(); const stats = manager.getStats(); try testing.expectEqual(@as(f32, 0.25), stats.progress); try testing.expectEqual(@as(u32, 2), stats.state.completed_pieces.load(.monotonic)); try testing.expectEqual(@as(u64, 2500), stats.state.downloaded_bytes.load(.monotonic)); } test "download: handle download failure" { const allocator = testing.allocator; var manager = try files.download.DownloadManager.init( 1000, 1, .sequential, 1000, allocator, ); defer manager.deinit(); try manager.selector.addPiece(0, 1); // Create active download const request = files.download.DownloadRequest.create(0, 0, 1000, .normal, "peer1"); const active_download = files.download.ActiveDownload{ .piece_index = 0, .peer_id = "peer1", .offset = 0, .length = 1000, .downloaded_bytes = 0, .started_at = std.time.timestamp(), .status = .downloading, }; try manager.active_downloads.put(0, active_download); // Handle failure try manager.handleDownloadFailure(0, "Network timeout"); // Should be removed from active downloads try testing.expect(!manager.active_downloads.contains(0)); try testing.expectEqual(@as(u32, 1), manager.state.failed_pieces.load(.monotonic)); } test "download: verify piece from disk" { const allocator = testing.allocator; // Create test file const test_file = "test_piece_verify.bin"; const test_data = "This is test data for piece verification from disk"; const file = try std.fs.cwd().createFile(test_file, .{}); _ = try file.write(test_data); file.close(); defer std.fs.cwd().deleteFile(test_file) catch {}; var manager = try files.download.DownloadManager.init( test_data.len, 1, .sequential, test_data.len, allocator, ); defer manager.deinit(); try manager.setOutputFile(test_file); // Add piece to available try manager.selector.addPiece(0, 1); // Calculate expected hash const expected_hash = try files.hash.HashUtils.sha256(test_data); // Verify piece const is_valid = try manager.verifyPiece(0, &expected_hash); try testing.expect(is_valid); // Verify with wrong hash const wrong_hash = [_]u8{0xAA} ** 32; const is_invalid = try manager.verifyPiece(0, &wrong_hash); try testing.expect(!is_invalid); }