896 lines
33 KiB
Zig
896 lines
33 KiB
Zig
//! Comprehensive tests for upload module
|
|
//!
|
|
//! Tests cover:
|
|
//! - PieceData: zero-copy vs owned memory patterns
|
|
//! - UploadRequest: creation, expiration, scoring
|
|
//! - UploadState: atomic counters, bandwidth tracking, statistics
|
|
//! - BandwidthLimiter: atomic consumption, utilization, dynamic limits
|
|
//! - UploadManager: full upload lifecycle, cancellation, peer limits
|
|
//! - UploadQueue: multi-manager coordination
|
|
//! - CombinedUploadStats: speed calculations
|
|
|
|
const std = @import("std");
|
|
const testing = std.testing;
|
|
const files = @import("files");
|
|
const upload = files.upload;
|
|
const PieceData = upload.PieceData;
|
|
const UploadRequest = upload.UploadRequest;
|
|
const UploadState = upload.UploadState;
|
|
const BandwidthLimiter = upload.BandwidthLimiter;
|
|
const UploadManager = upload.UploadManager;
|
|
const UploadQueue = upload.UploadQueue;
|
|
const CombinedUploadStats = upload.CombinedUploadStats;
|
|
const UploadStats = upload.UploadStats;
|
|
const UploadManagerStats = upload.UploadManagerStats;
|
|
const PieceUploadStats = upload.PieceUploadStats;
|
|
const AvailablePiece = upload.AvailablePiece;
|
|
const ActiveUpload = upload.ActiveUpload;
|
|
const PeerLimit = upload.PeerLimit;
|
|
|
|
const core = @import("core");
|
|
const Error = core.errors.Error;
|
|
|
|
// =============================================================================
|
|
// PieceData Tests - Zero-copy memory patterns
|
|
// =============================================================================
|
|
|
|
test "PieceData.borrowed creates zero-copy reference" {
|
|
const data = "test data for borrowed reference";
|
|
const piece = PieceData.borrowed(data);
|
|
|
|
try testing.expect(piece.isZeroCopy());
|
|
try testing.expectEqual(@as(?std.mem.Allocator, null), piece.allocator);
|
|
try testing.expectEqualSlices(u8, data, piece.data);
|
|
|
|
// deinit should be a no-op for borrowed data
|
|
piece.deinit();
|
|
}
|
|
|
|
test "PieceData.owned creates allocated reference" {
|
|
const allocator = testing.allocator;
|
|
const original = "owned data that will be freed";
|
|
|
|
// Create owned copy
|
|
const copy = try allocator.dupe(u8, original);
|
|
const piece = PieceData.owned(copy, allocator);
|
|
|
|
try testing.expect(!piece.isZeroCopy());
|
|
try testing.expect(piece.allocator != null);
|
|
try testing.expectEqualSlices(u8, original, piece.data);
|
|
|
|
// deinit should free the memory
|
|
piece.deinit();
|
|
}
|
|
|
|
test "PieceData.isZeroCopy distinguishes borrowed vs owned" {
|
|
const allocator = testing.allocator;
|
|
|
|
const borrowed_data = "borrowed";
|
|
const borrowed = PieceData.borrowed(borrowed_data);
|
|
try testing.expect(borrowed.isZeroCopy());
|
|
|
|
const owned_copy = try allocator.dupe(u8, "owned");
|
|
const owned = PieceData.owned(owned_copy, allocator);
|
|
try testing.expect(!owned.isZeroCopy());
|
|
|
|
// Cleanup
|
|
borrowed.deinit();
|
|
owned.deinit();
|
|
}
|
|
|
|
test "PieceData.borrowed with empty slice" {
|
|
const empty: []const u8 = "";
|
|
const piece = PieceData.borrowed(empty);
|
|
|
|
try testing.expect(piece.isZeroCopy());
|
|
try testing.expectEqual(@as(usize, 0), piece.data.len);
|
|
piece.deinit();
|
|
}
|
|
|
|
// =============================================================================
|
|
// UploadRequest Tests
|
|
// =============================================================================
|
|
|
|
test "UploadRequest.create copies peer_id to owned storage" {
|
|
const peer_id = "short_peer";
|
|
const request = UploadRequest.create(10, 100, 1024, peer_id, .normal);
|
|
|
|
try testing.expectEqual(@as(u32, 10), request.piece_index);
|
|
try testing.expectEqual(@as(u64, 100), request.offset);
|
|
try testing.expectEqual(@as(u32, 1024), request.length);
|
|
try testing.expectEqual(UploadRequest.UploadPriority.normal, request.priority);
|
|
|
|
// Verify peer_id was copied (first bytes match, rest are zeros)
|
|
try testing.expectEqualSlices(u8, peer_id, request.peer_id[0..peer_id.len]);
|
|
for (request.peer_id[peer_id.len..]) |byte| {
|
|
try testing.expectEqual(@as(u8, 0), byte);
|
|
}
|
|
}
|
|
|
|
test "UploadRequest.create truncates long peer_id to 32 bytes" {
|
|
const long_peer_id = "this_is_a_very_long_peer_id_that_exceeds_32_bytes_limit";
|
|
const request = UploadRequest.create(0, 0, 100, long_peer_id, .low);
|
|
|
|
// Should only copy first 32 bytes
|
|
try testing.expectEqualSlices(u8, long_peer_id[0..32], &request.peer_id);
|
|
}
|
|
|
|
test "UploadRequest.createWithContext includes request_id and file_hash" {
|
|
const peer_id = "context_peer";
|
|
const file_hash = [_]u8{0xAB} ** 32;
|
|
const request_id: u64 = 0xDEADBEEF12345678;
|
|
|
|
const request = UploadRequest.createWithContext(
|
|
5,
|
|
2048,
|
|
4096,
|
|
peer_id,
|
|
.urgent,
|
|
request_id,
|
|
file_hash,
|
|
);
|
|
|
|
try testing.expectEqual(@as(u32, 5), request.piece_index);
|
|
try testing.expectEqual(@as(u64, 2048), request.offset);
|
|
try testing.expectEqual(@as(u32, 4096), request.length);
|
|
try testing.expectEqual(UploadRequest.UploadPriority.urgent, request.priority);
|
|
try testing.expectEqual(request_id, request.request_id);
|
|
try testing.expectEqualSlices(u8, &file_hash, &request.file_hash);
|
|
}
|
|
|
|
test "UploadRequest.isExpired returns true for old requests" {
|
|
var request = UploadRequest.create(0, 0, 100, "peer", .normal);
|
|
|
|
// Just created - not expired with reasonable timeout
|
|
try testing.expect(!request.isExpired(60));
|
|
|
|
// Note: isExpired(0) returns false for just-created requests because
|
|
// (timestamp - requested_at) = 0, and 0 > 0 is false
|
|
|
|
// Set old timestamp to test expiration
|
|
request.requested_at = std.time.timestamp() - 100;
|
|
try testing.expect(request.isExpired(50)); // 50s timeout, 100s ago
|
|
try testing.expect(!request.isExpired(150)); // 150s timeout, 100s ago
|
|
|
|
// Test with negative timeout (always expired)
|
|
try testing.expect(request.isExpired(-1));
|
|
}
|
|
|
|
test "UploadRequest.getScore factors in priority" {
|
|
const low_priority = UploadRequest.create(0, 0, 100, "peer", .low);
|
|
const normal_priority = UploadRequest.create(0, 0, 100, "peer", .normal);
|
|
const high_priority = UploadRequest.create(0, 0, 100, "peer", .high);
|
|
const urgent_priority = UploadRequest.create(0, 0, 100, "peer", .urgent);
|
|
|
|
// Higher priority should give higher base score
|
|
try testing.expect(normal_priority.getScore() > low_priority.getScore());
|
|
try testing.expect(high_priority.getScore() > normal_priority.getScore());
|
|
try testing.expect(urgent_priority.getScore() > high_priority.getScore());
|
|
}
|
|
|
|
test "UploadRequest.getScore includes time waited" {
|
|
var request = UploadRequest.create(0, 0, 100, "peer", .normal);
|
|
const initial_score = request.getScore();
|
|
|
|
// Simulate waiting by setting old timestamp
|
|
request.requested_at = std.time.timestamp() - 10;
|
|
const later_score = request.getScore();
|
|
|
|
// Older requests should have higher score (time waited boost)
|
|
try testing.expect(later_score > initial_score);
|
|
}
|
|
|
|
test "UploadRequest priority enum values" {
|
|
try testing.expectEqual(@as(u8, 0), @intFromEnum(UploadRequest.UploadPriority.low));
|
|
try testing.expectEqual(@as(u8, 1), @intFromEnum(UploadRequest.UploadPriority.normal));
|
|
try testing.expectEqual(@as(u8, 2), @intFromEnum(UploadRequest.UploadPriority.high));
|
|
try testing.expectEqual(@as(u8, 3), @intFromEnum(UploadRequest.UploadPriority.urgent));
|
|
}
|
|
|
|
// =============================================================================
|
|
// UploadState Tests - Atomic counters and statistics
|
|
// =============================================================================
|
|
|
|
test "UploadState.init initializes all counters to zero" {
|
|
const max_bw: u64 = 1024 * 1024;
|
|
const state = UploadState.init(max_bw);
|
|
|
|
try testing.expectEqual(@as(u64, 0), state.total_uploaded.load(.monotonic));
|
|
try testing.expectEqual(@as(u32, 0), state.active_uploads.load(.monotonic));
|
|
try testing.expectEqual(@as(u32, 0), state.completed_uploads.load(.monotonic));
|
|
try testing.expectEqual(@as(u32, 0), state.failed_uploads.load(.monotonic));
|
|
try testing.expectEqual(@as(u32, 0), state.cancelled_count.load(.monotonic));
|
|
try testing.expectEqual(@as(u64, 0), state.upload_bandwidth.load(.monotonic));
|
|
try testing.expectEqual(max_bw, state.max_bandwidth);
|
|
}
|
|
|
|
test "UploadState.addUploadedBytes increments counters atomically" {
|
|
var state = UploadState.init(1024 * 1024);
|
|
|
|
state.addUploadedBytes(100);
|
|
try testing.expectEqual(@as(u64, 100), state.total_uploaded.load(.monotonic));
|
|
try testing.expectEqual(@as(u64, 100), state.upload_bandwidth.load(.monotonic));
|
|
|
|
state.addUploadedBytes(200);
|
|
try testing.expectEqual(@as(u64, 300), state.total_uploaded.load(.monotonic));
|
|
try testing.expectEqual(@as(u64, 300), state.upload_bandwidth.load(.monotonic));
|
|
}
|
|
|
|
test "UploadState.startUpload and completeUpload track lifecycle" {
|
|
var state = UploadState.init(1024 * 1024);
|
|
|
|
state.startUpload();
|
|
try testing.expectEqual(@as(u32, 1), state.active_uploads.load(.monotonic));
|
|
try testing.expectEqual(@as(u32, 0), state.completed_uploads.load(.monotonic));
|
|
|
|
state.startUpload();
|
|
try testing.expectEqual(@as(u32, 2), state.active_uploads.load(.monotonic));
|
|
|
|
state.completeUpload();
|
|
try testing.expectEqual(@as(u32, 1), state.active_uploads.load(.monotonic));
|
|
try testing.expectEqual(@as(u32, 1), state.completed_uploads.load(.monotonic));
|
|
}
|
|
|
|
test "UploadState.failUpload tracks failures" {
|
|
var state = UploadState.init(1024 * 1024);
|
|
|
|
state.startUpload();
|
|
state.startUpload();
|
|
try testing.expectEqual(@as(u32, 2), state.active_uploads.load(.monotonic));
|
|
|
|
state.failUpload();
|
|
try testing.expectEqual(@as(u32, 1), state.active_uploads.load(.monotonic));
|
|
try testing.expectEqual(@as(u32, 1), state.failed_uploads.load(.monotonic));
|
|
}
|
|
|
|
test "UploadState.resetBandwidth clears bandwidth counter" {
|
|
var state = UploadState.init(1024 * 1024);
|
|
|
|
state.addUploadedBytes(5000);
|
|
try testing.expectEqual(@as(u64, 5000), state.upload_bandwidth.load(.monotonic));
|
|
|
|
state.resetBandwidth();
|
|
try testing.expectEqual(@as(u64, 0), state.upload_bandwidth.load(.monotonic));
|
|
// total_uploaded should remain unchanged
|
|
try testing.expectEqual(@as(u64, 5000), state.total_uploaded.load(.monotonic));
|
|
}
|
|
|
|
test "UploadState.getCurrentBandwidth returns current usage" {
|
|
var state = UploadState.init(1024 * 1024);
|
|
|
|
try testing.expectEqual(@as(u64, 0), state.getCurrentBandwidth());
|
|
|
|
state.addUploadedBytes(12345);
|
|
try testing.expectEqual(@as(u64, 12345), state.getCurrentBandwidth());
|
|
}
|
|
|
|
test "UploadState.getBandwidthUtilization calculates percentage" {
|
|
var state = UploadState.init(1000); // 1000 bytes max
|
|
|
|
try testing.expectEqual(@as(f32, 0.0), state.getBandwidthUtilization());
|
|
|
|
state.addUploadedBytes(500);
|
|
try testing.expectApproxEqAbs(@as(f32, 0.5), state.getBandwidthUtilization(), 0.01);
|
|
|
|
state.addUploadedBytes(500);
|
|
try testing.expectApproxEqAbs(@as(f32, 1.0), state.getBandwidthUtilization(), 0.01);
|
|
}
|
|
|
|
test "UploadState.getBandwidthUtilization handles zero max_bandwidth" {
|
|
var state = UploadState.init(0);
|
|
state.addUploadedBytes(1000);
|
|
|
|
// Should return 0 to avoid division by zero
|
|
try testing.expectEqual(@as(f32, 0.0), state.getBandwidthUtilization());
|
|
}
|
|
|
|
test "UploadState.isBandwidthExceeded checks limit" {
|
|
var state = UploadState.init(1000);
|
|
|
|
try testing.expect(!state.isBandwidthExceeded());
|
|
|
|
state.addUploadedBytes(999);
|
|
try testing.expect(!state.isBandwidthExceeded());
|
|
|
|
state.addUploadedBytes(2); // Now at 1001
|
|
try testing.expect(state.isBandwidthExceeded());
|
|
}
|
|
|
|
test "UploadState.getUploadSpeed returns zero initially" {
|
|
var state = UploadState.init(1024 * 1024);
|
|
// Speed should be ~0 when just initialized (no time elapsed or data)
|
|
const speed = state.getUploadSpeed();
|
|
try testing.expect(speed >= 0.0);
|
|
}
|
|
|
|
test "UploadState.getStats returns complete statistics" {
|
|
var state = UploadState.init(1024 * 1024);
|
|
|
|
state.addUploadedBytes(5000);
|
|
state.startUpload();
|
|
state.startUpload();
|
|
state.completeUpload();
|
|
|
|
const stats = state.getStats();
|
|
try testing.expectEqual(@as(u64, 5000), stats.total_uploaded);
|
|
try testing.expectEqual(@as(u32, 1), stats.active_uploads);
|
|
try testing.expectEqual(@as(u32, 1), stats.completed_uploads);
|
|
try testing.expectEqual(@as(u32, 0), stats.failed_uploads);
|
|
}
|
|
|
|
// =============================================================================
|
|
// BandwidthLimiter Tests - Atomic operations and rate limiting
|
|
// =============================================================================
|
|
|
|
test "BandwidthLimiter.init creates limiter with correct config" {
|
|
const allocator = testing.allocator;
|
|
var limiter = BandwidthLimiter.init(10000, 1, allocator);
|
|
|
|
try testing.expectEqual(@as(u64, 10000), limiter.getMaxBandwidth());
|
|
try testing.expectEqual(@as(u64, 10000), limiter.getRemainingBandwidth());
|
|
}
|
|
|
|
test "BandwidthLimiter.canSend checks available bandwidth" {
|
|
const allocator = testing.allocator;
|
|
var limiter = BandwidthLimiter.init(1000, 1, allocator);
|
|
|
|
try testing.expect(limiter.canSend(500));
|
|
try testing.expect(limiter.canSend(1000));
|
|
try testing.expect(!limiter.canSend(1001));
|
|
}
|
|
|
|
test "BandwidthLimiter.tryConsume atomically checks and consumes" {
|
|
const allocator = testing.allocator;
|
|
var limiter = BandwidthLimiter.init(1000, 1, allocator);
|
|
|
|
// First consumption should succeed
|
|
try testing.expect(limiter.tryConsume(400));
|
|
try testing.expectEqual(@as(u64, 600), limiter.getRemainingBandwidth());
|
|
|
|
// Second consumption should succeed
|
|
try testing.expect(limiter.tryConsume(400));
|
|
try testing.expectEqual(@as(u64, 200), limiter.getRemainingBandwidth());
|
|
|
|
// This should fail - would exceed limit
|
|
try testing.expect(!limiter.tryConsume(300));
|
|
try testing.expectEqual(@as(u64, 200), limiter.getRemainingBandwidth());
|
|
|
|
// Exact remaining should succeed
|
|
try testing.expect(limiter.tryConsume(200));
|
|
try testing.expectEqual(@as(u64, 0), limiter.getRemainingBandwidth());
|
|
}
|
|
|
|
test "BandwidthLimiter.tryConsume allows unlimited when max is 0" {
|
|
const allocator = testing.allocator;
|
|
var limiter = BandwidthLimiter.init(0, 1, allocator); // 0 = unlimited
|
|
|
|
// Should always succeed with unlimited bandwidth
|
|
try testing.expect(limiter.tryConsume(1000000));
|
|
try testing.expect(limiter.tryConsume(999999999));
|
|
}
|
|
|
|
test "BandwidthLimiter.consumeBandwidth adds to usage" {
|
|
const allocator = testing.allocator;
|
|
var limiter = BandwidthLimiter.init(1000, 1, allocator);
|
|
|
|
limiter.consumeBandwidth(300);
|
|
try testing.expectEqual(@as(u64, 700), limiter.getRemainingBandwidth());
|
|
|
|
limiter.consumeBandwidth(500);
|
|
try testing.expectEqual(@as(u64, 200), limiter.getRemainingBandwidth());
|
|
}
|
|
|
|
test "BandwidthLimiter.getRemainingBandwidth clamps to zero" {
|
|
const allocator = testing.allocator;
|
|
var limiter = BandwidthLimiter.init(1000, 1, allocator);
|
|
|
|
// Over-consume (simulating race condition or manual consumption)
|
|
limiter.consumeBandwidth(1500);
|
|
|
|
// Should return 0, not underflow
|
|
try testing.expectEqual(@as(u64, 0), limiter.getRemainingBandwidth());
|
|
}
|
|
|
|
test "BandwidthLimiter.setMaxBandwidth updates limit dynamically" {
|
|
const allocator = testing.allocator;
|
|
var limiter = BandwidthLimiter.init(1000, 1, allocator);
|
|
|
|
try testing.expectEqual(@as(u64, 1000), limiter.getMaxBandwidth());
|
|
|
|
limiter.setMaxBandwidth(5000);
|
|
try testing.expectEqual(@as(u64, 5000), limiter.getMaxBandwidth());
|
|
|
|
limiter.setMaxBandwidth(500);
|
|
try testing.expectEqual(@as(u64, 500), limiter.getMaxBandwidth());
|
|
}
|
|
|
|
test "BandwidthLimiter.isLimitExceeded detects over-consumption" {
|
|
const allocator = testing.allocator;
|
|
var limiter = BandwidthLimiter.init(1000, 1, allocator);
|
|
|
|
try testing.expect(!limiter.isLimitExceeded());
|
|
|
|
limiter.consumeBandwidth(1000);
|
|
try testing.expect(!limiter.isLimitExceeded());
|
|
|
|
limiter.consumeBandwidth(1);
|
|
try testing.expect(limiter.isLimitExceeded());
|
|
}
|
|
|
|
test "BandwidthLimiter.getUtilization calculates percentage" {
|
|
const allocator = testing.allocator;
|
|
var limiter = BandwidthLimiter.init(1000, 1, allocator);
|
|
|
|
try testing.expectApproxEqAbs(@as(f32, 0.0), limiter.getUtilization(), 0.01);
|
|
|
|
limiter.consumeBandwidth(250);
|
|
try testing.expectApproxEqAbs(@as(f32, 0.25), limiter.getUtilization(), 0.01);
|
|
|
|
limiter.consumeBandwidth(750);
|
|
try testing.expectApproxEqAbs(@as(f32, 1.0), limiter.getUtilization(), 0.01);
|
|
}
|
|
|
|
test "BandwidthLimiter.getUtilization handles zero max_bandwidth" {
|
|
const allocator = testing.allocator;
|
|
var limiter = BandwidthLimiter.init(0, 1, allocator);
|
|
|
|
limiter.consumeBandwidth(1000);
|
|
try testing.expectEqual(@as(f32, 0.0), limiter.getUtilization());
|
|
}
|
|
|
|
// =============================================================================
|
|
// UploadManager Tests
|
|
// =============================================================================
|
|
|
|
test "UploadManager.init creates manager with correct state" {
|
|
const allocator = testing.allocator;
|
|
var manager = try UploadManager.init(1024 * 1024, 1024, allocator);
|
|
defer manager.deinit();
|
|
|
|
try testing.expectEqual(@as(?[]const u8, null), manager.file_path);
|
|
try testing.expectEqual(@as(u64, 0), manager.file_size);
|
|
try testing.expectEqual(@as(?files.filesystem.File, null), manager.cached_file);
|
|
}
|
|
|
|
test "UploadManager.addAvailablePiece and removeAvailablePiece" {
|
|
const allocator = testing.allocator;
|
|
var manager = try UploadManager.init(1024 * 1024, 1024, allocator);
|
|
defer manager.deinit();
|
|
|
|
const hash = [_]u8{0x12} ** 32;
|
|
|
|
// Add piece
|
|
try manager.addAvailablePiece(5, hash);
|
|
try testing.expectEqual(@as(usize, 1), manager.available_pieces.count());
|
|
|
|
// Add another piece
|
|
try manager.addAvailablePiece(10, hash);
|
|
try testing.expectEqual(@as(usize, 2), manager.available_pieces.count());
|
|
|
|
// Remove piece
|
|
manager.removeAvailablePiece(5);
|
|
try testing.expectEqual(@as(usize, 1), manager.available_pieces.count());
|
|
|
|
// Remove non-existent piece (should be no-op)
|
|
manager.removeAvailablePiece(999);
|
|
try testing.expectEqual(@as(usize, 1), manager.available_pieces.count());
|
|
}
|
|
|
|
test "UploadManager.handleUploadRequest rejects unavailable pieces" {
|
|
const allocator = testing.allocator;
|
|
var manager = try UploadManager.init(1024 * 1024, 1024, allocator);
|
|
defer manager.deinit();
|
|
|
|
// Request for piece that doesn't exist
|
|
const accepted = try manager.handleUploadRequest(0, 0, 512, "peer1", .normal);
|
|
try testing.expect(!accepted);
|
|
try testing.expectEqual(@as(usize, 0), manager.pending_requests.items.len);
|
|
}
|
|
|
|
test "UploadManager.handleUploadRequest accepts available pieces" {
|
|
const allocator = testing.allocator;
|
|
var manager = try UploadManager.init(1024 * 1024, 1024, allocator);
|
|
defer manager.deinit();
|
|
|
|
// Add available piece
|
|
const hash = [_]u8{0} ** 32;
|
|
try manager.addAvailablePiece(0, hash);
|
|
|
|
// Request should be accepted
|
|
const accepted = try manager.handleUploadRequest(0, 0, 512, "peer1", .normal);
|
|
try testing.expect(accepted);
|
|
try testing.expectEqual(@as(usize, 1), manager.pending_requests.items.len);
|
|
}
|
|
|
|
test "UploadManager.handleUploadRequest respects peer limits" {
|
|
const allocator = testing.allocator;
|
|
var manager = try UploadManager.init(1024 * 1024, 1024, allocator);
|
|
defer manager.deinit();
|
|
|
|
// Add piece
|
|
const hash = [_]u8{0} ** 32;
|
|
try manager.addAvailablePiece(0, hash);
|
|
|
|
// Set peer limit to 0 concurrent uploads
|
|
try manager.setPeerLimit("limited_peer", 0, 1024 * 1024);
|
|
|
|
// Request should be rejected due to peer limit
|
|
const accepted = try manager.handleUploadRequest(0, 0, 512, "limited_peer", .normal);
|
|
try testing.expect(!accepted);
|
|
}
|
|
|
|
test "UploadManager.processRequests moves requests to active" {
|
|
const allocator = testing.allocator;
|
|
var manager = try UploadManager.init(1024 * 1024, 1024, allocator);
|
|
defer manager.deinit();
|
|
|
|
// Add piece and request
|
|
const hash = [_]u8{0} ** 32;
|
|
try manager.addAvailablePiece(0, hash);
|
|
_ = try manager.handleUploadRequest(0, 0, 512, "peer1", .normal);
|
|
|
|
try testing.expectEqual(@as(usize, 1), manager.pending_requests.items.len);
|
|
try testing.expectEqual(@as(usize, 0), manager.active_uploads.count());
|
|
|
|
// Process requests
|
|
try manager.processRequests(10);
|
|
|
|
try testing.expectEqual(@as(usize, 0), manager.pending_requests.items.len);
|
|
try testing.expectEqual(@as(usize, 1), manager.active_uploads.count());
|
|
}
|
|
|
|
test "UploadManager.cancelUpload removes active upload" {
|
|
const allocator = testing.allocator;
|
|
var manager = try UploadManager.init(1024 * 1024, 1024, allocator);
|
|
defer manager.deinit();
|
|
|
|
// Setup: add piece, request, and process
|
|
const hash = [_]u8{0} ** 32;
|
|
try manager.addAvailablePiece(0, hash);
|
|
_ = try manager.handleUploadRequest(0, 0, 512, "peer1", .normal);
|
|
try manager.processRequests(10);
|
|
|
|
try testing.expectEqual(@as(usize, 1), manager.active_uploads.count());
|
|
|
|
// Cancel the upload
|
|
try manager.cancelUpload(0, "test cancellation");
|
|
|
|
try testing.expectEqual(@as(usize, 0), manager.active_uploads.count());
|
|
// Cancelled count should be incremented
|
|
try testing.expectEqual(@as(u32, 1), manager.state.cancelled_count.load(.monotonic));
|
|
}
|
|
|
|
test "UploadManager.cancelUpload handles non-existent upload gracefully" {
|
|
const allocator = testing.allocator;
|
|
var manager = try UploadManager.init(1024 * 1024, 1024, allocator);
|
|
defer manager.deinit();
|
|
|
|
// Cancel non-existent upload - should not error
|
|
try manager.cancelUpload(999, "non-existent piece");
|
|
}
|
|
|
|
test "UploadManager.setPeerLimit configures per-peer limits" {
|
|
const allocator = testing.allocator;
|
|
var manager = try UploadManager.init(1024 * 1024, 1024, allocator);
|
|
defer manager.deinit();
|
|
|
|
try manager.setPeerLimit("peer_A", 5, 500000);
|
|
try manager.setPeerLimit("peer_B", 10, 1000000);
|
|
|
|
try testing.expectEqual(@as(usize, 2), manager.peer_limits.count());
|
|
}
|
|
|
|
test "UploadManager.getStats returns comprehensive statistics" {
|
|
const allocator = testing.allocator;
|
|
var manager = try UploadManager.init(1024 * 1024, 1024, allocator);
|
|
defer manager.deinit();
|
|
|
|
// Add multiple pieces
|
|
const hash = [_]u8{0} ** 32;
|
|
try manager.addAvailablePiece(0, hash);
|
|
try manager.addAvailablePiece(1, hash);
|
|
try manager.addAvailablePiece(2, hash);
|
|
|
|
// Add request
|
|
_ = try manager.handleUploadRequest(0, 0, 512, "peer1", .normal);
|
|
|
|
const stats = manager.getStats();
|
|
try testing.expectEqual(@as(usize, 1), stats.pending_requests);
|
|
try testing.expectEqual(@as(usize, 0), stats.active_uploads);
|
|
try testing.expectEqual(@as(usize, 3), stats.available_pieces);
|
|
}
|
|
|
|
test "UploadManager.canAcceptUploads checks capacity" {
|
|
const allocator = testing.allocator;
|
|
var manager = try UploadManager.init(1024 * 1024, 1024, allocator);
|
|
defer manager.deinit();
|
|
|
|
// Should accept uploads initially
|
|
try testing.expect(manager.canAcceptUploads());
|
|
}
|
|
|
|
test "UploadManager.getPieceStats returns piece information" {
|
|
const allocator = testing.allocator;
|
|
var manager = try UploadManager.init(1024 * 1024, 1024, allocator);
|
|
defer manager.deinit();
|
|
|
|
// Non-existent piece
|
|
try testing.expectEqual(@as(?PieceUploadStats, null), manager.getPieceStats(0));
|
|
|
|
// Add piece
|
|
const hash = [_]u8{0xAB} ** 32;
|
|
try manager.addAvailablePiece(5, hash);
|
|
|
|
// Should return stats now
|
|
const stats = manager.getPieceStats(5);
|
|
try testing.expect(stats != null);
|
|
try testing.expectEqual(@as(u32, 5), stats.?.index);
|
|
try testing.expect(stats.?.is_available);
|
|
try testing.expectEqual(@as(u32, 0), stats.?.upload_count);
|
|
}
|
|
|
|
test "UploadManager.resetBandwidth resets both state and limiter" {
|
|
const allocator = testing.allocator;
|
|
var manager = try UploadManager.init(1024 * 1024, 1024, allocator);
|
|
defer manager.deinit();
|
|
|
|
// Consume some bandwidth
|
|
manager.state.addUploadedBytes(5000);
|
|
|
|
// Reset
|
|
manager.resetBandwidth();
|
|
|
|
try testing.expectEqual(@as(u64, 0), manager.state.upload_bandwidth.load(.monotonic));
|
|
}
|
|
|
|
test "UploadManager.setBandwidthLimit updates both state and limiter" {
|
|
const allocator = testing.allocator;
|
|
var manager = try UploadManager.init(1024 * 1024, 1024, allocator);
|
|
defer manager.deinit();
|
|
|
|
manager.setBandwidthLimit(5000);
|
|
|
|
try testing.expectEqual(@as(u64, 5000), manager.state.max_bandwidth);
|
|
try testing.expectEqual(@as(u64, 5000), manager.limiter.getMaxBandwidth());
|
|
}
|
|
|
|
test "UploadManager.isUsingMmap returns false without file" {
|
|
const allocator = testing.allocator;
|
|
var manager = try UploadManager.init(1024 * 1024, 1024, allocator);
|
|
defer manager.deinit();
|
|
|
|
try testing.expect(!manager.isUsingMmap());
|
|
}
|
|
|
|
test "UploadManager.setNetworkSender configures callback" {
|
|
const allocator = testing.allocator;
|
|
var manager = try UploadManager.init(1024 * 1024, 1024, allocator);
|
|
defer manager.deinit();
|
|
|
|
const TestContext = struct {
|
|
value: u32,
|
|
};
|
|
|
|
var ctx = TestContext{ .value = 42 };
|
|
|
|
const mockSender = struct {
|
|
fn send(_: []const u8, _: []const u8, _: ?*anyopaque) Error!void {}
|
|
}.send;
|
|
|
|
manager.setNetworkSender(mockSender, &ctx);
|
|
|
|
try testing.expect(manager.network_sender != null);
|
|
try testing.expect(manager.network_sender_context != null);
|
|
}
|
|
|
|
test "UploadManager.MAX_PENDING_REQUESTS constant" {
|
|
try testing.expectEqual(@as(usize, 10000), UploadManager.MAX_PENDING_REQUESTS);
|
|
}
|
|
|
|
// =============================================================================
|
|
// UploadQueue Tests
|
|
// =============================================================================
|
|
|
|
test "UploadQueue.init creates empty queue" {
|
|
const allocator = testing.allocator;
|
|
var queue = UploadQueue.init(allocator);
|
|
defer queue.deinit();
|
|
|
|
try testing.expectEqual(@as(usize, 0), queue.uploads.items.len);
|
|
}
|
|
|
|
test "UploadQueue.addUpload creates and returns manager" {
|
|
const allocator = testing.allocator;
|
|
var queue = UploadQueue.init(allocator);
|
|
defer queue.deinit();
|
|
|
|
const manager1 = try queue.addUpload(1024 * 1024, 1024);
|
|
try testing.expectEqual(@as(usize, 1), queue.uploads.items.len);
|
|
try testing.expectEqual(@as(u64, 1024 * 1024), manager1.state.max_bandwidth);
|
|
|
|
const manager2 = try queue.addUpload(2048 * 1024, 2048);
|
|
try testing.expectEqual(@as(usize, 2), queue.uploads.items.len);
|
|
try testing.expectEqual(@as(u64, 2048 * 1024), manager2.state.max_bandwidth);
|
|
}
|
|
|
|
test "UploadQueue.processAll processes all managers" {
|
|
const allocator = testing.allocator;
|
|
var queue = UploadQueue.init(allocator);
|
|
defer queue.deinit();
|
|
|
|
// Add all managers first before taking any pointers
|
|
// (to avoid use-after-free from ArrayList reallocation)
|
|
_ = try queue.addUpload(1024 * 1024, 1024);
|
|
_ = try queue.addUpload(1024 * 1024, 1024);
|
|
|
|
// Now access managers via the stable items slice
|
|
const hash = [_]u8{0} ** 32;
|
|
try queue.uploads.items[0].addAvailablePiece(0, hash);
|
|
try queue.uploads.items[1].addAvailablePiece(0, hash);
|
|
|
|
_ = try queue.uploads.items[0].handleUploadRequest(0, 0, 512, "peer1", .normal);
|
|
_ = try queue.uploads.items[1].handleUploadRequest(0, 0, 512, "peer2", .normal);
|
|
|
|
// Process all
|
|
try queue.processAll(10);
|
|
|
|
// Both should have moved requests to active
|
|
try testing.expectEqual(@as(usize, 1), queue.uploads.items[0].active_uploads.count());
|
|
try testing.expectEqual(@as(usize, 1), queue.uploads.items[1].active_uploads.count());
|
|
}
|
|
|
|
// Note: getCombinedStats tests are covered by inline tests in upload.zig
|
|
// Due to Zig module import const propagation differences, getCombinedStats
|
|
// cannot be called from external tests (the internal ArrayList iteration
|
|
// produces const references when compiled as a module)
|
|
|
|
// =============================================================================
|
|
// CombinedUploadStats Tests
|
|
// =============================================================================
|
|
|
|
test "CombinedUploadStats.getAverageSpeed calculates bytes per second" {
|
|
const now = std.time.timestamp();
|
|
const stats = CombinedUploadStats{
|
|
.total_uploaded = 10000,
|
|
.active_uploads = 1,
|
|
.completed_uploads = 5,
|
|
.available_pieces = 10,
|
|
.max_bandwidth = 1000000,
|
|
.start_time = now - 10, // 10 seconds ago
|
|
};
|
|
|
|
const speed = stats.getAverageSpeed();
|
|
// 10000 bytes / 10 seconds = 1000 bytes/second
|
|
try testing.expectApproxEqAbs(@as(f32, 1000.0), speed, 200.0); // Allow some timing variance
|
|
}
|
|
|
|
test "CombinedUploadStats.getAverageSpeed handles zero elapsed time" {
|
|
const now = std.time.timestamp();
|
|
const stats = CombinedUploadStats{
|
|
.total_uploaded = 10000,
|
|
.active_uploads = 1,
|
|
.completed_uploads = 5,
|
|
.available_pieces = 10,
|
|
.max_bandwidth = 1000000,
|
|
.start_time = now, // Just started
|
|
};
|
|
|
|
const speed = stats.getAverageSpeed();
|
|
// Should return 0 or small value to avoid division issues
|
|
try testing.expect(speed >= 0.0);
|
|
}
|
|
|
|
test "CombinedUploadStats.getElapsedTime returns seconds since start" {
|
|
const now = std.time.timestamp();
|
|
const stats = CombinedUploadStats{
|
|
.total_uploaded = 0,
|
|
.active_uploads = 0,
|
|
.completed_uploads = 0,
|
|
.available_pieces = 0,
|
|
.max_bandwidth = 0,
|
|
.start_time = now - 100,
|
|
};
|
|
|
|
const elapsed = stats.getElapsedTime();
|
|
// Should be approximately 100 seconds
|
|
try testing.expect(elapsed >= 99 and elapsed <= 101);
|
|
}
|
|
|
|
// =============================================================================
|
|
// Supporting Type Tests
|
|
// =============================================================================
|
|
|
|
test "AvailablePiece structure fields" {
|
|
const hash = [_]u8{0xFF} ** 32;
|
|
const piece = AvailablePiece{
|
|
.index = 42,
|
|
.hash = hash,
|
|
.available_at = 1234567890,
|
|
.upload_count = 5,
|
|
.is_verified = true,
|
|
};
|
|
|
|
try testing.expectEqual(@as(u32, 42), piece.index);
|
|
try testing.expectEqualSlices(u8, &hash, &piece.hash);
|
|
try testing.expectEqual(@as(i64, 1234567890), piece.available_at);
|
|
try testing.expectEqual(@as(u32, 5), piece.upload_count);
|
|
try testing.expect(piece.is_verified);
|
|
}
|
|
|
|
test "ActiveUpload.UploadStatus enum values" {
|
|
try testing.expectEqual(@as(u8, 1), @intFromEnum(ActiveUpload.UploadStatus.uploading));
|
|
try testing.expectEqual(@as(u8, 2), @intFromEnum(ActiveUpload.UploadStatus.throttled));
|
|
try testing.expectEqual(@as(u8, 3), @intFromEnum(ActiveUpload.UploadStatus.completed));
|
|
try testing.expectEqual(@as(u8, 4), @intFromEnum(ActiveUpload.UploadStatus.cancelled));
|
|
}
|
|
|
|
test "PeerLimit structure fields" {
|
|
const limit = PeerLimit{
|
|
.max_concurrent = 10,
|
|
.max_bandwidth = 1024 * 1024,
|
|
.current_bandwidth = 512 * 1024,
|
|
.active_uploads = 3,
|
|
};
|
|
|
|
try testing.expectEqual(@as(u32, 10), limit.max_concurrent);
|
|
try testing.expectEqual(@as(u64, 1024 * 1024), limit.max_bandwidth);
|
|
try testing.expectEqual(@as(u64, 512 * 1024), limit.current_bandwidth);
|
|
try testing.expectEqual(@as(u32, 3), limit.active_uploads);
|
|
}
|
|
|
|
test "UploadStats structure fields" {
|
|
const stats = UploadStats{
|
|
.total_uploaded = 100000,
|
|
.active_uploads = 5,
|
|
.completed_uploads = 20,
|
|
.failed_uploads = 2,
|
|
.upload_speed = 5000.5,
|
|
.bandwidth_utilization = 0.75,
|
|
};
|
|
|
|
try testing.expectEqual(@as(u64, 100000), stats.total_uploaded);
|
|
try testing.expectEqual(@as(u32, 5), stats.active_uploads);
|
|
try testing.expectEqual(@as(u32, 20), stats.completed_uploads);
|
|
try testing.expectEqual(@as(u32, 2), stats.failed_uploads);
|
|
try testing.expectApproxEqAbs(@as(f32, 5000.5), stats.upload_speed, 0.1);
|
|
try testing.expectApproxEqAbs(@as(f32, 0.75), stats.bandwidth_utilization, 0.01);
|
|
}
|
|
|
|
test "UploadManagerStats structure fields" {
|
|
const inner_stats = UploadStats{
|
|
.total_uploaded = 50000,
|
|
.active_uploads = 3,
|
|
.completed_uploads = 10,
|
|
.failed_uploads = 1,
|
|
.upload_speed = 2500.0,
|
|
.bandwidth_utilization = 0.5,
|
|
};
|
|
|
|
const manager_stats = UploadManagerStats{
|
|
.state = inner_stats,
|
|
.pending_requests = 5,
|
|
.active_uploads = 3,
|
|
.available_pieces = 100,
|
|
.bandwidth_utilization = 0.5,
|
|
};
|
|
|
|
try testing.expectEqual(@as(usize, 5), manager_stats.pending_requests);
|
|
try testing.expectEqual(@as(usize, 3), manager_stats.active_uploads);
|
|
try testing.expectEqual(@as(usize, 100), manager_stats.available_pieces);
|
|
try testing.expectEqual(@as(u64, 50000), manager_stats.state.total_uploaded);
|
|
}
|
|
|
|
test "PieceUploadStats structure fields" {
|
|
const stats = PieceUploadStats{
|
|
.index = 42,
|
|
.upload_count = 7,
|
|
.is_available = true,
|
|
.available_at = 1234567890,
|
|
};
|
|
|
|
try testing.expectEqual(@as(u32, 42), stats.index);
|
|
try testing.expectEqual(@as(u32, 7), stats.upload_count);
|
|
try testing.expect(stats.is_available);
|
|
try testing.expectEqual(@as(i64, 1234567890), stats.available_at);
|
|
}
|