Files
zigp2p/tests/files/test_piece_pipeline.zig
2026-02-06 21:03:59 -03:00

545 lines
16 KiB
Zig

//! Comprehensive tests for piece_pipeline.zig
//!
//! Tests cover pipeline initialization, task queuing, worker threads,
//! callback processing, statistics, and edge cases.
const std = @import("std");
const testing = std.testing;
const Thread = std.Thread;
const files = @import("files");
const core = @import("core");
const Error = core.errors.Error;
const piece_pipeline = files.piece_pipeline;
const PiecePipeline = piece_pipeline.PiecePipeline;
const PiecePipelineConfig = piece_pipeline.PiecePipelineConfig;
const PipelineCallbacks = piece_pipeline.PipelineCallbacks;
const PipelineStats = piece_pipeline.PipelineStats;
const PieceTask = piece_pipeline.PieceTask;
// ============================================================================
// Configuration Tests
// ============================================================================
test "PiecePipelineConfig: default values" {
const config = PiecePipelineConfig{};
try testing.expectEqual(@as(u32, 0), config.num_workers);
try testing.expectEqual(@as(usize, 2048), config.max_queue_size);
try testing.expect(config.prioritize_small_pieces);
}
test "PiecePipelineConfig: custom values" {
const config = PiecePipelineConfig{
.num_workers = 4,
.max_queue_size = 512,
.prioritize_small_pieces = false,
};
try testing.expectEqual(@as(u32, 4), config.num_workers);
try testing.expectEqual(@as(usize, 512), config.max_queue_size);
try testing.expect(!config.prioritize_small_pieces);
}
// ============================================================================
// Pipeline Initialization Tests
// ============================================================================
test "PiecePipeline: init and deinit" {
const allocator = testing.allocator;
var pipeline = PiecePipeline.init(allocator, .{
.num_workers = 2,
.max_queue_size = 100,
});
defer pipeline.deinit();
try testing.expectEqual(@as(u32, 2), pipeline.config.num_workers);
try testing.expect(pipeline.callbacks == null);
}
test "PiecePipeline: setCallbacks" {
const allocator = testing.allocator;
const DummyCallback = struct {
fn process(_: *anyopaque, _: [32]u8, _: [32]u8, _: u32, _: u32, _: []const u8) Error!void {}
};
var dummy: u32 = 0;
var pipeline = PiecePipeline.init(allocator, .{ .num_workers = 1 });
defer pipeline.deinit();
try testing.expect(pipeline.callbacks == null);
pipeline.setCallbacks(.{
.context = @ptrCast(&dummy),
.process_piece_fn = DummyCallback.process,
});
try testing.expect(pipeline.callbacks != null);
}
test "PiecePipeline: start without callbacks returns error" {
const allocator = testing.allocator;
var pipeline = PiecePipeline.init(allocator, .{ .num_workers = 1 });
defer pipeline.deinit();
// Starting without callbacks should fail
const result = pipeline.start();
try testing.expectError(Error.InvalidState, result);
}
test "PiecePipeline: start and stop" {
const allocator = testing.allocator;
const DummyCallback = struct {
fn process(_: *anyopaque, _: [32]u8, _: [32]u8, _: u32, _: u32, _: []const u8) Error!void {}
};
var dummy: u32 = 0;
var pipeline = PiecePipeline.init(allocator, .{ .num_workers = 2 });
defer pipeline.deinit();
pipeline.setCallbacks(.{
.context = @ptrCast(&dummy),
.process_piece_fn = DummyCallback.process,
});
try pipeline.start();
try testing.expectEqual(@as(usize, 2), pipeline.workers.items.len);
pipeline.stop();
try testing.expectEqual(@as(usize, 0), pipeline.workers.items.len);
}
test "PiecePipeline: stop without start is safe" {
const allocator = testing.allocator;
var pipeline = PiecePipeline.init(allocator, .{ .num_workers = 1 });
defer pipeline.deinit();
// Should not crash
pipeline.stop();
try testing.expectEqual(@as(usize, 0), pipeline.workers.items.len);
}
// ============================================================================
// Task Queuing Tests
// ============================================================================
test "PiecePipeline: queuePiece basic" {
const allocator = testing.allocator;
var processed = std.atomic.Value(u32).init(0);
const TestCallback = struct {
fn process(ctx: *anyopaque, _: [32]u8, _: [32]u8, _: u32, _: u32, _: []const u8) Error!void {
const counter: *std.atomic.Value(u32) = @ptrCast(@alignCast(ctx));
_ = counter.fetchAdd(1, .monotonic);
}
};
var pipeline = PiecePipeline.init(allocator, .{ .num_workers = 1 });
defer pipeline.deinit();
pipeline.setCallbacks(.{
.context = @ptrCast(&processed),
.process_piece_fn = TestCallback.process,
});
try pipeline.start();
const test_data = "Test piece data";
const hash = [_]u8{0xAA} ** 32;
const peer = [_]u8{0xBB} ** 32;
try pipeline.queuePiece(peer, hash, 0, 0, test_data);
try pipeline.queuePiece(peer, hash, 1, 0, test_data);
try pipeline.queuePiece(peer, hash, 2, 0, test_data);
// Wait for processing
var attempts: u32 = 0;
while (attempts < 100) : (attempts += 1) {
if (processed.load(.acquire) >= 3) break;
Thread.sleep(10 * std.time.ns_per_ms);
}
pipeline.stop();
try testing.expectEqual(@as(u32, 3), processed.load(.acquire));
}
test "PiecePipeline: getQueueDepth" {
const allocator = testing.allocator;
const SlowCallback = struct {
fn process(_: *anyopaque, _: [32]u8, _: [32]u8, _: u32, _: u32, _: []const u8) Error!void {
Thread.sleep(50 * std.time.ns_per_ms);
}
};
var dummy: u32 = 0;
var pipeline = PiecePipeline.init(allocator, .{
.num_workers = 1,
.max_queue_size = 100,
});
defer pipeline.deinit();
pipeline.setCallbacks(.{
.context = @ptrCast(&dummy),
.process_piece_fn = SlowCallback.process,
});
try testing.expectEqual(@as(usize, 0), pipeline.getQueueDepth());
// Don't start - queue will fill up
const test_data = "Test";
const hash = [_]u8{0} ** 32;
const peer = [_]u8{0} ** 32;
try pipeline.queuePiece(peer, hash, 0, 0, test_data);
try testing.expectEqual(@as(usize, 1), pipeline.getQueueDepth());
try pipeline.queuePiece(peer, hash, 1, 0, test_data);
try testing.expectEqual(@as(usize, 2), pipeline.getQueueDepth());
}
// ============================================================================
// Statistics Tests
// ============================================================================
test "PiecePipeline: getStats initial values" {
const allocator = testing.allocator;
var pipeline = PiecePipeline.init(allocator, .{ .num_workers = 1 });
defer pipeline.deinit();
const stats = pipeline.getStats();
try testing.expectEqual(@as(u64, 0), stats.tasks_queued);
try testing.expectEqual(@as(u64, 0), stats.tasks_processed);
try testing.expectEqual(@as(u64, 0), stats.tasks_failed);
try testing.expectEqual(@as(u64, 0), stats.queue_full_count);
try testing.expectEqual(@as(usize, 0), stats.current_queue_depth);
try testing.expectEqual(@as(usize, 0), stats.worker_count);
}
test "PiecePipeline: getStats reflects operations" {
const allocator = testing.allocator;
var processed = std.atomic.Value(u32).init(0);
const TestCallback = struct {
fn process(ctx: *anyopaque, _: [32]u8, _: [32]u8, _: u32, _: u32, _: []const u8) Error!void {
const counter: *std.atomic.Value(u32) = @ptrCast(@alignCast(ctx));
_ = counter.fetchAdd(1, .monotonic);
}
};
var pipeline = PiecePipeline.init(allocator, .{ .num_workers = 2 });
defer pipeline.deinit();
pipeline.setCallbacks(.{
.context = @ptrCast(&processed),
.process_piece_fn = TestCallback.process,
});
try pipeline.start();
var stats = pipeline.getStats();
try testing.expectEqual(@as(usize, 2), stats.worker_count);
const test_data = "Data";
const hash = [_]u8{0} ** 32;
const peer = [_]u8{0} ** 32;
try pipeline.queuePiece(peer, hash, 0, 0, test_data);
try pipeline.queuePiece(peer, hash, 1, 0, test_data);
// Wait for processing
var attempts: u32 = 0;
while (attempts < 100) : (attempts += 1) {
stats = pipeline.getStats();
if (stats.tasks_processed >= 2) break;
Thread.sleep(10 * std.time.ns_per_ms);
}
pipeline.stop();
stats = pipeline.getStats();
try testing.expectEqual(@as(u64, 2), stats.tasks_queued);
try testing.expectEqual(@as(u64, 2), stats.tasks_processed);
}
test "PiecePipeline: callback failure increments tasks_failed" {
const allocator = testing.allocator;
const FailingCallback = struct {
fn process(_: *anyopaque, _: [32]u8, _: [32]u8, _: u32, _: u32, _: []const u8) Error!void {
return Error.InvalidData;
}
};
var dummy: u32 = 0;
var pipeline = PiecePipeline.init(allocator, .{ .num_workers = 1 });
defer pipeline.deinit();
pipeline.setCallbacks(.{
.context = @ptrCast(&dummy),
.process_piece_fn = FailingCallback.process,
});
try pipeline.start();
const test_data = "Test";
const hash = [_]u8{0} ** 32;
const peer = [_]u8{0} ** 32;
try pipeline.queuePiece(peer, hash, 0, 0, test_data);
try pipeline.queuePiece(peer, hash, 1, 0, test_data);
// Wait for processing
var attempts: u32 = 0;
while (attempts < 100) : (attempts += 1) {
const stats = pipeline.getStats();
if (stats.tasks_failed >= 2) break;
Thread.sleep(10 * std.time.ns_per_ms);
}
pipeline.stop();
const stats = pipeline.getStats();
try testing.expectEqual(@as(u64, 2), stats.tasks_failed);
}
// ============================================================================
// PipelineStats Tests
// ============================================================================
test "PipelineStats: throughput calculation" {
var stats = PipelineStats{
.tasks_queued = 100,
.tasks_processed = 50,
.tasks_failed = 5,
.queue_full_count = 2,
.current_queue_depth = 10,
.worker_count = 4,
.avg_queue_wait_ns = 1000,
};
const throughput = stats.throughput(10.0); // 50 tasks in 10 seconds
try testing.expectApproxEqAbs(@as(f64, 5.0), throughput, 0.001);
}
test "PipelineStats: throughput with zero elapsed time" {
var stats = PipelineStats{
.tasks_queued = 100,
.tasks_processed = 50,
.tasks_failed = 0,
.queue_full_count = 0,
.current_queue_depth = 0,
.worker_count = 2,
.avg_queue_wait_ns = 0,
};
try testing.expectEqual(@as(f64, 0), stats.throughput(0));
try testing.expectEqual(@as(f64, 0), stats.throughput(-1.0));
}
// ============================================================================
// PieceTask Tests
// ============================================================================
test "PieceTask: deinit frees data" {
const allocator = testing.allocator;
const data = try allocator.alloc(u8, 64);
@memset(data, 0xAB);
var task = PieceTask{
.peer_id = [_]u8{0} ** 32,
.content_hash = [_]u8{0} ** 32,
.piece_index = 0,
.offset = 0,
.data = data,
.allocator = allocator,
.queued_at = 0,
};
// deinit should free without leak
task.deinit();
}
// ============================================================================
// PipelineCallbacks Tests
// ============================================================================
test "PipelineCallbacks: processPiece delegates to function" {
var called = false;
const TestCallback = struct {
fn process(ctx: *anyopaque, _: [32]u8, _: [32]u8, _: u32, _: u32, _: []const u8) Error!void {
const flag: *bool = @ptrCast(@alignCast(ctx));
flag.* = true;
}
};
const callbacks = PipelineCallbacks{
.context = @ptrCast(&called),
.process_piece_fn = TestCallback.process,
};
try callbacks.processPiece(
[_]u8{0} ** 32,
[_]u8{0} ** 32,
0,
0,
"test",
);
try testing.expect(called);
}
// ============================================================================
// Edge Cases
// ============================================================================
test "PiecePipeline: deinit with pending tasks cleans up" {
const allocator = testing.allocator;
const DummyCallback = struct {
fn process(_: *anyopaque, _: [32]u8, _: [32]u8, _: u32, _: u32, _: []const u8) Error!void {}
};
var dummy: u32 = 0;
var pipeline = PiecePipeline.init(allocator, .{
.num_workers = 1,
.max_queue_size = 100,
});
pipeline.setCallbacks(.{
.context = @ptrCast(&dummy),
.process_piece_fn = DummyCallback.process,
});
// Don't start - queue tasks that won't be processed
const test_data = "Pending data";
const hash = [_]u8{0} ** 32;
const peer = [_]u8{0} ** 32;
try pipeline.queuePiece(peer, hash, 0, 0, test_data);
try pipeline.queuePiece(peer, hash, 1, 0, test_data);
// deinit should clean up pending tasks without leak
pipeline.deinit();
}
test "PiecePipeline: empty data queue" {
const allocator = testing.allocator;
var processed = std.atomic.Value(u32).init(0);
const TestCallback = struct {
fn process(ctx: *anyopaque, _: [32]u8, _: [32]u8, _: u32, _: u32, data: []const u8) Error!void {
if (data.len == 0) {
const counter: *std.atomic.Value(u32) = @ptrCast(@alignCast(ctx));
_ = counter.fetchAdd(1, .monotonic);
}
}
};
var pipeline = PiecePipeline.init(allocator, .{ .num_workers = 1 });
defer pipeline.deinit();
pipeline.setCallbacks(.{
.context = @ptrCast(&processed),
.process_piece_fn = TestCallback.process,
});
try pipeline.start();
// Queue empty data
const empty_data: []const u8 = "";
const hash = [_]u8{0} ** 32;
const peer = [_]u8{0} ** 32;
try pipeline.queuePiece(peer, hash, 0, 0, empty_data);
// Wait for processing
var attempts: u32 = 0;
while (attempts < 100) : (attempts += 1) {
if (processed.load(.acquire) >= 1) break;
Thread.sleep(10 * std.time.ns_per_ms);
}
pipeline.stop();
try testing.expectEqual(@as(u32, 1), processed.load(.acquire));
}
test "PiecePipeline: multiple start stop cycles" {
const allocator = testing.allocator;
const DummyCallback = struct {
fn process(_: *anyopaque, _: [32]u8, _: [32]u8, _: u32, _: u32, _: []const u8) Error!void {}
};
var dummy: u32 = 0;
var pipeline = PiecePipeline.init(allocator, .{ .num_workers = 1 });
defer pipeline.deinit();
pipeline.setCallbacks(.{
.context = @ptrCast(&dummy),
.process_piece_fn = DummyCallback.process,
});
// Multiple cycles
try pipeline.start();
pipeline.stop();
try pipeline.start();
pipeline.stop();
try pipeline.start();
pipeline.stop();
}
test "PiecePipeline: shutdown drains queue" {
const allocator = testing.allocator;
var processed = std.atomic.Value(u32).init(0);
const TestCallback = struct {
fn process(ctx: *anyopaque, _: [32]u8, _: [32]u8, _: u32, _: u32, _: []const u8) Error!void {
const counter: *std.atomic.Value(u32) = @ptrCast(@alignCast(ctx));
_ = counter.fetchAdd(1, .monotonic);
}
};
var pipeline = PiecePipeline.init(allocator, .{ .num_workers = 1 });
defer pipeline.deinit();
pipeline.setCallbacks(.{
.context = @ptrCast(&processed),
.process_piece_fn = TestCallback.process,
});
try pipeline.start();
// Queue several tasks
const test_data = "Test";
const hash = [_]u8{0} ** 32;
const peer = [_]u8{0} ** 32;
var i: u32 = 0;
while (i < 5) : (i += 1) {
try pipeline.queuePiece(peer, hash, i, 0, test_data);
}
// Stop should drain the queue
pipeline.stop();
// All tasks should be processed
try testing.expectEqual(@as(u32, 5), processed.load(.acquire));
}