This commit is contained in:
2026-02-06 21:03:59 -03:00
commit 2b7ab5f570
267 changed files with 176026 additions and 0 deletions

621
tests/core/test_address.zig Normal file
View File

@@ -0,0 +1,621 @@
//! Tests for address handling module
const std = @import("std");
const testing = std.testing;
const mem = std.mem;
const os = std.os;
const core = @import("core");
const Address = core.address.Address;
const Ipv4Address = core.address.Ipv4Address;
const Ipv6Address = core.address.Ipv6Address;
const UnixAddress = core.address.UnixAddress;
const AddressList = core.address.AddressList;
const AddressResolver = core.address.AddressResolver;
const AddressFamily = core.address.AddressFamily;
const Error = core.errors.Error;
test "ipv4 address creation and parsing" {
// Test IPv4 address creation
const bytes = [_]u8{ 192, 168, 1, 100 };
const addr = Ipv4Address.init(bytes);
try testing.expectEqualSlices(u8, &bytes, &addr.bytes);
// Test IPv4 address from string
const addr_str = "192.168.1.100";
const parsed_addr = try Ipv4Address.fromString(addr_str);
try testing.expectEqualSlices(u8, &bytes, &parsed_addr.bytes);
// Test string representation
const str_repr = addr.toStringWithLen();
try testing.expectEqualSlices(u8, "192.168.1.100", str_repr.buf[0..str_repr.len]);
}
test "ipv4 address properties" {
// Test localhost detection
const localhost_bytes = [_]u8{ 127, 0, 0, 1 };
const localhost = Ipv4Address.init(localhost_bytes);
try testing.expect(localhost.isLocalhost());
try testing.expect(localhost.isLoopback());
// Test private network detection
const private_bytes = [_]u8{ 192, 168, 1, 100 };
const private = Ipv4Address.init(private_bytes);
try testing.expect(private.isPrivate());
// Test public address
const public_bytes = [_]u8{ 8, 8, 8, 8 };
const public = Ipv4Address.init(public_bytes);
try testing.expect(!public.isPrivate());
try testing.expect(!public.isLocalhost());
// Test multicast detection
const multicast_bytes = [_]u8{ 224, 0, 0, 1 };
const multicast = Ipv4Address.init(multicast_bytes);
try testing.expect(multicast.isMulticast());
}
test "ipv6 address creation and operations" {
// Test IPv6 address creation
var bytes: [16]u8 = [_]u8{0} ** 16;
bytes[15] = 1; // ::1 (loopback)
const addr = Ipv6Address.init(bytes);
try testing.expect(addr.isLoopback());
// Test multicast address
bytes[0] = 0xff; // Start with ff
const mcast_addr = Ipv6Address.init(bytes);
try testing.expect(mcast_addr.isMulticast());
// Test link-local address
bytes[0] = 0xfe;
bytes[1] = 0x80;
const link_local = Ipv6Address.init(bytes);
try testing.expect(link_local.isLinkLocal());
// Test unique local address
bytes[0] = 0xfc;
bytes[1] = 0x00;
const unique_local = Ipv6Address.init(bytes);
try testing.expect(unique_local.isUniqueLocal());
}
test "unix socket address" {
// Test Unix socket creation
const path = "/tmp/test.sock";
const addr = try UnixAddress.fromString(path);
try testing.expectEqualSlices(u8, path, addr.toString());
try testing.expect(addr.isAbsolute());
// Test relative path
const relative_path = "test.sock";
const relative_addr = try UnixAddress.fromString(relative_path);
try testing.expect(!relative_addr.isAbsolute());
}
test "address parsing various formats" {
// Test IPv4 with port
const ipv4_str = "192.168.1.100:8080";
const addr = try Address.parse(ipv4_str);
try testing.expect(addr.family == .ipv4);
try testing.expectEqual(@as(u16, 8080), addr.port);
try testing.expect(mem.eql(u8, &addr.data.ipv4.bytes, &.{192, 168, 1, 100}));
// Test IPv4 without port
const ipv4_no_port = "192.168.1.100";
const addr2 = try Address.parse(ipv4_no_port);
try testing.expect(addr2.family == .ipv4);
try testing.expectEqual(@as(u16, 0), addr2.port);
// Test IPv6 with port
const ipv6_str = "[2001:db8::1]:8080";
const addr3 = try Address.parse(ipv6_str);
try testing.expect(addr3.family == .ipv6);
try testing.expectEqual(@as(u16, 8080), addr3.port);
// Test IPv6 without port
const ipv6_no_port = "2001:db8::1";
const addr4 = try Address.parse(ipv6_no_port);
try testing.expect(addr4.family == .ipv6);
try testing.expectEqual(@as(u16, 0), addr4.port);
// Test Unix socket
const unix_str = "/tmp/test.sock";
const addr5 = try Address.parse(unix_str);
try testing.expect(addr5.family == .unix);
try testing.expectEqual(@as(u16, 0), addr5.port);
}
test "address validation" {
// Test valid addresses
const valid_ipv4 = try Address.parse("192.168.1.100:8080");
try testing.expect(valid_ipv4.isValid());
const valid_ipv6 = try Address.parse("[2001:db8::1]:8080");
try testing.expect(valid_ipv6.isValid());
const valid_unix = try Address.parse("/tmp/test.sock");
try testing.expect(valid_unix.isValid());
// Test address comparison
const addr1 = try Address.parse("192.168.1.100:8080");
const addr2 = try Address.parse("192.168.1.100:8080");
const addr3 = try Address.parse("192.168.1.100:9090");
try testing.expect(addr1.equals(addr2));
try testing.expect(!addr1.equals(addr3));
// Test address comparison
const cmp = addr1.compare(addr2);
try testing.expectEqual(@as(i32, 0), cmp);
const cmp2 = addr1.compare(addr3);
try testing.expect(cmp2 < 0); // port 8080 < 9090
}
test "address special properties" {
// Test loopback detection
const loopback_ipv4 = try Address.parse("127.0.0.1:8080");
try testing.expect(loopback_ipv4.isLoopback());
// Test private address detection
const private_ipv4 = try Address.parse("192.168.1.100:8080");
try testing.expect(private_ipv4.isPrivate());
const public_ipv4 = try Address.parse("8.8.8.8:8080");
try testing.expect(!public_ipv4.isPrivate());
}
test "address list operations" {
var list = AddressList.init(testing.allocator);
defer list.deinit();
const addr1 = try Address.parse("192.168.1.100:8080");
const addr2 = try Address.parse("192.168.1.101:8080");
const addr3 = try Address.parse("192.168.1.102:8080");
// Test adding addresses
try list.add(addr1);
try list.add(addr2);
try list.add(addr3);
try testing.expectEqual(@as(usize, 3), list.len());
// Test finding addresses
try testing.expect(list.find(addr1) != null);
try testing.expect(list.find(addr2) != null);
try testing.expect(list.find(addr3) != null);
// Test contains
try testing.expect(list.contains(addr1));
try testing.expect(list.contains(addr2));
// Test removal
list.remove(addr2);
try testing.expectEqual(@as(usize, 2), list.len());
try testing.expect(!list.contains(addr2));
// Test get by index
const retrieved = list.get(0).?;
try testing.expect(retrieved.equals(addr1));
// Test get by invalid index
try testing.expect(list.get(10) == null);
}
test "address list sorting and management" {
var list = AddressList.init(testing.allocator);
defer list.deinit();
// Add addresses in random order
const addr1 = try Address.parse("192.168.1.103:8080");
const addr2 = try Address.parse("192.168.1.101:8080");
const addr3 = try Address.parse("192.168.1.102:8080");
try list.add(addr1);
try list.add(addr2);
try list.add(addr3);
// Sort addresses
list.sort();
// Verify sorting (should be in order by address, then port)
const first = list.get(0).?;
const second = list.get(1).?;
const third = list.get(2).?;
try testing.expect(first.compare(second) <= 0);
try testing.expect(second.compare(third) <= 0);
// Test clearing
list.clear();
try testing.expectEqual(@as(usize, 0), list.len());
}
test "address resolver" {
var resolver = AddressResolver.init(testing.allocator);
// Test service resolution
const port = try resolver.resolveService("8080");
try testing.expectEqual(@as(u16, 8080), port);
const port2 = try resolver.resolveService("443");
try testing.expectEqual(@as(u16, 443), port2);
// Test invalid service - returns InvalidPort for non-numeric strings
try testing.expectError(Error.InvalidPort, resolver.resolveService("invalid"));
}
test "address system conversion" {
// Test IPv4 to/from system address
const addr = try Address.parse("192.168.1.100:8080");
const sock_addr = try addr.toSockAddr();
// Verify the family is IPv4 (AF_INET = 2 on most systems)
try testing.expect(sock_addr.family == std.posix.AF.INET);
const back_to_addr = try Address.fromSockAddr(sock_addr);
try testing.expect(back_to_addr.equals(addr));
// Test IPv6 conversion
const ipv6_addr = try Address.parse("[2001:db8::1]:8080");
const ipv6_sock_addr = try ipv6_addr.toSockAddr();
try testing.expect(ipv6_sock_addr.family == std.posix.AF.INET6);
const back_to_ipv6 = try Address.fromSockAddr(ipv6_sock_addr);
try testing.expect(back_to_ipv6.equals(ipv6_addr));
}
test "address error handling" {
// Test invalid IPv4 address
try testing.expectError(Error.AddressParseError, Ipv4Address.fromString("invalid"));
try testing.expectError(Error.AddressParseError, Ipv4Address.fromString("256.1.1.1"));
try testing.expectError(Error.AddressParseError, Ipv4Address.fromString("1.1.1"));
// Test invalid IPv6 address
try testing.expectError(Error.AddressParseError, Ipv6Address.fromString("invalid"));
// Test invalid port - returns InvalidPort
try testing.expectError(Error.InvalidPort, Address.parse("192.168.1.1:65536"));
try testing.expectError(Error.InvalidPort, Address.parse("192.168.1.1:abc"));
}
test "address edge cases" {
// Test zero address
const zero_addr = try Address.parse("0.0.0.0:0");
try testing.expect(zero_addr.isValid());
// Test broadcast address
const broadcast = try Address.parse("255.255.255.255:0");
try testing.expect(broadcast.isValid());
// Test localhost variations (IPv4 only - IPv6 compressed notation has parsing issues)
const localhost_variants = [_][]const u8{
"127.0.0.1",
"127.0.0.1:8080",
};
for (localhost_variants) |variant| {
const addr = try Address.parse(variant);
try testing.expect(addr.isLoopback());
}
// Test very long Unix socket path (should handle gracefully)
const long_path = "/tmp/" ++ "a" ** 200;
if (long_path.len < 108) { // Unix socket path limit
const unix_addr = try Address.parse(long_path);
try testing.expect(unix_addr.isValid());
}
}
test "address custom types" {
// Test custom address creation
const custom_data = "custom_address_data";
const custom_addr = Address.custom(123, custom_data);
try testing.expect(custom_addr.family == .custom);
try testing.expect(custom_addr.data.custom.id == 123);
try testing.expectEqualSlices(u8, custom_data, custom_addr.data.custom.data);
try testing.expect(custom_addr.isValid());
}
// ============================================================================
// Additional Coverage Tests
// ============================================================================
test "ipv4 address boundary values" {
// Test max IPv4 address
const max_addr = try Ipv4Address.fromString("255.255.255.255");
try testing.expectEqualSlices(u8, &[_]u8{ 255, 255, 255, 255 }, &max_addr.bytes);
// Test min IPv4 address
const min_addr = try Ipv4Address.fromString("0.0.0.0");
try testing.expectEqualSlices(u8, &[_]u8{ 0, 0, 0, 0 }, &min_addr.bytes);
// Test single octet boundary
const boundary = try Ipv4Address.fromString("0.0.0.255");
try testing.expectEqual(@as(u8, 255), boundary.bytes[3]);
}
test "ipv4 address parsing errors" {
// Test value > 255
try testing.expectError(Error.AddressParseError, Ipv4Address.fromString("256.0.0.0"));
try testing.expectError(Error.AddressParseError, Ipv4Address.fromString("0.256.0.0"));
try testing.expectError(Error.AddressParseError, Ipv4Address.fromString("0.0.256.0"));
try testing.expectError(Error.AddressParseError, Ipv4Address.fromString("0.0.0.256"));
// Test too few parts
try testing.expectError(Error.AddressParseError, Ipv4Address.fromString("192.168.1"));
try testing.expectError(Error.AddressParseError, Ipv4Address.fromString("192.168"));
try testing.expectError(Error.AddressParseError, Ipv4Address.fromString("192"));
// Test too many parts
try testing.expectError(Error.AddressParseError, Ipv4Address.fromString("192.168.1.1.1"));
// Test non-numeric
try testing.expectError(Error.AddressParseError, Ipv4Address.fromString("abc.168.1.1"));
}
test "ipv6 compressed notation" {
// Test fully compressed (unspecified)
const unspecified = try Ipv6Address.fromString("::");
var expected_zeros: [16]u8 = [_]u8{0} ** 16;
try testing.expectEqualSlices(u8, &expected_zeros, &unspecified.bytes);
// Test trailing compression
const trailing = try Ipv6Address.fromString("2001:db8::");
try testing.expectEqual(@as(u8, 0x20), trailing.bytes[0]);
try testing.expectEqual(@as(u8, 0x01), trailing.bytes[1]);
// Test middle compression
const middle = try Ipv6Address.fromString("2001:db8::1");
try testing.expectEqual(@as(u8, 0x20), middle.bytes[0]);
}
test "ipv6 address parsing errors" {
// Test invalid hex digits
try testing.expectError(Error.AddressParseError, Ipv6Address.fromString("ghij::1"));
}
test "unix address path length" {
// Test max length path (107 chars + null = 108)
const max_path = "/" ++ "a" ** 106;
const max_addr = try UnixAddress.fromString(max_path);
try testing.expectEqualSlices(u8, max_path, max_addr.toString());
// Test path overflow - returns InvalidAddressFormat
const overflow_path = "/" ++ "a" ** 200;
try testing.expectError(Error.InvalidAddressFormat, UnixAddress.fromString(overflow_path));
}
test "address parse with malformed brackets" {
// Test missing closing bracket
try testing.expectError(Error.AddressParseError, Address.parse("[2001:db8::1:8080"));
// Test missing opening bracket for IPv6 with port
try testing.expectError(Error.AddressParseError, Address.parse("2001:db8::1]:8080"));
}
test "address toU128 conversion" {
// Test IPv4 to u128
const ipv4 = try Address.parse("192.168.1.100:8080");
const ipv4_u128 = ipv4.toU128();
try testing.expect(ipv4_u128 > 0);
// Test IPv6 to u128
const ipv6 = try Address.parse("[2001:db8::1]:8080");
const ipv6_u128 = ipv6.toU128();
try testing.expect(ipv6_u128 > 0);
// Test Unix returns 0
const unix = try Address.parse("/tmp/test.sock");
try testing.expectEqual(@as(u128, 0), unix.toU128());
// Test custom returns 0
const custom = Address.custom(123, "data");
try testing.expectEqual(@as(u128, 0), custom.toU128());
}
test "address getRawBytes" {
// Test IPv4 raw bytes
const ipv4 = try Address.parse("192.168.1.100:8080");
const ipv4_bytes = try ipv4.getRawBytes();
try testing.expectEqual(@as(usize, 4), ipv4_bytes.len);
try testing.expectEqualSlices(u8, &[_]u8{ 192, 168, 1, 100 }, ipv4_bytes);
// Test IPv6 raw bytes
const ipv6 = try Address.parse("[::1]:8080");
const ipv6_bytes = try ipv6.getRawBytes();
try testing.expectEqual(@as(usize, 16), ipv6_bytes.len);
// Test Unix raw bytes (path slice)
const unix = try Address.parse("/tmp/test.sock");
const unix_bytes = try unix.getRawBytes();
try testing.expect(unix_bytes.len > 0);
// Test custom raw bytes
const custom = Address.custom(123, "custom_data");
const custom_bytes = try custom.getRawBytes();
try testing.expectEqualSlices(u8, "custom_data", custom_bytes);
}
test "address compare various families" {
// Test IPv4 vs IPv4 same address
const ipv4_a = try Address.parse("192.168.1.100:8080");
const ipv4_b = try Address.parse("192.168.1.100:8080");
try testing.expectEqual(@as(i32, 0), ipv4_a.compare(ipv4_b));
// Test IPv4 vs IPv4 different address
const ipv4_c = try Address.parse("192.168.1.101:8080");
try testing.expect(ipv4_a.compare(ipv4_c) < 0);
// Test IPv4 vs IPv6 (different families)
const ipv6 = try Address.parse("[::1]:8080");
const family_cmp = ipv4_a.compare(ipv6);
try testing.expect(family_cmp != 0);
// Test port comparison (same address, different port)
const ipv4_d = try Address.parse("192.168.1.100:9090");
try testing.expect(ipv4_a.compare(ipv4_d) < 0);
// Test Unix comparison
const unix_a = try Address.parse("/tmp/a.sock");
const unix_b = try Address.parse("/tmp/b.sock");
try testing.expect(unix_a.compare(unix_b) < 0);
// Test custom comparison
const custom_a = Address.custom(100, "data");
const custom_b = Address.custom(200, "data");
try testing.expect(custom_a.compare(custom_b) < 0);
}
test "address toString and toStringBuf" {
// Test IPv4 toString
const ipv4 = try Address.parse("192.168.1.100:8080");
const ipv4_str = try ipv4.toString(testing.allocator);
defer testing.allocator.free(ipv4_str);
try testing.expect(ipv4_str.len > 0);
// Test IPv6 toString
const ipv6 = try Address.parse("[2001:db8::1]:8080");
const ipv6_str = try ipv6.toString(testing.allocator);
defer testing.allocator.free(ipv6_str);
try testing.expect(ipv6_str.len > 0);
// Test toStringBuf
var buf: [128]u8 = undefined;
const ipv4_buf = ipv4.toStringBuf(&buf);
try testing.expect(ipv4_buf.len > 0);
}
test "address isValid edge cases" {
// Test IPv4 multicast with port
const mcast_ipv4 = Address.ipv4([_]u8{ 224, 0, 0, 1 }, 8080);
try testing.expect(mcast_ipv4.isValid());
// Test IPv4 multicast without port (port 0)
const mcast_no_port = Address.ipv4([_]u8{ 224, 0, 0, 1 }, 0);
const valid = mcast_no_port.isValid();
_ = valid; // Just check it doesn't crash
// Test custom with empty data
const custom_empty = Address.custom(0, "");
const custom_valid = custom_empty.isValid();
_ = custom_valid;
}
test "address list addMany" {
var list = AddressList.init(testing.allocator);
defer list.deinit();
const addr1 = try Address.parse("192.168.1.1:8080");
const addr2 = try Address.parse("192.168.1.2:8080");
const addr3 = try Address.parse("192.168.1.3:8080");
// Add multiple addresses at once
const addrs = [_]Address{ addr1, addr2, addr3 };
try list.addMany(&addrs);
try testing.expectEqual(@as(usize, 3), list.len());
try testing.expect(list.contains(addr1));
try testing.expect(list.contains(addr2));
try testing.expect(list.contains(addr3));
}
test "address list remove non-existent" {
var list = AddressList.init(testing.allocator);
defer list.deinit();
const addr1 = try Address.parse("192.168.1.1:8080");
const addr2 = try Address.parse("192.168.1.2:8080");
try list.add(addr1);
// Remove non-existent address should not crash
list.remove(addr2);
try testing.expectEqual(@as(usize, 1), list.len());
}
test "address list multiple operations" {
var list = AddressList.init(testing.allocator);
defer list.deinit();
const addr1 = try Address.parse("192.168.1.1:8080");
const addr2 = try Address.parse("192.168.1.2:8080");
try list.add(addr1);
try list.add(addr2);
// Verify count by accessing elements
try testing.expectEqual(@as(usize, 2), list.len());
try testing.expect(list.get(0) != null);
try testing.expect(list.get(1) != null);
try testing.expect(list.get(2) == null);
}
test "ipv4 address network class detection" {
// Test Class A private (10.x.x.x)
const class_a = Ipv4Address.init([_]u8{ 10, 0, 0, 1 });
try testing.expect(class_a.isPrivate());
// Test Class B private (172.16.x.x - 172.31.x.x)
const class_b = Ipv4Address.init([_]u8{ 172, 16, 0, 1 });
try testing.expect(class_b.isPrivate());
// Test Class B edge (172.32.x.x is NOT private)
const not_class_b = Ipv4Address.init([_]u8{ 172, 32, 0, 1 });
try testing.expect(!not_class_b.isPrivate());
// Test multicast (224.0.0.0 - 239.255.255.255)
const multicast = Ipv4Address.init([_]u8{ 224, 0, 0, 1 });
try testing.expect(multicast.isMulticast());
// Test loopback (127.x.x.x)
const loopback = Ipv4Address.init([_]u8{ 127, 0, 0, 1 });
try testing.expect(loopback.isLoopback());
}
test "ipv6 address special types" {
// Test link-local (fe80::/10)
var link_local_bytes: [16]u8 = [_]u8{0} ** 16;
link_local_bytes[0] = 0xfe;
link_local_bytes[1] = 0x80;
const link_local = Ipv6Address.init(link_local_bytes);
try testing.expect(link_local.isLinkLocal());
// Test unique local (fc00::/7)
var unique_local_bytes: [16]u8 = [_]u8{0} ** 16;
unique_local_bytes[0] = 0xfc;
const unique_local = Ipv6Address.init(unique_local_bytes);
try testing.expect(unique_local.isUniqueLocal());
// Test multicast (ff00::/8)
var multicast_bytes: [16]u8 = [_]u8{0} ** 16;
multicast_bytes[0] = 0xff;
const multicast = Ipv6Address.init(multicast_bytes);
try testing.expect(multicast.isMulticast());
// Test loopback (::1)
var loopback_bytes: [16]u8 = [_]u8{0} ** 16;
loopback_bytes[15] = 1;
const loopback = Ipv6Address.init(loopback_bytes);
try testing.expect(loopback.isLoopback());
}
test "address ipv4 and ipv6 factory methods" {
// Test Address.ipv4 factory
const ipv4 = Address.ipv4([_]u8{ 192, 168, 1, 100 }, 8080);
try testing.expect(ipv4.family == .ipv4);
try testing.expectEqual(@as(u16, 8080), ipv4.port);
// Test Address.ipv6 factory
var ipv6_bytes: [16]u8 = [_]u8{0} ** 16;
ipv6_bytes[15] = 1;
const ipv6 = Address.ipv6(ipv6_bytes, 9090);
try testing.expect(ipv6.family == .ipv6);
try testing.expectEqual(@as(u16, 9090), ipv6.port);
}

434
tests/core/test_buffer.zig Normal file
View File

@@ -0,0 +1,434 @@
//! Tests for buffer management module
const std = @import("std");
const testing = std.testing;
const Buffer = @import("../../src/core/buffer.zig");
const PoolConfig = @import("../../src/core/buffer.zig").PoolConfig;
const BufferPool = @import("../../src/core/buffer.zig").BufferPool;
const PoolStats = @import("../../src/core/buffer.zig").PoolStats;
const BufferType = @import("../../src/core/buffer.zig").BufferType;
const BufferFlags = @import("../../src/core/buffer.zig").BufferFlags;
const StreamBuffer = @import("../../src/core/buffer.zig").StreamBuffer;
const PacketBuffer = @import("../../src/core/buffer.zig").PacketBuffer;
const MessageBuffer = @import("../../src/core/buffer.zig").MessageBuffer;
const BufferManager = @import("../../src/core/buffer.zig").BufferManager;
test "buffer pool configuration" {
const config = PoolConfig{
.min_chunk_size = 128,
.max_chunk_size = 4096,
.initial_chunks = 4,
.max_chunks = 16,
.grow_factor = 2.0,
};
try testing.expectEqual(@as(usize, 128), config.min_chunk_size);
try testing.expectEqual(@as(usize, 4096), config.max_chunk_size);
try testing.expectEqual(@as(usize, 4), config.initial_chunks);
try testing.expectEqual(@as(usize, 16), config.max_chunks);
try testing.expectEqual(@as(f32, 2.0), config.grow_factor);
}
test "buffer pool creation and basic operations" {
const config = PoolConfig{
.min_chunk_size = 64,
.max_chunk_size = 1024,
.initial_chunks = 2,
.max_chunks = 10,
};
var pool = BufferPool.init(config, testing.allocator);
defer pool.deinit();
// Test initial pool stats
const initial_stats = pool.stats();
try testing.expect(initial_stats.total_chunks >= 2);
try testing.expect(initial_stats.free_chunks >= 2);
try testing.expectEqual(@as(usize, 0), initial_stats.used_chunks);
}
test "buffer pool allocation and deallocation" {
const config = PoolConfig{
.min_chunk_size = 64,
.max_chunk_size = 1024,
.initial_chunks = 2,
.max_chunks = 10,
};
var pool = BufferPool.init(config, testing.allocator);
defer pool.deinit();
// Test allocation
const buf1 = try pool.acquire(32);
try testing.expect(buf1.len == 32);
const buf2 = try pool.acquire(64);
try testing.expect(buf2.len == 64);
const buf3 = try pool.acquire(128);
try testing.expect(buf3.len == 128);
// Test stats after allocation
const allocated_stats = pool.stats();
try testing.expectEqual(@as(usize, 3), allocated_stats.used_chunks);
// Test deallocation
pool.release(buf1);
pool.release(buf2);
pool.release(buf3);
// Test stats after deallocation
const freed_stats = pool.stats();
try testing.expectEqual(@as(usize, 0), freed_stats.used_chunks);
try testing.expect(freed_stats.utilization() == 0.0);
}
test "buffer pool reuse" {
const config = PoolConfig{
.min_chunk_size = 128,
.max_chunk_size = 1024,
.initial_chunks = 1,
.max_chunks = 5,
};
var pool = BufferPool.init(config, testing.allocator);
defer pool.deinit();
// Allocate and release to test reuse
const buf1 = try pool.acquire(100);
pool.release(buf1);
const buf2 = try pool.acquire(100);
// Should reuse the same chunk
try testing.expect(buf2.ptr == buf1.ptr);
}
test "stream buffer creation and operations" {
var manager = BufferManager.init(.{}, testing.allocator);
defer manager.deinit();
// Test stream buffer from pool
const buffer = try manager.createStreamBuffer(100);
defer buffer.release();
try testing.expect(buffer.base.capacity >= 100);
try testing.expectEqual(@as(usize, 0), buffer.base.availableRead());
try testing.expectEqual(@as(usize, 100), buffer.base.availableWrite());
// Test stream buffer with external data
const external_data = try testing.allocator.alloc(u8, 50);
defer testing.allocator.free(external_data);
const external_buffer = StreamBuffer.initWithData(external_data, true);
try testing.expectEqual(@as(usize, 50), external_buffer.base.capacity);
try testing.expectEqual(@as(usize, 0), external_buffer.base.availableRead());
}
test "stream buffer write and read operations" {
var manager = BufferManager.init(.{}, testing.allocator);
defer manager.deinit();
const buffer = try manager.createStreamBuffer(100);
defer buffer.release();
// Test write operation
const test_data = "Hello, World!";
try buffer.write(test_data);
try testing.expectEqual(test_data.len, buffer.base.availableRead());
try testing.expectEqual(@as(usize, 100 - test_data.len), buffer.base.availableWrite());
// Test read operation
var read_buffer: [100]u8 = undefined;
const n = try buffer.read(&read_buffer);
try testing.expectEqual(test_data.len, n);
try testing.expectEqualSlices(u8, test_data, read_buffer[0..n]);
try testing.expectEqual(@as(usize, 0), buffer.base.availableRead());
}
test "stream buffer peek and skip operations" {
var manager = BufferManager.init(.{}, testing.allocator);
defer manager.deinit();
const buffer = try manager.createStreamBuffer(100);
defer buffer.release();
const test_data = "ABCDEFGHIJ";
try buffer.write(test_data);
// Test peek operation
const first_byte = buffer.peek(0).?;
try testing.expectEqual(@as(u8, 'A'), first_byte);
const second_byte = buffer.peek(1).?;
try testing.expectEqual(@as(u8, 'B'), second_byte);
// Test skip operation
try buffer.skip(3);
const after_skip_byte = buffer.peek(0).?;
try testing.expectEqual(@as(u8, 'D'), after_skip_byte);
// Test available read after skip
try testing.expectEqual(@as(usize, 7), buffer.base.availableRead());
}
test "stream reader and writer interfaces" {
var manager = BufferManager.init(.{}, testing.allocator);
defer manager.deinit();
const buffer = try manager.createStreamBuffer(100);
defer buffer.release();
var reader = buffer.asReader();
var writer = buffer.asWriter();
// Test writer interface
try writer.writeByte('A');
try writer.write("BC");
// Test reader interface
const byte = try reader.readByte();
try testing.expectEqual(@as(u8, 'A'), byte);
var read_data: [10]u8 = undefined;
const n = try reader.read(&read_data);
try testing.expectEqual(@as(usize, 2), n);
try testing.expectEqualSlices(u8, "BC", read_data[0..n]);
// Test read all
const test_data = "Test data for reading all";
try buffer.base.write(test_data);
const all_data = try reader.readAll(testing.allocator);
defer testing.allocator.free(all_data);
try testing.expectEqualSlices(u8, test_data, all_data);
}
test "packet buffer operations" {
var manager = BufferManager.init(.{}, testing.allocator);
defer manager.deinit();
const buffer = try manager.createPacketBuffer(100);
defer buffer.release();
// Test setting packet data
const packet_data = "UDP packet data";
try buffer.setPacketData(packet_data);
try testing.expectEqual(packet_data.len, buffer.packetSize());
try testing.expectEqualSlices(u8, packet_data, buffer.getPacketData());
try testing.expect(buffer.isComplete(packet_data.len));
try testing.expect(!buffer.isComplete(packet_data.len + 1));
// Test buffer capacity check
try testing.expect(buffer.canFit(packet_data.len));
try testing.expect(!buffer.canFit(101));
}
test "message buffer operations" {
var manager = BufferManager.init(.{}, testing.allocator);
defer manager.deinit();
const buffer = try manager.createMessageBuffer(100);
defer buffer.release();
// Test message header operations
buffer.setMessageHeader(1, 12345);
const header = buffer.getMessageHeader();
try testing.expectEqual(@as(u8, 1), header.msg_type);
try testing.expectEqual(@as(u32, 12345), header.msg_id);
try testing.expect(header.timestamp > 0);
try testing.expectEqual(@as(usize, 0), header.data_size);
// Test message data
const message_data = "Message payload";
try buffer.base.write(message_data);
const updated_header = buffer.getMessageHeader();
try testing.expectEqual(@as(usize, message_data.len), updated_header.data_size);
}
test "buffer flags operations" {
var flags = BufferFlags{
.read_only = false,
.owns_data = true,
.compressed = false,
.encrypted = false,
.priority = 5,
};
try testing.expect(!flags.read_only);
try testing.expect(flags.owns_data);
try testing.expect(!flags.compressed);
try testing.expect(!flags.encrypted);
try testing.expectEqual(@as(u3, 5), flags.priority);
}
test "buffer reference counting" {
var manager = BufferManager.init(.{}, testing.allocator);
defer manager.deinit();
const buffer = try manager.createStreamBuffer(100);
// Test initial ref count
try testing.expect(buffer.base.ref_count.load(.monotonic) == 1);
// Test acquire (increment ref count)
buffer.acquire();
try testing.expect(buffer.base.ref_count.load(.monotonic) == 2);
buffer.acquire();
try testing.expect(buffer.base.ref_count.load(.monotonic) == 3);
// Test release (decrement ref count)
buffer.release();
try testing.expect(buffer.base.ref_count.load(.monotonic) == 2);
buffer.release();
try testing.expect(buffer.base.ref_count.load(.monotonic) == 1);
// Final release should not panic (would deallocate)
buffer.release();
}
test "buffer compact operation" {
var manager = BufferManager.init(.{}, testing.allocator);
defer manager.deinit();
const buffer = try manager.createStreamBuffer(100);
defer buffer.release();
// Write and partially read to create gap
const test_data = "This is a long test string for compacting";
try buffer.write(test_data);
// Read part of the data
var read_buffer: [10]u8 = undefined;
const n = try buffer.read(&read_buffer);
try testing.expectEqual(@as(usize, 10), n);
try testing.expectEqual(@as(usize, 10), buffer.base.read_pos);
try testing.expectEqual(@as(usize, test_data.len), buffer.base.write_pos);
// Compact should move remaining data to beginning
buffer.compact();
try testing.expectEqual(@as(usize, 0), buffer.base.read_pos);
try testing.expectEqual(@as(usize, test_data.len - 10), buffer.base.write_pos);
// Verify remaining data is correct
var remaining_data: [50]u8 = undefined;
const remaining_n = try buffer.read(&remaining_data);
try testing.expectEqual(test_data.len - 10, remaining_n);
const expected_remaining = test_data[10..];
try testing.expectEqualSlices(u8, expected_remaining, remaining_data[0..remaining_n]);
}
test "buffer manager operations" {
const config = PoolConfig{
.min_chunk_size = 256,
.max_chunk_size = 2048,
.initial_chunks = 3,
.max_chunks = 20,
};
var manager = BufferManager.init(config, testing.allocator);
defer manager.deinit();
// Test creating different buffer types
const stream_buf = try manager.createStreamBuffer(128);
defer stream_buf.release();
const packet_buf = try manager.createPacketBuffer(256);
defer packet_buf.release();
const message_buf = try manager.createMessageBuffer(512);
defer message_buf.release();
// Test pool statistics
const stats = manager.getPoolStats();
try testing.expect(stats.total_chunks >= 3);
try testing.expect(stats.total_bytes >= 128 + 256 + 512);
// Test utilization
const utilization = stats.utilization();
try testing.expect(utilization > 0.0);
try testing.expect(utilization <= 1.0);
}
test "buffer error handling" {
var manager = BufferManager.init(.{}, testing.allocator);
defer manager.deinit();
// Test write beyond capacity
const buffer = try manager.createStreamBuffer(10);
defer buffer.release();
const large_data = "This is too much data for the buffer";
try testing.expectError(Buffer.Error.BufferTooSmall, buffer.write(large_data));
// Test read beyond available data
var read_buffer: [10]u8 = undefined;
try testing.expectEqual(@as(usize, 0), try buffer.read(&read_buffer));
// Test peek beyond available data
try testing.expect(buffer.peek(0) == null);
// Test skip beyond available data
try testing.expectError(Buffer.Error.BufferUnderflow, buffer.skip(1));
}
test "buffer capacity management" {
var manager = BufferManager.init(.{}, testing.allocator);
defer manager.deinit();
const buffer = try manager.createStreamBuffer(100);
defer buffer.release();
// Write some data
const data1 = "First";
try buffer.write(data1);
// Ensure capacity should work for current capacity
try buffer.ensureCapacity(50); // Less than current capacity
try buffer.ensureCapacity(150); // More than current capacity
// Note: ensureCapacity for larger size is not implemented yet
// This would require buffer growth implementation
}
test "buffer type identification" {
try testing.expectEqual(@as(u8, 1), @intFromEnum(BufferType.stream));
try testing.expectEqual(@as(u8, 2), @intFromEnum(BufferType.packet));
try testing.expectEqual(@as(u8, 3), @intFromEnum(BufferType.message));
}
test "buffer pool limits" {
const config = PoolConfig{
.min_chunk_size = 1024,
.max_chunk_size = 4096,
.initial_chunks = 1,
.max_chunks = 2, // Very small limit
};
var pool = BufferPool.init(config, testing.allocator);
defer pool.deinit();
// Should be able to allocate within limits
const buf1 = try pool.acquire(512);
const buf2 = try pool.acquire(512);
// Should fail to allocate beyond limits
try testing.expectError(Buffer.Error.ResourceExhausted, pool.acquire(512));
// Clean up
pool.release(buf1);
pool.release(buf2);
}

View File

@@ -0,0 +1,445 @@
const std = @import("std");
const testing = std.testing;
const core = @import("core");
const Buffer = core.buffer;
const BufferPool = Buffer.BufferPool;
const PoolConfig = Buffer.PoolConfig;
const StreamBuffer = Buffer.StreamBuffer;
const PacketBuffer = Buffer.PacketBuffer;
const MessageBuffer = Buffer.MessageBuffer;
const BufferManager = Buffer.BufferManager;
const Error = core.errors.Error;
test "buffer pool: initialization and cleanup" {
const allocator = testing.allocator;
const config = PoolConfig{
.min_chunk_size = 1024,
.max_chunk_size = 64 * 1024,
.initial_chunks = 4,
};
var pool = BufferPool.init(config, allocator);
defer pool.deinit();
const stats = pool.stats();
try testing.expect(stats.total_chunks >= 4);
}
test "buffer pool: acquire and release" {
const allocator = testing.allocator;
const config = PoolConfig{
.min_chunk_size = 512,
.max_chunk_size = 4096,
};
var pool = BufferPool.init(config, allocator);
defer pool.deinit();
const buf = try pool.acquire(1024);
try testing.expectEqual(@as(usize, 1024), buf.len);
pool.release(buf);
}
test "buffer pool: acquire under memory pressure" {
const allocator = testing.allocator;
const config = PoolConfig{
.min_chunk_size = 1024,
.max_chunk_size = 8192,
.max_chunks = 3,
};
var pool = BufferPool.init(config, allocator);
defer pool.deinit();
const buf1 = try pool.acquire(1024);
const buf2 = try pool.acquire(2048);
const buf3 = try pool.acquire(1024);
// Should fail - pool is at max capacity
const result = pool.acquire(1024);
try testing.expectError(Error.ResourceExhausted, result);
// Release one buffer
pool.release(buf1);
// Now acquisition should succeed
const buf4 = try pool.acquire(1024);
try testing.expectEqual(@as(usize, 1024), buf4.len);
pool.release(buf2);
pool.release(buf3);
pool.release(buf4);
}
test "buffer pool: buffer with exactly max size" {
const allocator = testing.allocator;
const config = PoolConfig{
.min_chunk_size = 1024,
.max_chunk_size = 16384,
};
var pool = BufferPool.init(config, allocator);
defer pool.deinit();
const buf = try pool.acquire(16384);
try testing.expectEqual(@as(usize, 16384), buf.len);
pool.release(buf);
}
test "buffer pool: buffer with max+1 size fails" {
const allocator = testing.allocator;
const config = PoolConfig{
.min_chunk_size = 1024,
.max_chunk_size = 8192,
.max_single_allocation = 8192,
};
var pool = BufferPool.init(config, allocator);
defer pool.deinit();
const result = pool.acquire(8193);
try testing.expectError(Error.AllocationTooLarge, result);
}
test "buffer pool: allocation size calculation" {
const allocator = testing.allocator;
const config = PoolConfig{
.min_chunk_size = 1024,
.max_chunk_size = 16384,
.grow_factor = 2.0,
};
var pool = BufferPool.init(config, allocator);
defer pool.deinit();
// Request 3000 bytes, should get next power of 2 * grow_factor
const buf = try pool.acquire(3000);
try testing.expect(buf.len == 3000);
pool.release(buf);
}
test "buffer pool: statistics tracking" {
const allocator = testing.allocator;
const config = PoolConfig{
.min_chunk_size = 512,
.max_chunk_size = 4096,
.initial_chunks = 2,
};
var pool = BufferPool.init(config, allocator);
defer pool.deinit();
const buf1 = try pool.acquire(512);
const buf2 = try pool.acquire(1024);
const stats = pool.stats();
try testing.expect(stats.used_chunks >= 2);
try testing.expect(stats.total_chunks >= 2);
pool.release(buf1);
pool.release(buf2);
}
test "stream buffer: create and destroy" {
const allocator = testing.allocator;
var buffer = try StreamBuffer.init(allocator, 1024);
defer buffer.deinit();
try testing.expectEqual(@as(usize, 1024), buffer.base.capacity);
try testing.expectEqual(@as(usize, 0), buffer.base.write_pos);
}
test "stream buffer: write and read" {
const allocator = testing.allocator;
var buffer = try StreamBuffer.init(allocator, 1024);
defer buffer.deinit();
const data = "Hello, World!";
try buffer.write(data);
var read_buf: [100]u8 = undefined;
const n = try buffer.read(&read_buf);
try testing.expectEqual(data.len, n);
try testing.expectEqualSlices(u8, data, read_buf[0..n]);
}
test "stream buffer: write overflow detection" {
const allocator = testing.allocator;
var buffer = try StreamBuffer.init(allocator, 10);
defer buffer.deinit();
const data = "This is too long!";
const result = buffer.write(data);
try testing.expectError(Error.BufferTooSmall, result);
}
test "stream buffer: read underflow" {
const allocator = testing.allocator;
var buffer = try StreamBuffer.init(allocator, 1024);
defer buffer.deinit();
try buffer.write("short");
var read_buf: [100]u8 = undefined;
const n = try buffer.read(&read_buf);
try testing.expectEqual(@as(usize, 5), n);
}
test "stream buffer: ensureCapacity grows buffer" {
const allocator = testing.allocator;
var buffer = try StreamBuffer.init(allocator, 64);
defer buffer.deinit();
try testing.expectEqual(@as(usize, 64), buffer.base.capacity);
try buffer.ensureCapacity(256);
try testing.expect(buffer.base.capacity >= 256);
}
test "stream buffer: ensureCapacity preserves data" {
const allocator = testing.allocator;
var buffer = try StreamBuffer.init(allocator, 32);
defer buffer.deinit();
const test_data = "Test Data";
try buffer.write(test_data);
try buffer.ensureCapacity(128);
var read_buf: [32]u8 = undefined;
const n = try buffer.read(&read_buf);
try testing.expectEqual(test_data.len, n);
try testing.expectEqualSlices(u8, test_data, read_buf[0..n]);
}
test "stream buffer: ensureCapacity without allocator fails" {
var data: [64]u8 = undefined;
var buffer = StreamBuffer.initWithData(&data, false);
const result = buffer.ensureCapacity(128);
try testing.expectError(Error.BufferTooSmall, result);
}
test "stream buffer: ensureCapacity no-op when sufficient" {
const allocator = testing.allocator;
var buffer = try StreamBuffer.init(allocator, 128);
defer buffer.deinit();
const original_capacity = buffer.base.capacity;
try buffer.ensureCapacity(64);
try testing.expectEqual(original_capacity, buffer.base.capacity);
}
test "stream buffer: peek operation" {
const allocator = testing.allocator;
var buffer = try StreamBuffer.init(allocator, 1024);
defer buffer.deinit();
try buffer.write("ABC");
try testing.expectEqual(@as(u8, 'A'), buffer.peek(0).?);
try testing.expectEqual(@as(u8, 'B'), buffer.peek(1).?);
try testing.expectEqual(@as(u8, 'C'), buffer.peek(2).?);
try testing.expect(buffer.peek(3) == null);
}
test "stream buffer: skip operation" {
const allocator = testing.allocator;
var buffer = try StreamBuffer.init(allocator, 1024);
defer buffer.deinit();
try buffer.write("ABCDEF");
try buffer.skip(2);
var read_buf: [10]u8 = undefined;
const n = try buffer.read(&read_buf);
try testing.expectEqualSlices(u8, "CDEF", read_buf[0..n]);
}
test "stream buffer: skip overflow" {
const allocator = testing.allocator;
var buffer = try StreamBuffer.init(allocator, 1024);
defer buffer.deinit();
try buffer.write("ABC");
const result = buffer.skip(10);
try testing.expectError(Error.BufferUnderflow, result);
}
test "stream buffer: reset clears buffer" {
const allocator = testing.allocator;
var buffer = try StreamBuffer.init(allocator, 1024);
defer buffer.deinit();
try buffer.write("test data");
buffer.reset();
try testing.expectEqual(@as(usize, 0), buffer.base.read_pos);
try testing.expectEqual(@as(usize, 0), buffer.base.write_pos);
}
test "stream buffer: write and read integers" {
const allocator = testing.allocator;
var buffer = try StreamBuffer.init(allocator, 1024);
defer buffer.deinit();
try buffer.writeInt(u32, 0x12345678, .big);
const value = try buffer.readInt(u32, .big);
try testing.expectEqual(@as(u32, 0x12345678), value);
}
test "packet buffer: set and get packet data" {
const allocator = testing.allocator;
const config = PoolConfig{};
var pool = BufferPool.init(config, allocator);
defer pool.deinit();
var buffer = try PacketBuffer.initFromPool(100, &pool);
defer buffer.release();
const test_data = "Packet data";
try buffer.setPacketData(test_data);
try testing.expectEqual(test_data.len, buffer.packetSize());
try testing.expectEqualSlices(u8, test_data, buffer.getPacketData());
}
test "packet buffer: isComplete check" {
const allocator = testing.allocator;
const config = PoolConfig{};
var pool = BufferPool.init(config, allocator);
defer pool.deinit();
var buffer = try PacketBuffer.initFromPool(100, &pool);
defer buffer.release();
try buffer.setPacketData("12345");
try testing.expect(buffer.isComplete(5));
try testing.expect(!buffer.isComplete(10));
}
test "packet buffer: canFit check" {
const allocator = testing.allocator;
const config = PoolConfig{};
var pool = BufferPool.init(config, allocator);
defer pool.deinit();
var buffer = try PacketBuffer.initFromPool(50, &pool);
defer buffer.release();
try testing.expect(buffer.canFit(50));
try testing.expect(!buffer.canFit(100));
}
test "message buffer: message header operations" {
const allocator = testing.allocator;
const config = PoolConfig{};
var pool = BufferPool.init(config, allocator);
defer pool.deinit();
var buffer = try MessageBuffer.initFromPool(100, &pool);
defer buffer.release();
buffer.setMessageHeader(42, 12345);
const header = buffer.getMessageHeader();
try testing.expectEqual(@as(u8, 42), header.msg_type);
try testing.expectEqual(@as(u32, 12345), header.msg_id);
try testing.expect(header.timestamp > 0);
}
test "buffer manager: create stream buffer" {
const allocator = testing.allocator;
const config = PoolConfig{};
var manager = BufferManager.init(config, allocator);
defer manager.deinit();
var buffer = try manager.createStreamBuffer(1024);
defer buffer.release();
try testing.expect(buffer.base.capacity >= 1024);
}
test "buffer manager: create packet buffer" {
const allocator = testing.allocator;
const config = PoolConfig{};
var manager = BufferManager.init(config, allocator);
defer manager.deinit();
var buffer = try manager.createPacketBuffer(512);
defer buffer.release();
try testing.expect(buffer.base.capacity >= 512);
}
test "buffer manager: create message buffer" {
const allocator = testing.allocator;
const config = PoolConfig{};
var manager = BufferManager.init(config, allocator);
defer manager.deinit();
var buffer = try manager.createMessageBuffer(256);
defer buffer.release();
try testing.expect(buffer.base.capacity >= 256);
}
test "buffer manager: pool statistics" {
const allocator = testing.allocator;
const config = PoolConfig{
.initial_chunks = 4,
};
var manager = BufferManager.init(config, allocator);
defer manager.deinit();
const stats = manager.getPoolStats();
try testing.expect(stats.total_chunks >= 4);
}
test "buffer: reference counting" {
const allocator = testing.allocator;
const config = PoolConfig{};
var manager = BufferManager.init(config, allocator);
defer manager.deinit();
var buffer = try manager.createStreamBuffer(1024);
buffer.acquire();
buffer.acquire();
buffer.release();
buffer.release();
buffer.release(); // Final release
}

View File

@@ -0,0 +1,371 @@
//! Comprehensive tests for buffer overflow prevention and size limits
//!
//! This test suite validates that all size limits and buffer overflow
//! protections are working correctly across the codebase.
const std = @import("std");
const testing = std.testing;
const mem = std.mem;
// Import modules to test
const core = @import("core");
const Error = core.errors.Error;
const Address = core.address.Address;
const AddressResolver = core.address.AddressResolver;
const MAX_DNS_RESULTS = core.address.MAX_DNS_RESULTS;
const BufferPool = core.buffer.BufferPool;
const PoolConfig = core.buffer.PoolConfig;
const files = @import("files");
const TransferMessage = files.transfer.TransferMessage;
const TransferLimits = files.transfer.TransferLimits;
const network = @import("network");
const NetworkManager = network.network_manager.NetworkManager;
const NetworkManagerConfig = network.network_manager.Config;
//============================================================================
// Transfer Message Size Limit Tests
//============================================================================
test "transfer message: reject oversized messages" {
const allocator = testing.allocator;
// Create a message with total size exceeding MAX_MESSAGE_SIZE
const huge_data = try allocator.alloc(u8, TransferLimits.MAX_MESSAGE_SIZE);
defer allocator.free(huge_data);
@memset(huge_data, 0xFF);
const message = TransferMessage{
.message_type = .piece_data,
.message_id = 123,
.peer_id = "peer123",
.data = huge_data,
.timestamp = std.time.timestamp(),
};
// Should fail due to size limit
const result = message.serialize(allocator);
try testing.expectError(Error.MessageTooLarge, result);
}
test "transfer message: reject oversized peer ID" {
const allocator = testing.allocator;
// Create peer ID exceeding MAX_PEER_ID_LEN
const huge_peer_id = try allocator.alloc(u8, TransferLimits.MAX_PEER_ID_LEN + 1);
defer allocator.free(huge_peer_id);
@memset(huge_peer_id, 'A');
// Create a valid message first
const valid_msg = TransferMessage{
.message_type = .handshake,
.message_id = 1,
.peer_id = "normal_peer",
.data = "test",
.timestamp = std.time.timestamp(),
};
const serialized = try valid_msg.serialize(allocator);
defer allocator.free(serialized);
// Manually craft a buffer with oversized peer_id_len
const buffer_size = 1024;
const bad_buffer = try allocator.alloc(u8, buffer_size);
defer allocator.free(bad_buffer);
@memset(bad_buffer, 0);
// Header: type(1) + id(4) + peer_id_len(2) + timestamp(8) + data_len(4)
bad_buffer[0] = @intFromEnum(TransferMessage.MessageType.handshake);
// Set peer_id_len to exceed limit
const bad_len: u16 = TransferLimits.MAX_PEER_ID_LEN + 1;
@memcpy(bad_buffer[5..7], &std.mem.toBytes(std.mem.nativeToBig(u16, bad_len)));
// Should fail during deserialization
const result = TransferMessage.deserialize(bad_buffer, allocator);
try testing.expectError(Error.InvalidData, result);
}
test "transfer message: reject oversized data" {
const allocator = testing.allocator;
// Manually craft a buffer with oversized data_len
const buffer_size = 1024;
const bad_buffer = try allocator.alloc(u8, buffer_size);
defer allocator.free(bad_buffer);
@memset(bad_buffer, 0);
// Header: type(1) + id(4) + peer_id_len(2) + timestamp(8) + data_len(4)
bad_buffer[0] = @intFromEnum(TransferMessage.MessageType.piece_data);
// Set small peer_id_len
const peer_len: u16 = 10;
@memcpy(bad_buffer[5..7], &std.mem.toBytes(std.mem.nativeToBig(u16, peer_len)));
// Set data_len to exceed limit
const bad_data_len: u32 = TransferLimits.MAX_DATA_LEN + 1;
@memcpy(bad_buffer[15..19], &std.mem.toBytes(std.mem.nativeToBig(u32, bad_data_len)));
// Should fail during deserialization
const result = TransferMessage.deserialize(bad_buffer, allocator);
try testing.expectError(Error.InvalidData, result);
}
test "transfer message: accept valid sized messages" {
const allocator = testing.allocator;
// Create a message within limits
const valid_data = "This is valid data";
const message = TransferMessage{
.message_type = .handshake,
.message_id = 456,
.peer_id = "valid_peer_id",
.data = valid_data,
.timestamp = std.time.timestamp(),
};
// Should succeed
const serialized = try message.serialize(allocator);
defer allocator.free(serialized);
var deserialized = try TransferMessage.deserialize(serialized, allocator);
defer deserialized.deinit(allocator);
try testing.expectEqual(message.message_type, deserialized.message_type);
try testing.expectEqual(message.message_id, deserialized.message_id);
try testing.expectEqualSlices(u8, message.peer_id, deserialized.peer_id);
try testing.expectEqualSlices(u8, message.data, deserialized.data);
}
//============================================================================
// Buffer Pool Allocation Limit Tests
//============================================================================
test "buffer pool: reject allocation exceeding max_single_allocation" {
const config = PoolConfig{
.min_chunk_size = 1024,
.max_chunk_size = 1024 * 1024,
.initial_chunks = 2,
.max_chunks = 10,
.max_single_allocation = 10 * 1024 * 1024, // 10MB
};
var pool = BufferPool.init(config, testing.allocator);
defer pool.deinit();
// Try to acquire buffer larger than max_single_allocation
const result = pool.acquire(config.max_single_allocation + 1);
try testing.expectError(Error.AllocationTooLarge, result);
}
test "buffer pool: accept allocation within max_single_allocation" {
const config = PoolConfig{
.min_chunk_size = 1024,
.max_chunk_size = 1024 * 1024,
.initial_chunks = 2,
.max_chunks = 10,
.max_single_allocation = 10 * 1024 * 1024, // 10MB
};
var pool = BufferPool.init(config, testing.allocator);
defer pool.deinit();
// Acquire buffer within limits
const buffer = try pool.acquire(1024);
try testing.expect(buffer.len == 1024);
pool.release(buffer);
}
test "buffer pool: enforce maximum allocation size" {
const config = PoolConfig{
.max_single_allocation = 1024, // Very small limit for testing
};
var pool = BufferPool.init(config, testing.allocator);
defer pool.deinit();
// Try various sizes
try testing.expectError(Error.AllocationTooLarge, pool.acquire(1025));
try testing.expectError(Error.AllocationTooLarge, pool.acquire(2048));
try testing.expectError(Error.AllocationTooLarge, pool.acquire(10000));
// This should work
const valid = try pool.acquire(1024);
try testing.expect(valid.len == 1024);
pool.release(valid);
}
//============================================================================
// Network Manager Buffer Size Tests
//============================================================================
test "network manager: configurable receive buffer size" {
const config = NetworkManagerConfig{
.receive_buffer_size = 8192, // 8KB
.max_message_size = 4096, // 4KB
};
var connections = std.AutoHashMap(network.peer.PeerId, *core.socket.Socket).init(testing.allocator);
defer connections.deinit();
var manager = NetworkManager.initWithConfig(testing.allocator, &connections, config);
defer manager.deinit();
try testing.expectEqual(@as(usize, 8192), manager.config.receive_buffer_size);
try testing.expectEqual(@as(usize, 4096), manager.config.max_message_size);
}
//============================================================================
// DNS Resolution Limit Tests
//============================================================================
test "dns resolution: limit results to MAX_DNS_RESULTS" {
// Note: This is a conceptual test. Actual DNS resolution would require
// a real network connection or mock. We verify the constant exists.
try testing.expect(MAX_DNS_RESULTS == 100);
}
test "address resolver: verify MAX_DNS_RESULTS constant" {
// Verify the constant is properly defined
const max_results: usize = MAX_DNS_RESULTS;
try testing.expect(max_results > 0);
try testing.expect(max_results <= 1000); // Reasonable upper bound
}
//============================================================================
// Integration Tests
//============================================================================
test "integration: transfer limits prevent resource exhaustion" {
// Verify all limits are reasonable and coordinated
try testing.expect(TransferLimits.MAX_PEER_ID_LEN < TransferLimits.MAX_MESSAGE_SIZE);
try testing.expect(TransferLimits.MAX_DATA_LEN < TransferLimits.MAX_MESSAGE_SIZE);
try testing.expect(TransferLimits.MAX_HANDSHAKE_SIZE < TransferLimits.MAX_MESSAGE_SIZE);
// Verify limits are large enough for practical use
try testing.expect(TransferLimits.MAX_PEER_ID_LEN >= 64);
try testing.expect(TransferLimits.MAX_DATA_LEN >= 1024 * 1024); // At least 1MB
try testing.expect(TransferLimits.MAX_MESSAGE_SIZE >= 1024 * 1024); // At least 1MB
}
test "integration: buffer pool limits prevent memory exhaustion" {
const default_config = PoolConfig{};
// Verify defaults are reasonable
try testing.expect(default_config.max_single_allocation > default_config.max_chunk_size);
try testing.expect(default_config.max_chunks > 0);
try testing.expect(default_config.initial_chunks <= default_config.max_chunks);
}
test "integration: network manager config prevents stack overflow" {
const default_config = NetworkManagerConfig{};
// Verify receive buffer is allocated on heap (not stack)
// Stack allocation was 65536 bytes, now configurable
try testing.expect(default_config.receive_buffer_size == 64 * 1024);
try testing.expect(default_config.max_message_size <= default_config.receive_buffer_size * 16);
}
//============================================================================
// Edge Case Tests
//============================================================================
test "edge case: zero-sized allocations" {
var pool = BufferPool.init(.{}, testing.allocator);
defer pool.deinit();
// Zero-sized allocation should be handled gracefully
const result = pool.acquire(0);
if (result) |buffer| {
try testing.expect(buffer.len == 0);
pool.release(buffer);
} else |_| {
// Also acceptable to reject zero-sized allocations
}
}
test "edge case: boundary conditions for transfer limits" {
const allocator = testing.allocator;
// Test at exact limits
const peer_id = try allocator.alloc(u8, TransferLimits.MAX_PEER_ID_LEN);
defer allocator.free(peer_id);
@memset(peer_id, 'A');
const data = try allocator.alloc(u8, 1024);
defer allocator.free(data);
@memset(data, 'B');
const message = TransferMessage{
.message_type = .handshake,
.message_id = 999,
.peer_id = peer_id,
.data = data,
.timestamp = std.time.timestamp(),
};
// Should succeed if total size is within limit
const total_size = TransferMessage.HEADER_SIZE + peer_id.len + data.len;
if (total_size <= TransferLimits.MAX_MESSAGE_SIZE) {
const serialized = try message.serialize(allocator);
defer allocator.free(serialized);
try testing.expect(serialized.len > 0);
}
}
//============================================================================
// Performance/Stress Tests
//============================================================================
test "stress: multiple allocations within limits" {
const config = PoolConfig{
.max_single_allocation = 1024 * 1024, // 1MB
.max_chunks = 100,
};
var pool = BufferPool.init(config, testing.allocator);
defer pool.deinit();
// Allocate and release many buffers
var i: usize = 0;
while (i < 50) : (i += 1) {
const size = (i + 1) * 1024; // 1KB, 2KB, 3KB, ...
if (size <= config.max_single_allocation) {
const buffer = try pool.acquire(size);
pool.release(buffer);
}
}
// Check pool stats
const stats = pool.stats();
try testing.expect(stats.total_chunks > 0);
}
test "stress: rapid allocation and deallocation" {
const config = PoolConfig{
.min_chunk_size = 512,
.max_chunk_size = 4096,
.max_single_allocation = 8192,
.initial_chunks = 4,
.max_chunks = 20,
};
var pool = BufferPool.init(config, testing.allocator);
defer pool.deinit();
var buffers: [10][]u8 = undefined;
// Allocate 10 buffers
for (&buffers, 0..) |*buf, idx| {
buf.* = try pool.acquire(1024 + idx * 128);
}
// Release them in reverse order
var idx: usize = buffers.len;
while (idx > 0) {
idx -= 1;
pool.release(buffers[idx]);
}
// Verify pool is in good state
const stats = pool.stats();
try testing.expect(stats.free_chunks + stats.used_chunks == stats.total_chunks);
}

View File

@@ -0,0 +1,461 @@
//! Tests for connection abstraction module
const std = @import("std");
const testing = std.testing;
const Connection = @import("../../src/core/connection.zig").Connection;
const ConnectionConfig = @import("../../src/core/connection.zig").ConnectionConfig;
const ConnectionType = @import("../../src/core/connection.zig").ConnectionType;
const ConnectionState = @import("../../src/core/connection.zig").ConnectionState;
const ConnectionStats = @import("../../src/core/connection.zig").ConnectionStats;
const HealthStatus = @import("../../src/core/connection.zig").HealthStatus;
const HealthCheckResult = @import("../../src/core/connection.zig").HealthCheckResult;
const ConnectionPool = @import("../../src/core/connection.zig").ConnectionPool;
const PoolStats = @import("../../src/core/connection.zig").PoolStats;
const Address = @import("../../src/core/address.zig").Address;
const Buffer = @import("../../src/core/buffer.zig");
test "connection configuration" {
const config = ConnectionConfig{
.connection_type = .tcp,
.buffer_size = 8192,
.timeout_ms = 10000,
.keep_alive = false,
.no_delay = false,
.max_retry_attempts = 5,
.retry_delay_ms = 2000,
.health_check_interval = 60000,
.enable_metrics = false,
};
try testing.expect(config.connection_type == .tcp);
try testing.expect(config.buffer_size == 8192);
try testing.expect(config.timeout_ms == 10000);
try testing.expect(config.max_retry_attempts == 5);
try testing.expect(config.health_check_interval == 60000);
}
test "connection creation" {
const config = ConnectionConfig{ .connection_type = .tcp };
var connection = try Connection.init(.tcp, config, testing.allocator);
defer connection.deinit();
// Test initial state
try testing.expect(connection.getState() == .disconnected);
try testing.expect(connection.getType() == .tcp);
try testing.expect(connection.getId() > 0);
try testing.expect(connection.isActive() == false);
// Test created timestamp
try testing.expect(connection.created_at > 0);
// Test initial stats
const stats = connection.getStats();
try testing.expectEqual(@as(u64, 0), stats.getBytesSent());
try testing.expectEqual(@as(u64, 0), stats.getBytesReceived());
}
test "connection statistics tracking" {
const config = ConnectionConfig{ .connection_type = .udp };
var connection = try Connection.init(.udp, config, testing.allocator);
defer connection.deinit();
const stats = connection.getStats();
// Test initial statistics
try testing.expectEqual(@as(u64, 0), stats.getBytesSent());
try testing.expectEqual(@as(u64, 0), stats.getBytesReceived());
try testing.expectEqual(@as(u64, 0), stats.getMessagesSent());
try testing.expectEqual(@as(u64, 0), stats.getMessagesReceived());
try testing.expectEqual(@as(u64, 0), stats.getConnectionAttempts());
try testing.expectEqual(@as(u64, 0), stats.getSuccessfulConnections());
try testing.expectEqual(@as(u64, 0), stats.getFailedConnections());
// Test stat recording
stats.recordSend(100, 2);
stats.recordReceive(200, 1);
stats.recordConnectionAttempt();
stats.recordSuccessfulConnection();
stats.recordFailedConnection();
stats.recordError();
try testing.expectEqual(@as(u64, 100), stats.getBytesSent());
try testing.expectEqual(@as(u64, 200), stats.getBytesReceived());
try testing.expectEqual(@as(u64, 2), stats.getMessagesSent());
try testing.expectEqual(@as(u64, 1), stats.getMessagesReceived());
try testing.expectEqual(@as(u64, 1), stats.getConnectionAttempts());
try testing.expectEqual(@as(u64, 1), stats.getSuccessfulConnections());
try testing.expectEqual(@as(u64, 1), stats.getFailedConnections());
try testing.expectEqual(@as(u64, 1), stats.getErrors());
// Test activity timestamps
try testing.expect(stats.getLastActivity() > 0);
try testing.expect(stats.getUptime() > 0);
}
test "connection state transitions" {
const config = ConnectionConfig{ .connection_type = .tcp };
var connection = try Connection.init(.tcp, config, testing.allocator);
defer connection.deinit();
// Initial state
try testing.expect(connection.getState() == .disconnected);
// Connect to local address (should work for testing)
const addr = try Address.parse("127.0.0.1:0");
try connection.connect(addr);
// After successful connect, should be in connected state
try testing.expect(connection.getState() == .connected);
// Disconnect
try connection.disconnect();
try testing.expect(connection.getState() == .closed);
}
test "connection health checking" {
const config = ConnectionConfig{ .connection_type = .udp };
var connection = try Connection.init(.udp, config, testing.allocator);
defer connection.deinit();
// Test health check when disconnected
const result1 = connection.checkHealth();
try testing.expect(result1.status == .unhealthy);
try testing.expect(result1.error != null);
// Connect to local address
const addr = try Address.parse("127.0.0.1:0");
try connection.connect(addr);
// Test health check when connected
const result2 = connection.checkHealth();
try testing.expect(result2.status == .healthy or result2.status == .degraded);
// Test health status update
connection.updateHealthStatus(result2);
try testing.expect(connection.getHealthStatus() == result2.status);
// Test needs health check
try testing.expect(connection.needsHealthCheck() == true);
}
test "connection health status management" {
const config = ConnectionConfig{ .connection_type = .tcp };
var connection = try Connection.init(.tcp, config, testing.allocator);
defer connection.deinit();
// Test initial health status
try testing.expect(connection.getHealthStatus() == .unknown);
// Test healthy status
const healthy_result = HealthCheckResult.healthy(10);
connection.updateHealthStatus(healthy_result);
try testing.expect(connection.getHealthStatus() == .healthy);
// Test degraded status
const degraded_result = HealthCheckResult.degraded(1000, Connection.Error.ConnectionTimeout);
connection.updateHealthStatus(degraded_result);
try testing.expect(connection.getHealthStatus() == .degraded);
// Test unhealthy status
const unhealthy_result = HealthCheckResult.unhealthy(Connection.Error.ConnectionClosed);
connection.updateHealthStatus(unhealthy_result);
try testing.expect(connection.getHealthStatus() == .unhealthy);
}
test "connection data operations" {
const config = ConnectionConfig{ .connection_type = .udp };
var connection = try Connection.init(.udp, config, testing.allocator);
defer connection.deinit();
// Connect to local address
const addr = try Address.parse("127.0.0.1:0");
try connection.connect(addr);
// Test send operation
const test_data = "Test message";
try connection.send(test_data);
// Test send to specific address (UDP)
const send_addr = try Address.parse("127.0.0.1:0");
try connection.sendTo(test_data, send_addr);
// Test receive operation (may timeout or return no data)
var receive_buffer: [1024]u8 = undefined;
const received = connection.receive(&receive_buffer) catch |err| {
// Expected to fail in test environment
if (err == Connection.Error.ConnectionTimeout or
err == Connection.Error.ConnectionClosed) {
return;
}
return err;
};
_ = received; // May not receive data in test environment
}
test "connection buffer management" {
const config = ConnectionConfig{
.connection_type = .tcp,
.buffer_size = 1024,
};
var connection = try Connection.init(.tcp, config, testing.allocator);
defer connection.deinit();
// Test buffer creation
const send_buffer = try connection.createSendBuffer();
try testing.expect(send_buffer.base.capacity >= 1024);
send_buffer.release();
const receive_buffer = try connection.createReceiveBuffer();
try testing.expect(receive_buffer.base.capacity >= 1024);
receive_buffer.release();
}
test "connection error handling" {
const config = ConnectionConfig{ .connection_type = .tcp };
var connection = try Connection.init(.tcp, config, testing.allocator);
defer connection.deinit();
// Test operations on disconnected connection
try testing.expectError(Connection.Error.InvalidConnectionState, connection.send("data"));
// Test send buffer on disconnected connection
const buffer = try connection.createSendBuffer();
try testing.expectError(Connection.Error.InvalidConnectionState, connection.sendBuffer(buffer));
buffer.release();
// Test duplicate connection
const addr = try Address.parse("127.0.0.1:0");
try connection.connect(addr);
try testing.expectError(Connection.Error.ConnectionAlreadyExists, connection.connect(addr));
}
test "connection pool operations" {
const config = ConnectionConfig{ .connection_type = .tcp };
var pool = ConnectionPool.init(config, testing.allocator);
defer pool.deinit();
// Test creating connections
const conn1 = try pool.createConnection(.tcp);
const conn2 = try pool.createConnection(.udp);
const conn3 = try pool.createConnection(.tcp);
try testing.expectEqual(@as(usize, 3), pool.connections.items.len);
// Test finding connection by address (should be null since not connected)
const addr = try Address.parse("127.0.0.1:0");
try testing.expect(pool.findConnectionByAddress(addr) == null);
// Test pool statistics
const stats = pool.getPoolStats();
try testing.expectEqual(@as(usize, 3), stats.total_connections);
try testing.expectEqual(@as(usize, 0), stats.active_connections);
try testing.expectEqual(@as(usize, 3), stats.disconnected_connections);
// Test removing connection
pool.removeConnection(conn2);
try testing.expectEqual(@as(usize, 2), pool.connections.items.len);
}
test "connection pool active connections" {
const config = ConnectionConfig{ .connection_type = .tcp };
var pool = ConnectionPool.init(config, testing.allocator);
defer pool.deinit();
// Create connections
const conn1 = try pool.createConnection(.tcp);
const conn2 = try pool.createConnection(.udp);
// Connect one of them
const addr = try Address.parse("127.0.0.1:0");
try conn1.connect(addr);
// Get active connections
const active = try pool.getActiveConnections();
defer active.deinit();
try testing.expect(active.items.len >= 1);
}
test "connection types" {
try testing.expectEqual(@as(u8, 1), @intFromEnum(ConnectionType.tcp));
try testing.expectEqual(@as(u8, 2), @intFromEnum(ConnectionType.udp));
try testing.expectEqual(@as(u8, 3), @intFromEnum(ConnectionType.unix_stream));
try testing.expectEqual(@as(u8, 4), @intFromEnum(ConnectionType.unix_dgram));
}
test "connection states" {
try testing.expectEqual(@as(u8, 0), @intFromEnum(ConnectionState.disconnected));
try testing.expectEqual(@as(u8, 1), @intFromEnum(ConnectionState.connecting));
try testing.expectEqual(@as(u8, 2), @intFromEnum(ConnectionState.connected));
try testing.expectEqual(@as(u8, 3), @intFromEnum(ConnectionState.closing));
try testing.expectEqual(@as(u8, 4), @intFromEnum(ConnectionState.closed));
try testing.expectEqual(@as(u8, 5), @intFromEnum(ConnectionState.error));
}
test "health check result creation" {
// Test healthy result
const healthy = HealthCheckResult.healthy(10);
try testing.expect(healthy.status == .healthy);
try testing.expect(healthy.latency_ms == 10);
try testing.expect(healthy.error == null);
try testing.expect(healthy.timestamp > 0);
// Test degraded result
const degraded = HealthCheckResult.degraded(1000, Connection.Error.ConnectionTimeout);
try testing.expect(degraded.status == .degraded);
try testing.expect(degraded.latency_ms == 1000);
try testing.expect(degraded.error != null);
try testing.expect(degraded.error == Connection.Error.ConnectionTimeout);
// Test unhealthy result
const unhealthy = HealthCheckResult.unhealthy(Connection.Error.ConnectionClosed);
try testing.expect(unhealthy.status == .unhealthy);
try testing.expect(unhealthy.latency_ms == -1);
try testing.expect(unhealthy.error != null);
try testing.expect(unhealthy.error == Connection.Error.ConnectionClosed);
}
test "connection uptime calculation" {
const config = ConnectionConfig{ .connection_type = .tcp };
var connection = try Connection.init(.tcp, config, testing.allocator);
defer connection.deinit();
// Test uptime when not connected
try testing.expectEqual(@as(i64, 0), connection.getUptime());
// Connect and test uptime
const addr = try Address.parse("127.0.0.1:0");
try connection.connect(addr);
const uptime = connection.getUptime();
try testing.expect(uptime >= 0);
// Small delay and check uptime increases
std.time.sleep(1_000_000); // 1 millisecond
const new_uptime = connection.getUptime();
try testing.expect(new_uptime >= uptime);
}
test "connection graceful shutdown" {
const config = ConnectionConfig{ .connection_type = .tcp };
var connection = try Connection.init(.tcp, config, testing.allocator);
defer connection.deinit();
// Test graceful shutdown when disconnected
try connection.gracefulShutdown(1000);
try testing.expect(connection.getState() == .closed);
// Test graceful shutdown when connected
const addr = try Address.parse("127.0.0.1:0");
try connection.connect(addr);
try connection.gracefulShutdown(1000);
try testing.expect(connection.getState() == .closed);
}
test "connection address management" {
const config = ConnectionConfig{ .connection_type = .tcp };
var connection = try Connection.init(.tcp, config, testing.allocator);
defer connection.deinit();
// Test initial address state
try testing.expect(connection.getLocalAddress() == null);
try testing.expect(connection.getRemoteAddress() == null);
// Connect to set addresses
const addr = try Address.parse("127.0.0.1:0");
try connection.connect(addr);
const local_addr = connection.getLocalAddress();
const remote_addr = connection.getRemoteAddress();
try testing.expect(local_addr != null);
try testing.expect(remote_addr != null);
// UDP connection should have local address but no remote address
var udp_connection = try Connection.init(.udp, config, testing.allocator);
defer udp_connection.deinit();
try udp_connection.connect(addr);
const udp_local = udp_connection.getLocalAddress();
const udp_remote = udp_connection.getRemoteAddress();
try testing.expect(udp_local != null);
try testing.expect(udp_remote != null);
}
test "connection pool statistics accuracy" {
const config = ConnectionConfig{ .connection_type = .tcp };
var pool = ConnectionPool.init(config, testing.allocator);
defer pool.deinit();
// Create connections with different states
const conn1 = try pool.createConnection(.tcp);
const conn2 = try pool.createConnection(.udp);
const conn3 = try pool.createConnection(.tcp);
// Connect some of them
const addr = try Address.parse("127.0.0.1:0");
try conn1.connect(addr);
try conn3.connect(addr);
// Check pool statistics
const stats = pool.getPoolStats();
try testing.expectEqual(@as(usize, 3), stats.total_connections);
try testing.expectEqual(@as(usize, 2), stats.active_connections);
try testing.expectEqual(@as(usize, 1), stats.disconnected_connections);
// Test bytes statistics
conn1.getStats().recordSend(100, 1);
conn2.getStats().recordSend(200, 1);
conn3.getStats().recordReceive(150, 1);
const updated_stats = pool.getPoolStats();
try testing.expectEqual(@as(u64, 300), updated_stats.total_bytes_sent);
try testing.expectEqual(@as(u64, 150), updated_stats.total_bytes_received);
}
test "connection retry logic simulation" {
const config = ConnectionConfig{
.connection_type = .tcp,
.max_retry_attempts = 3,
.retry_delay_ms = 100,
};
var connection = try Connection.init(.tcp, config, testing.allocator);
defer connection.deinit();
// Test that configuration is stored correctly
try testing.expect(connection.config.max_retry_attempts == 3);
try testing.expect(connection.config.retry_delay_ms == 100);
// In a real implementation, retry logic would be tested here
// For now, we just verify the configuration is accessible
}
test "connection metrics and monitoring" {
const config = ConnectionConfig{
.connection_type = .tcp,
.enable_metrics = true,
};
var connection = try Connection.init(.tcp, config, testing.allocator);
defer connection.deinit();
const stats = connection.getStats();
// Test health check metrics
stats.recordHealthCheck();
try testing.expectEqual(@as(u64, 1), stats.getHealthChecks());
// Test connection attempt metrics
stats.recordConnectionAttempt();
stats.recordSuccessfulConnection();
stats.recordFailedConnection();
try testing.expectEqual(@as(u64, 1), stats.getConnectionAttempts());
try testing.expectEqual(@as(u64, 1), stats.getSuccessfulConnections());
try testing.expectEqual(@as(u64, 1), stats.getFailedConnections());
}

View File

@@ -0,0 +1,377 @@
const std = @import("std");
const testing = std.testing;
const core = @import("core");
const Connection = core.connection.Connection;
const ConnectionType = core.connection.ConnectionType;
const ConnectionState = core.connection.ConnectionState;
const ConnectionConfig = core.connection.ConnectionConfig;
const ConnectionPool = core.connection.ConnectionPool;
const ConnectionStats = core.connection.ConnectionStats;
const HealthStatus = core.connection.HealthStatus;
const Address = core.address.Address;
const Error = core.errors.Error;
test "connection: create TCP connection succeeds" {
const allocator = testing.allocator;
const config = ConnectionConfig{ .connection_type = .tcp };
var conn = try Connection.init(.tcp, config, allocator);
defer conn.deinit();
try testing.expectEqual(ConnectionState.disconnected, conn.state);
try testing.expectEqual(ConnectionType.tcp, conn.connection_type);
}
test "connection: create UDP connection succeeds" {
const allocator = testing.allocator;
const config = ConnectionConfig{ .connection_type = .udp };
var conn = try Connection.init(.udp, config, allocator);
defer conn.deinit();
try testing.expectEqual(ConnectionType.udp, conn.connection_type);
}
test "connection: connection has unique ID" {
const allocator = testing.allocator;
const config = ConnectionConfig{ .connection_type = .tcp };
var conn1 = try Connection.init(.tcp, config, allocator);
defer conn1.deinit();
var conn2 = try Connection.init(.tcp, config, allocator);
defer conn2.deinit();
try testing.expect(conn1.getId() != conn2.getId());
}
test "connection: stats initialization" {
const allocator = testing.allocator;
const config = ConnectionConfig{ .connection_type = .tcp };
var conn = try Connection.init(.tcp, config, allocator);
defer conn.deinit();
const stats = conn.getStats();
try testing.expectEqual(@as(u64, 0), stats.getBytesSent());
try testing.expectEqual(@as(u64, 0), stats.getBytesReceived());
try testing.expectEqual(@as(u64, 0), stats.getConnectionAttempts());
}
test "connection: stats record send" {
const allocator = testing.allocator;
const config = ConnectionConfig{ .connection_type = .tcp };
var conn = try Connection.init(.tcp, config, allocator);
defer conn.deinit();
const stats = conn.getStatsMut();
stats.recordSend(1024, 1);
try testing.expectEqual(@as(u64, 1024), conn.getStats().getBytesSent());
try testing.expectEqual(@as(u64, 1), conn.getStats().getMessagesSent());
}
test "connection: stats record receive" {
const allocator = testing.allocator;
const config = ConnectionConfig{ .connection_type = .tcp };
var conn = try Connection.init(.tcp, config, allocator);
defer conn.deinit();
const stats = conn.getStatsMut();
stats.recordReceive(2048, 2);
try testing.expectEqual(@as(u64, 2048), conn.getStats().getBytesReceived());
try testing.expectEqual(@as(u64, 2), conn.getStats().getMessagesReceived());
}
test "connection: stats record connection attempt" {
const allocator = testing.allocator;
const config = ConnectionConfig{ .connection_type = .tcp };
var conn = try Connection.init(.tcp, config, allocator);
defer conn.deinit();
const stats = conn.getStatsMut();
stats.recordConnectionAttempt();
try testing.expectEqual(@as(u64, 1), conn.getStats().getConnectionAttempts());
}
test "connection: stats record successful connection" {
const allocator = testing.allocator;
const config = ConnectionConfig{ .connection_type = .tcp };
var conn = try Connection.init(.tcp, config, allocator);
defer conn.deinit();
const stats = conn.getStatsMut();
stats.recordSuccessfulConnection();
try testing.expectEqual(@as(u64, 1), conn.getStats().getSuccessfulConnections());
}
test "connection: stats record failed connection" {
const allocator = testing.allocator;
const config = ConnectionConfig{ .connection_type = .tcp };
var conn = try Connection.init(.tcp, config, allocator);
defer conn.deinit();
const stats = conn.getStatsMut();
stats.recordFailedConnection();
try testing.expectEqual(@as(u64, 1), conn.getStats().getFailedConnections());
}
test "connection: stats record error" {
const allocator = testing.allocator;
const config = ConnectionConfig{ .connection_type = .tcp };
var conn = try Connection.init(.tcp, config, allocator);
defer conn.deinit();
const stats = conn.getStatsMut();
stats.recordError();
try testing.expectEqual(@as(u64, 1), conn.getStats().getErrors());
}
test "connection: state machine from disconnected to failed" {
const allocator = testing.allocator;
const config = ConnectionConfig{ .connection_type = .tcp };
var conn = try Connection.init(.tcp, config, allocator);
defer conn.deinit();
try testing.expectEqual(ConnectionState.disconnected, conn.getState());
// Try to connect to invalid address
const addr = try Address.parse("127.0.0.1:59999");
_ = conn.connect(addr) catch {};
try testing.expectEqual(ConnectionState.failed, conn.getState());
}
test "connection: UDP connection state transitions" {
const allocator = testing.allocator;
const config = ConnectionConfig{ .connection_type = .udp };
var conn = try Connection.init(.udp, config, allocator);
defer conn.deinit();
try testing.expectEqual(ConnectionState.disconnected, conn.getState());
const addr = try Address.parse("127.0.0.1:0");
try conn.connect(addr);
try testing.expectEqual(ConnectionState.connected, conn.getState());
}
test "connection: disconnect closes connection" {
const allocator = testing.allocator;
const config = ConnectionConfig{ .connection_type = .udp };
var conn = try Connection.init(.udp, config, allocator);
defer conn.deinit();
const addr = try Address.parse("127.0.0.1:0");
try conn.connect(addr);
try conn.disconnect();
try testing.expectEqual(ConnectionState.closed, conn.getState());
}
test "connection: send on disconnected connection fails" {
const allocator = testing.allocator;
const config = ConnectionConfig{ .connection_type = .tcp };
var conn = try Connection.init(.tcp, config, allocator);
defer conn.deinit();
const result = conn.send("test");
try testing.expectError(Error.InvalidConnectionState, result);
}
test "connection: isActive returns false for disconnected" {
const allocator = testing.allocator;
const config = ConnectionConfig{ .connection_type = .tcp };
var conn = try Connection.init(.tcp, config, allocator);
defer conn.deinit();
try testing.expect(!conn.isActive());
}
test "connection: isActive returns true for connected" {
const allocator = testing.allocator;
const config = ConnectionConfig{ .connection_type = .udp };
var conn = try Connection.init(.udp, config, allocator);
defer conn.deinit();
const addr = try Address.parse("127.0.0.1:0");
try conn.connect(addr);
try testing.expect(conn.isActive());
}
test "connection: health check on disconnected returns unhealthy" {
const allocator = testing.allocator;
const config = ConnectionConfig{ .connection_type = .tcp };
var conn = try Connection.init(.tcp, config, allocator);
defer conn.deinit();
const health = conn.checkHealth();
try testing.expectEqual(HealthStatus.unhealthy, health.status);
}
test "connection: health check on connected UDP returns healthy" {
const allocator = testing.allocator;
const config = ConnectionConfig{ .connection_type = .udp };
var conn = try Connection.init(.udp, config, allocator);
defer conn.deinit();
const addr = try Address.parse("127.0.0.1:0");
try conn.connect(addr);
const health = conn.checkHealth();
try testing.expectEqual(HealthStatus.healthy, health.status);
}
test "connection: update health status changes connection state" {
const allocator = testing.allocator;
const config = ConnectionConfig{ .connection_type = .tcp };
var conn = try Connection.init(.tcp, config, allocator);
defer conn.deinit();
const health = conn.checkHealth();
conn.updateHealthStatus(health);
try testing.expectEqual(HealthStatus.unhealthy, conn.getHealthStatus());
}
test "connection: graceful shutdown on disconnected is safe" {
const allocator = testing.allocator;
const config = ConnectionConfig{ .connection_type = .tcp };
var conn = try Connection.init(.tcp, config, allocator);
defer conn.deinit();
try conn.gracefulShutdown(1000);
try testing.expectEqual(ConnectionState.disconnected, conn.getState());
}
test "connection pool: create and destroy" {
const allocator = testing.allocator;
const config = ConnectionConfig{ .connection_type = .tcp };
var pool = ConnectionPool.init(config, allocator);
defer pool.deinit();
try testing.expectEqual(@as(usize, 0), pool.connections.items.len);
}
test "connection pool: create connection" {
const allocator = testing.allocator;
const config = ConnectionConfig{ .connection_type = .tcp };
var pool = ConnectionPool.init(config, allocator);
defer pool.deinit();
_ = try pool.createConnection(.tcp);
try testing.expectEqual(@as(usize, 1), pool.connections.items.len);
}
test "connection pool: create multiple connections" {
const allocator = testing.allocator;
const config = ConnectionConfig{ .connection_type = .tcp };
var pool = ConnectionPool.init(config, allocator);
defer pool.deinit();
_ = try pool.createConnection(.tcp);
_ = try pool.createConnection(.udp);
try testing.expectEqual(@as(usize, 2), pool.connections.items.len);
}
test "connection pool: remove connection" {
const allocator = testing.allocator;
const config = ConnectionConfig{ .connection_type = .tcp };
var pool = ConnectionPool.init(config, allocator);
defer pool.deinit();
const conn = try pool.createConnection(.tcp);
pool.removeConnection(conn);
try testing.expectEqual(@as(usize, 0), pool.connections.items.len);
}
test "connection pool: get active connections" {
const allocator = testing.allocator;
const config = ConnectionConfig{ .connection_type = .udp };
var pool = ConnectionPool.init(config, allocator);
defer pool.deinit();
const conn = try pool.createConnection(.udp);
const addr = try Address.parse("127.0.0.1:0");
try conn.connect(addr);
var active = try pool.getActiveConnections();
defer active.deinit(allocator);
try testing.expectEqual(@as(usize, 1), active.items.len);
}
test "connection pool: pool stats tracking" {
const allocator = testing.allocator;
const config = ConnectionConfig{ .connection_type = .tcp };
var pool = ConnectionPool.init(config, allocator);
defer pool.deinit();
_ = try pool.createConnection(.tcp);
_ = try pool.createConnection(.tcp);
const stats = pool.getPoolStats();
try testing.expectEqual(@as(usize, 2), stats.total_connections);
}
test "connection: buffer creation" {
const allocator = testing.allocator;
const config = ConnectionConfig{
.connection_type = .tcp,
.buffer_size = 4096,
};
var conn = try Connection.init(.tcp, config, allocator);
defer conn.deinit();
var buffer = try conn.createSendBuffer();
defer buffer.release();
try testing.expect(buffer.base.capacity >= 4096);
}
test "connection: concurrent stats updates" {
const allocator = testing.allocator;
const config = ConnectionConfig{ .connection_type = .tcp };
var conn = try Connection.init(.tcp, config, allocator);
defer conn.deinit();
const stats = conn.getStatsMut();
stats.recordSend(100, 1);
stats.recordSend(200, 1);
stats.recordReceive(300, 1);
try testing.expectEqual(@as(u64, 300), conn.getStats().getBytesSent());
try testing.expectEqual(@as(u64, 2), conn.getStats().getMessagesSent());
try testing.expectEqual(@as(u64, 300), conn.getStats().getBytesReceived());
}

129
tests/core/test_error.zig Normal file
View File

@@ -0,0 +1,129 @@
//! Tests for error handling module
const std = @import("std");
const testing = std.testing;
const Error = @import("../../src/core/error.zig").Error;
const ErrorInfo = @import("../../src/core/error.zig").ErrorInfo;
const ErrorContext = @import("../../src/core/error.zig").ErrorContext;
const ErrorResult = @import("../../src/core/error.zig").ErrorResult;
const ErrorStats = @import("../../src/core/error.zig").ErrorStats;
test "error basic operations" {
// Test error propagation
const test_fn = fn() Error!void {
return Error.ConnectionRefused;
};
const result = test_fn();
try testing.expectError(Error.ConnectionRefused, result);
}
test "error context operations" {
var context = ErrorContext.init("connect", "network");
try testing.expectEqualSlices(u8, "connect", context.operation);
try testing.expectEqualSlices(u8, "network", context.component);
try testing.expect(context.peer_id == null);
try testing.expect(context.connection_id == null);
context = context.withPeerId("peer123");
try testing.expectEqualSlices(u8, "peer123", context.peer_id.?);
context = context.withConnectionId("conn456");
try testing.expectEqualSlices(u8, "conn456", context.connection_id.?);
}
test "error result creation" {
const context = ErrorContext.init("send", "transport");
const error_result = ErrorResult.create(
Error.ConnectionRefused,
"Connection failed",
context,
"test.zig",
42,
"test_function",
);
try testing.expect(Error.ConnectionRefused == error_result.error);
try testing.expect(error_result.info.message.len > 0);
}
test "error string conversion" {
try testing.expectEqualSlices(u8, "ConnectionRefused", Error.toString(Error.ConnectionRefused));
try testing.expectEqualSlices(u8, "NetworkError", Error.toString(Error.NetworkError));
try testing.expectEqualSlices(u8, "AddressInUse", Error.toString(Error.AddressInUse));
}
test "error conversion helpers" {
try testing.expect(Error.ConnectionRefused == Error.fromInt(-2));
try testing.expect(Error.AddressInUse == Error.fromInt(-3));
try testing.expect(Error.NetworkError == Error.fromInt(-1));
}
test "assert operations" {
// Test successful assertion
const result = Error.assertWithError(true, Error.ConnectionRefused, "should not error");
try testing.expect(result == void);
// Test failed assertion
const error_result = Error.assertWithError(false, Error.ConnectionRefused, "should error");
try testing.expectError(Error.ConnectionRefused, error_result);
}
test "error stats operations" {
var stats = ErrorStats.init();
// Test initial state
try testing.expectEqual(@as(u64, 0), stats.getTotal());
try testing.expectEqual(@as(u64, 0), stats.getCount(Error.ConnectionRefused));
// Record some errors
stats.record(Error.ConnectionRefused);
stats.record(Error.ConnectionRefused);
stats.record(Error.AddressInUse);
// Verify statistics
try testing.expectEqual(@as(u64, 3), stats.getTotal());
try testing.expectEqual(@as(u64, 2), stats.getCount(Error.ConnectionRefused));
try testing.expectEqual(@as(u64, 1), stats.getCount(Error.AddressInUse));
try testing.expectEqual(@as(u64, 0), stats.getCount(Error.NetworkError));
// Test utilization calculation
const utilization = stats.utilization();
try testing.expect(utilization >= 0.0 and utilization <= 1.0);
}
test "global error statistics" {
var stats = ErrorStats.init();
Error.setGlobalErrorStats(&stats);
try testing.expect(Error.getGlobalErrorStats() == &stats);
// Record global errors
Error.recordGlobalError(Error.ConnectionRefused);
Error.recordGlobalError(Error.AddressInUse);
Error.recordGlobalError(Error.ConnectionRefused);
// Verify global stats
try testing.expectEqual(@as(u64, 3), stats.getTotal());
try testing.expectEqual(@as(u64, 2), stats.getCount(Error.ConnectionRefused));
try testing.expectEqual(@as(u64, 1), stats.getCount(Error.AddressInUse));
}
test "error wrapping" {
const wrapped = Error.wrapError(Error.ConnectionRefused, Error.NetworkError);
try testing.expectError(Error.ConnectionRefused, wrapped);
}
test "macros and utilities" {
// Test error creation macro
const err = Error.err(Error.ConnectionRefused, "test error", .{});
try testing.expect(Error.ConnectionRefused == err);
// Test unexpected macro
_ = Error.assert(true, "should not panic");
// Test unreachable macro
// This would panic if called, so we just verify it exists
_ = Error.unreachable;
}

71
tests/core/test_main.zig Normal file
View File

@@ -0,0 +1,71 @@
//! Main test runner for core networking module
//!
//! This file imports and runs all core networking tests.
const std = @import("std");
const testing = std.testing;
const ErrorTests = @import("test_error.zig");
const AddressTests = @import("test_address.zig");
const BufferTests = @import("test_buffer.zig");
const SocketTests = @import("test_socket.zig");
const ConnectionTests = @import("test_connection.zig");
// Export all test functions for the test runner
pub usingnamespace ErrorTests;
pub usingnamespace AddressTests;
pub usingnamespace BufferTests;
pub usingnamespace SocketTests;
pub usingnamespace ConnectionTests;
pub fn main() !void {
// Run all tests
testing.main();
}
// Test all core modules
test "all core networking tests" {
// This test ensures all modules are properly integrated
// and can work together
// Test error module integration
try ErrorTests.test_error_basic_operations();
try ErrorTests.test_error_context_operations();
try ErrorTests.test_error_stats_operations();
// Test address module integration
try AddressTests.test_ipv4_address_creation_and_parsing();
try AddressTests.test_ipv4_address_properties();
try AddressTests.test_ipv6_address_creation_and_operations();
try AddressTests.test_unix_socket_address();
try AddressTests.test_address_parsing_various_formats();
try AddressTests.test_address_validation();
try AddressTests.test_address_list_operations();
try AddressTests.test_address_system_conversion();
// Test buffer module integration
try BufferTests.test_buffer_pool_configuration();
try BufferTests.test_buffer_pool_creation_and_basic_operations();
try BufferTests.test_stream_buffer_creation_and_operations();
try BufferTests.test_packet_buffer_operations();
try BufferTests.test_message_buffer_operations();
try BufferTests.test_buffer_manager_operations();
// Test socket module integration
try SocketTests.test_socket_factory_creation();
try SocketTests.test_socket_creation_with_config();
try SocketTests.test_socket_state_management();
try SocketTests.test_socket_binding();
try SocketTests.test_socket_listening();
try SocketTests.test_socket_options();
try SocketTests.test_socket_statistics();
try SocketTests.test_socket_manager_operations();
// Test connection module integration
try ConnectionTests.test_connection_configuration();
try ConnectionTests.test_connection_creation();
try ConnectionTests.test_connection_statistics_tracking();
try ConnectionTests.test_connection_state_transitions();
try ConnectionTests.test_connection_health_checking();
try ConnectionTests.test_connection_pool_operations();
}

392
tests/core/test_socket.zig Normal file
View File

@@ -0,0 +1,392 @@
//! Tests for socket management module
const std = @import("std");
const testing = std.testing;
const Socket = @import("../../src/core/socket.zig").Socket;
const SocketConfig = @import("../../src/core/socket.zig").SocketConfig;
const SocketProtocol = @import("../../src/core/socket.zig").SocketProtocol;
const SocketOption = @import("../../src/core/socket.zig").SocketOption;
const SocketState = @import("../../src/core/socket.zig").SocketState;
const SocketStats = @import("../../src/core/socket.zig").SocketStats;
const SocketFactory = @import("../../src/core/socket.zig").SocketFactory;
const SocketManager = @import("../../src/core/socket.zig").SocketManager;
const Address = @import("../../src/core/address.zig").Address;
test "socket protocol types" {
try testing.expectEqual(@as(u8, 1), @intFromEnum(SocketProtocol.tcp));
try testing.expectEqual(@as(u8, 2), @intFromEnum(SocketProtocol.udp));
try testing.expectEqual(@as(u8, 3), @intFromEnum(SocketProtocol.unix_stream));
try testing.expectEqual(@as(u8, 4), @intFromEnum(SocketProtocol.unix_dgram));
}
test "socket configuration" {
const config = SocketConfig{
.protocol = .tcp,
.non_blocking = true,
.reuse_address = false,
.reuse_port = true,
.keep_alive = false,
.no_delay = false,
.buffer_size = 8192,
.timeout_ms = 5000,
.multicast_ttl = 2,
};
try testing.expect(config.protocol == .tcp);
try testing.expect(config.non_blocking == true);
try testing.expect(config.reuse_address == false);
try testing.expect(config.reuse_port == true);
try testing.expect(config.buffer_size == 8192);
try testing.expect(config.timeout_ms == 5000);
}
test "socket factory creation" {
var factory = SocketFactory.init(testing.allocator);
// Test TCP socket creation
const tcp_socket = try factory.createTcpSocket();
try testing.expect(tcp_socket.getState() == .created);
try testing.expect(tcp_socket.getStats().bytes_sent == 0);
tcp_socket.deinit();
// Test UDP socket creation
const udp_socket = try factory.createUdpSocket();
try testing.expect(udp_socket.getState() == .created);
udp_socket.deinit();
// Test Unix socket creation
const unix_stream = try factory.createUnixStreamSocket();
try testing.expect(unix_stream.getState() == .created);
unix_stream.deinit();
const unix_dgram = try factory.createUnixDgramSocket();
try testing.expect(unix_dgram.getState() == .created);
unix_dgram.deinit();
}
test "socket creation with config" {
const config = SocketConfig{
.protocol = .tcp,
.buffer_size = 4096,
.timeout_ms = 10000,
};
var factory = SocketFactory.init(testing.allocator);
const socket = try factory.createSocketWithConfig(config);
try testing.expect(socket.getState() == .created);
try testing.expect(socket.config.buffer_size == 4096);
socket.deinit();
}
test "socket state management" {
var socket = try Socket.init(.tcp, testing.allocator);
defer socket.deinit();
// Initial state
try testing.expect(socket.getState() == .created);
try testing.expect(socket.isValid() == false);
// Open socket
try socket.open();
try testing.expect(socket.getState() == .created); // Still created after open
try testing.expect(socket.isValid() == true);
// Close socket
try socket.close();
try testing.expect(socket.getState() == .closed);
try testing.expect(socket.isValid() == false);
}
test "socket binding" {
var socket = try Socket.init(.tcp, testing.allocator);
defer socket.deinit();
// Bind to localhost
const bind_addr = try Address.parse("127.0.0.1:0");
try socket.bind(bind_addr);
const local_addr = socket.getLocalAddress().?;
try testing.expect(local_addr.family == .ipv4);
// UDP socket binding should work differently
var udp_socket = try Socket.init(.udp, testing.allocator);
defer udp_socket.deinit();
try udp_socket.bind(bind_addr);
try testing.expect(udp_socket.getState() == .bound);
}
test "socket listening" {
var socket = try Socket.init(.tcp, testing.allocator);
defer socket.deinit();
// Bind first
const bind_addr = try Address.parse("127.0.0.1:0");
try socket.bind(bind_addr);
// Listen
try socket.listen(10);
try testing.expect(socket.getState() == .listening);
// UDP sockets can't listen
var udp_socket = try Socket.init(.udp, testing.allocator);
defer udp_socket.deinit();
try testing.expectError(Socket.Error.OperationNotSupported, udp_socket.listen(10));
}
test "socket options" {
var socket = try Socket.init(.tcp, testing.allocator);
defer socket.deinit();
// Test getting default options
const reuse_addr = try socket.getOption(.reuse_address);
try testing.expect(reuse_addr == 0 or reuse_addr == 1);
const keep_alive = try socket.getOption(.keep_alive);
try testing.expect(keep_alive == 0 or keep_alive == 1);
const buffer_size = try socket.getOption(.buffer_size);
try testing.expect(buffer_size > 0);
// Test setting options
try socket.setOption(.reuse_address, 1);
const new_reuse_addr = try socket.getOption(.reuse_address);
try testing.expect(new_reuse_addr == 1);
try socket.setOption(.keep_alive, 1);
const new_keep_alive = try socket.getOption(.keep_alive);
try testing.expect(new_keep_alive == 1);
// Test unsupported option
try testing.expectError(Socket.Error.OperationNotSupported, socket.getOption(.multicast_ttl));
}
test "socket statistics" {
var socket = try Socket.init(.udp, testing.allocator);
defer socket.deinit();
const stats = socket.getStats();
// Test initial stats
try testing.expectEqual(@as(u64, 0), stats.bytes_sent);
try testing.expectEqual(@as(u64, 0), stats.bytes_received);
try testing.expectEqual(@as(u64, 0), stats.packets_sent);
try testing.expectEqual(@as(u64, 0), stats.packets_received);
try testing.expectEqual(@as(u64, 0), stats.errors);
// Test stat recording
stats.recordSend(100);
stats.recordReceive(200);
stats.recordError();
try testing.expectEqual(@as(u64, 100), stats.bytes_sent);
try testing.expectEqual(@as(u64, 200), stats.bytes_received);
try testing.expectEqual(@as(u64, 1), stats.packets_sent);
try testing.expectEqual(@as(u64, 1), stats.packets_received);
try testing.expectEqual(@as(u64, 1), stats.errors);
// Test timestamp update
const last_activity = stats.last_activity;
try testing.expect(last_activity > 0);
}
test "socket manager operations" {
var manager = SocketManager.init(testing.allocator);
defer manager.deinit();
// Create multiple sockets
const tcp_socket = try manager.createTcpSocket();
const udp_socket = try manager.createUdpSocket();
try testing.expectEqual(@as(usize, 2), manager.sockets.items.len);
// Test socket retrieval
try testing.expect(&manager.sockets.items[0] == tcp_socket);
try testing.expect(&manager.sockets.items[1] == udp_socket);
// Test removing socket
manager.removeSocket(tcp_socket);
try testing.expectEqual(@as(usize, 1), manager.sockets.items.len);
// Verify remaining socket is UDP by checking its protocol
try testing.expectEqual(SocketProtocol.udp, manager.sockets.items[0].config.protocol);
}
test "socket manager active sockets" {
var manager = SocketManager.init(testing.allocator);
defer manager.deinit();
// Create sockets
const socket1 = try manager.createTcpSocket();
const socket2 = try manager.createUdpSocket();
// Both should be valid initially
const active_sockets = manager.getActiveSockets();
try testing.expect(active_sockets.len >= 2);
}
test "socket protocol-specific operations" {
// Test TCP socket operations
var tcp_socket = try Socket.init(.tcp, testing.allocator);
defer tcp_socket.deinit();
try testing.expectError(Socket.Error.InvalidState, tcp_socket.listen(10));
// UDP socket operations
var udp_socket = try Socket.init(.udp, testing.allocator);
defer udp_socket.deinit();
try testing.expectError(Socket.Error.InvalidState, udp_socket.accept());
// Test unsupported operations
try testing.expectError(Socket.Error.OperationNotSupported, tcp_socket.sendTo("data", try Address.parse("127.0.0.1:0")));
try testing.expectError(Socket.Error.OperationNotSupported, tcp_socket.receiveFrom(&[_]u8{0} ** 100));
}
test "socket polling and readiness" {
var socket = try Socket.init(.tcp, testing.allocator);
defer socket.deinit();
try socket.open();
// Test canRead when not connected
const can_read = socket.canRead();
// This might return true or false depending on implementation
// The important thing is that it doesn't error
_ = can_read;
const can_write = socket.canWrite();
_ = can_write;
}
test "socket address management" {
var socket = try Socket.init(.tcp, testing.allocator);
defer socket.deinit();
// Test initial address state
try testing.expect(socket.getLocalAddress() == null);
try testing.expect(socket.getRemoteAddress() == null);
// Bind to get local address
const bind_addr = try Address.parse("127.0.0.1:0");
try socket.bind(bind_addr);
const local_addr = socket.getLocalAddress();
try testing.expect(local_addr != null);
// After binding, should have local address
const bound_addr = local_addr.?;
try testing.expect(bound_addr.family == .ipv4);
}
test "socket error handling" {
var socket = try Socket.init(.tcp, testing.allocator);
defer socket.deinit();
// Test invalid state operations
try testing.expectError(Socket.Error.InvalidState, socket.accept());
try testing.expectError(Socket.Error.InvalidState, socket.connect(try Address.parse("127.0.0.1:0")));
// Test operations on closed socket
try socket.close();
try testing.expectError(Socket.Error.InvalidState, socket.send("data"));
try testing.expectError(Socket.Error.InvalidState, socket.receive(&[_]u8{0} ** 100));
}
test "socket configuration validation" {
// Test default configuration
const config = SocketConfig{ .protocol = .tcp };
try testing.expect(config.protocol == .tcp);
try testing.expect(config.non_blocking == false);
try testing.expect(config.buffer_size == 64 * 1024); // Default buffer size
try testing.expect(config.timeout_ms == 30000); // Default timeout
// Test custom configuration
const custom_config = SocketConfig{
.protocol = .udp,
.buffer_size = 8192,
.timeout_ms = 5000,
.multicast_ttl = 4,
};
try testing.expect(custom_config.protocol == .udp);
try testing.expect(custom_config.buffer_size == 8192);
try testing.expect(custom_config.timeout_ms == 5000);
try testing.expect(custom_config.multicast_ttl == 4);
}
test "socket creation errors" {
var factory = SocketFactory.init(testing.allocator);
// Test creating socket with invalid protocol (should not happen in current design)
// but test that factory methods work as expected
const tcp_socket = try factory.createTcpSocket();
try testing.expect(tcp_socket.fd >= 0 or tcp_socket.fd == -1); // Should be valid or invalid file descriptor
tcp_socket.deinit();
}
test "socket graceful cleanup" {
var socket = try Socket.init(.tcp, testing.allocator);
// Double close should be safe
try socket.close();
try socket.close(); // Should not error
}
test "socket manager cleanup" {
var manager = SocketManager.init(testing.allocator);
// Create some sockets
const socket1 = try manager.createTcpSocket();
const socket2 = try manager.createUdpSocket();
// Manager deinit should clean up all sockets
manager.deinit();
// After deinit, sockets should be closed
try testing.expect(socket1.getState() == .closed);
try testing.expect(socket2.getState() == .closed);
}
test "socket type consistency" {
var factory = SocketFactory.init(testing.allocator);
// Verify socket types are created correctly
const tcp_socket = try factory.createTcpSocket();
const udp_socket = try factory.createUdpSocket();
const unix_stream = try factory.createUnixStreamSocket();
const unix_dgram = try factory.createUnixDgramSocket();
// Check that protocol matches expected types
try testing.expect(tcp_socket.config.protocol == .tcp);
try testing.expect(udp_socket.config.protocol == .udp);
try testing.expect(unix_stream.config.protocol == .unix_stream);
try testing.expect(unix_dgram.config.protocol == .unix_dgram);
tcp_socket.deinit();
udp_socket.deinit();
unix_stream.deinit();
unix_dgram.deinit();
}
test "socket buffer operations" {
// This test would require actual buffer types from buffer.zig
// For now, just test that the methods exist and can be called
var socket = try Socket.init(.tcp, testing.allocator);
defer socket.deinit();
// These operations would normally require a buffer
// We're just testing the method signatures exist
_ = socket.canRead;
_ = socket.canWrite;
_ = socket.getStats;
_ = socket.getState;
}

View File

@@ -0,0 +1,366 @@
const std = @import("std");
const testing = std.testing;
const core = @import("core");
const Socket = core.socket.Socket;
const SocketConfig = core.socket.SocketConfig;
const SocketProtocol = core.socket.SocketProtocol;
const SocketState = core.socket.SocketState;
const SocketOption = core.socket.SocketOption;
const Address = core.address.Address;
const Error = core.errors.Error;
test "socket: create TCP socket succeeds" {
const allocator = testing.allocator;
var socket = try Socket.init(.tcp, allocator);
defer socket.deinit();
try testing.expectEqual(SocketState.created, socket.state);
try testing.expect(socket.fd == -1);
}
test "socket: create UDP socket succeeds" {
const allocator = testing.allocator;
var socket = try Socket.init(.udp, allocator);
defer socket.deinit();
try testing.expectEqual(SocketState.created, socket.state);
try testing.expectEqual(SocketProtocol.udp, socket.config.protocol);
}
test "socket: open TCP socket changes state" {
const allocator = testing.allocator;
var socket = try Socket.init(.tcp, allocator);
defer socket.deinit();
try socket.open();
try testing.expectEqual(SocketState.opened, socket.state);
try testing.expect(socket.fd >= 0);
}
test "socket: bind with valid address succeeds" {
const allocator = testing.allocator;
var socket = try Socket.init(.tcp, allocator);
defer socket.deinit();
const addr = try Address.parse("127.0.0.1:0");
try socket.bind(addr);
try testing.expectEqual(SocketState.bound, socket.state);
try testing.expect(socket.local_address != null);
}
test "socket: bind without open auto-opens socket" {
const allocator = testing.allocator;
var socket = try Socket.init(.tcp, allocator);
defer socket.deinit();
try testing.expectEqual(SocketState.created, socket.state);
const addr = try Address.parse("127.0.0.1:0");
try socket.bind(addr);
try testing.expectEqual(SocketState.bound, socket.state);
try testing.expect(socket.fd >= 0);
}
test "socket: listen on bound socket succeeds" {
const allocator = testing.allocator;
var socket = try Socket.init(.tcp, allocator);
defer socket.deinit();
const addr = try Address.parse("127.0.0.1:0");
try socket.bind(addr);
try socket.listen(10);
try testing.expectEqual(SocketState.listening, socket.state);
}
test "socket: listen on UDP socket fails" {
const allocator = testing.allocator;
var socket = try Socket.init(.udp, allocator);
defer socket.deinit();
const result = socket.listen(10);
try testing.expectError(Error.OperationNotSupported, result);
}
test "socket: send on closed socket returns error" {
const allocator = testing.allocator;
var socket = try Socket.init(.tcp, allocator);
try socket.open();
try socket.close();
const result = socket.send("test");
try testing.expectError(Error.InvalidState, result);
}
test "socket: receive on closed socket returns error" {
const allocator = testing.allocator;
var socket = try Socket.init(.tcp, allocator);
try socket.open();
try socket.close();
var buffer: [100]u8 = undefined;
const result = socket.receive(&buffer);
try testing.expectError(Error.InvalidState, result);
}
test "socket: state transitions created -> opened -> bound -> listening" {
const allocator = testing.allocator;
var socket = try Socket.init(.tcp, allocator);
defer socket.deinit();
try testing.expectEqual(SocketState.created, socket.getState());
try socket.open();
try testing.expectEqual(SocketState.opened, socket.getState());
const addr = try Address.parse("127.0.0.1:0");
try socket.bind(addr);
try testing.expectEqual(SocketState.bound, socket.getState());
try socket.listen(10);
try testing.expectEqual(SocketState.listening, socket.getState());
}
test "socket: invalid state transition fails" {
const allocator = testing.allocator;
var socket = try Socket.init(.tcp, allocator);
defer socket.deinit();
// Try to listen before binding
const result = socket.listen(10);
try testing.expectError(Error.InvalidState, result);
}
test "socket: set and get socket option" {
const allocator = testing.allocator;
var socket = try Socket.init(.tcp, allocator);
defer socket.deinit();
try socket.open();
try socket.setOption(.reuse_address, 1);
const value = try socket.getOption(.reuse_address);
try testing.expect(value != 0);
}
test "socket: set option on closed socket fails" {
const allocator = testing.allocator;
var socket = try Socket.init(.tcp, allocator);
try socket.open();
try socket.close();
const result = socket.setOption(.reuse_address, 1);
try testing.expectError(Error.InvalidState, result);
}
test "socket: socket statistics track send" {
const allocator = testing.allocator;
var socket = try Socket.init(.tcp, allocator);
defer socket.deinit();
const stats = socket.getStatsMut();
stats.recordSend(100);
try testing.expectEqual(@as(u64, 100), socket.getStats().bytes_sent);
try testing.expectEqual(@as(u64, 1), socket.getStats().packets_sent);
}
test "socket: socket statistics track receive" {
const allocator = testing.allocator;
var socket = try Socket.init(.tcp, allocator);
defer socket.deinit();
const stats = socket.getStatsMut();
stats.recordReceive(200);
try testing.expectEqual(@as(u64, 200), socket.getStats().bytes_received);
try testing.expectEqual(@as(u64, 1), socket.getStats().packets_received);
}
test "socket: socket statistics track errors" {
const allocator = testing.allocator;
var socket = try Socket.init(.tcp, allocator);
defer socket.deinit();
const stats = socket.getStatsMut();
stats.recordError();
try testing.expectEqual(@as(u64, 1), socket.getStats().errors);
}
test "socket: close socket changes state" {
const allocator = testing.allocator;
var socket = try Socket.init(.tcp, allocator);
try socket.open();
try testing.expectEqual(SocketState.opened, socket.state);
try socket.close();
try testing.expectEqual(SocketState.closed, socket.state);
}
test "socket: double close is safe" {
const allocator = testing.allocator;
var socket = try Socket.init(.tcp, allocator);
try socket.open();
try socket.close();
try socket.close(); // Should not error
try testing.expectEqual(SocketState.closed, socket.state);
}
test "socket: isValid returns false for created socket" {
const allocator = testing.allocator;
var socket = try Socket.init(.tcp, allocator);
defer socket.deinit();
try testing.expect(!socket.isValid());
}
test "socket: isValid returns true for opened socket" {
const allocator = testing.allocator;
var socket = try Socket.init(.tcp, allocator);
defer socket.deinit();
try socket.open();
try testing.expect(socket.isValid());
}
test "socket: isValid returns false for closed socket" {
const allocator = testing.allocator;
var socket = try Socket.init(.tcp, allocator);
try socket.open();
try socket.close();
try testing.expect(!socket.isValid());
}
test "socket: connect updates remote address" {
const allocator = testing.allocator;
var socket = try Socket.init(.tcp, allocator);
defer socket.deinit();
try socket.open();
// Try to connect (will fail but that's OK, we're testing address storage)
const addr = try Address.parse("127.0.0.1:9999");
_ = socket.connect(addr) catch {};
// Even if connection fails, remote address should be set
if (socket.remote_address) |remote| {
try testing.expectEqual(addr.port, remote.port);
}
}
test "socket: setNonBlocking on created socket fails" {
const allocator = testing.allocator;
var socket = try Socket.init(.tcp, allocator);
defer socket.deinit();
const result = socket.setNonBlocking(true);
try testing.expectError(Error.InvalidState, result);
}
test "socket: setNonBlocking on opened socket succeeds" {
const allocator = testing.allocator;
var socket = try Socket.init(.tcp, allocator);
defer socket.deinit();
try socket.open();
try socket.setNonBlocking(true);
try testing.expect(socket.config.non_blocking);
}
test "socket: canRead on new socket" {
const allocator = testing.allocator;
var socket = try Socket.init(.udp, allocator);
defer socket.deinit();
try socket.open();
const addr = try Address.parse("127.0.0.1:0");
try socket.bind(addr);
const can_read = try socket.canRead();
// New socket should not have data available
try testing.expect(!can_read);
}
test "socket: canWrite on new socket" {
const allocator = testing.allocator;
var socket = try Socket.init(.tcp, allocator);
defer socket.deinit();
try socket.open();
const can_write = try socket.canWrite();
// New socket should be writable
try testing.expect(can_write);
}
test "socket: UDP sendTo requires UDP protocol" {
const allocator = testing.allocator;
var tcp_socket = try Socket.init(.tcp, allocator);
defer tcp_socket.deinit();
try tcp_socket.open();
const addr = try Address.parse("127.0.0.1:9999");
const result = tcp_socket.sendTo("test", addr);
try testing.expectError(Error.OperationNotSupported, result);
}
test "socket: UDP receiveFrom requires UDP protocol" {
const allocator = testing.allocator;
var tcp_socket = try Socket.init(.tcp, allocator);
defer tcp_socket.deinit();
try tcp_socket.open();
var buffer: [100]u8 = undefined;
const result = tcp_socket.receiveFrom(&buffer);
try testing.expectError(Error.OperationNotSupported, result);
}
test "socket: config with custom buffer size" {
const allocator = testing.allocator;
const config = SocketConfig{
.protocol = .tcp,
.buffer_size = 128 * 1024,
};
var socket = try Socket.create(config, allocator);
defer socket.deinit();
try testing.expectEqual(@as(usize, 128 * 1024), socket.config.buffer_size);
}
test "socket: config with custom timeout" {
const allocator = testing.allocator;
const config = SocketConfig{
.protocol = .tcp,
.timeout_ms = 60000,
};
var socket = try Socket.create(config, allocator);
defer socket.deinit();
try testing.expectEqual(@as(u32, 60000), socket.config.timeout_ms);
}
test "socket: multiple sockets do not interfere" {
const allocator = testing.allocator;
var socket1 = try Socket.init(.tcp, allocator);
defer socket1.deinit();
var socket2 = try Socket.init(.udp, allocator);
defer socket2.deinit();
try socket1.open();
try socket2.open();
try testing.expect(socket1.fd != socket2.fd);
try testing.expectEqual(SocketProtocol.tcp, socket1.config.protocol);
try testing.expectEqual(SocketProtocol.udp, socket2.config.protocol);
}

View File

@@ -0,0 +1,576 @@
//! Thread safety tests for Core module
//!
//! This test suite verifies that the thread-safe implementations of
//! BufferPool, ConnectionPool, and SocketManager correctly handle
//! concurrent access without data corruption or race conditions.
const std = @import("std");
const testing = std.testing;
const Thread = std.Thread;
const time = std.time;
const core = @import("core");
const Buffer = core.buffer;
const Connection = core.connection;
const Socket = core.socket;
const Address = core.Address;
const Error = core.Error;
/// Test configuration
const TestConfig = struct {
num_threads: usize = 8,
operations_per_thread: usize = 100,
buffer_size: usize = 1024,
};
/// Thread context for buffer pool tests
const BufferPoolThreadContext = struct {
pool: *Buffer.BufferPool,
thread_id: usize,
operations: usize,
allocator: std.mem.Allocator,
errors: std.atomic.Value(u32),
success_count: std.atomic.Value(u32),
};
/// Thread context for connection pool tests
const ConnectionPoolThreadContext = struct {
pool: *Connection.ConnectionPool,
thread_id: usize,
operations: usize,
allocator: std.mem.Allocator,
errors: std.atomic.Value(u32),
success_count: std.atomic.Value(u32),
};
/// Thread context for socket manager tests
const SocketManagerThreadContext = struct {
manager: *Socket.SocketManager,
thread_id: usize,
operations: usize,
allocator: std.mem.Allocator,
errors: std.atomic.Value(u32),
success_count: std.atomic.Value(u32),
};
/// Worker function for concurrent buffer pool operations
fn bufferPoolWorker(context: *BufferPoolThreadContext) void {
var i: usize = 0;
while (i < context.operations) : (i += 1) {
// Acquire buffer
const buffer = context.pool.acquire(context.thread_id * 100 + 64) catch {
_ = context.errors.fetchAdd(1, .monotonic);
continue;
};
// Simulate work with the buffer
@memset(buffer, @as(u8, @truncate(context.thread_id)));
// Small delay to increase chance of race conditions
Thread.sleep(1 * time.ns_per_ms);
// Verify buffer contents
for (buffer) |byte| {
if (byte != @as(u8, @truncate(context.thread_id))) {
_ = context.errors.fetchAdd(1, .monotonic);
break;
}
}
// Release buffer
context.pool.release(buffer);
_ = context.success_count.fetchAdd(1, .monotonic);
}
}
/// Worker function for concurrent connection pool operations
fn connectionPoolWorker(context: *ConnectionPoolThreadContext) void {
var connections = std.ArrayList(*Connection.Connection){};
defer {
// Clean up connections created by this thread
for (connections.items) |conn| {
context.pool.removeConnection(conn);
}
connections.deinit(context.allocator);
}
var i: usize = 0;
while (i < context.operations) : (i += 1) {
// Create connection
const conn_type: Connection.ConnectionType = if (i % 2 == 0) .tcp else .udp;
const conn = context.pool.createConnection(conn_type) catch {
_ = context.errors.fetchAdd(1, .monotonic);
continue;
};
connections.append(context.allocator, conn) catch {
_ = context.errors.fetchAdd(1, .monotonic);
continue;
};
// Verify connection state
if (conn.getState() != .disconnected) {
_ = context.errors.fetchAdd(1, .monotonic);
}
// Small delay to increase chance of race conditions
Thread.sleep(1 * time.ns_per_ms);
_ = context.success_count.fetchAdd(1, .monotonic);
}
// Test finding connections
const addr = Address.parse("127.0.0.1:8080") catch {
_ = context.errors.fetchAdd(1, .monotonic);
return;
};
_ = context.pool.findConnectionByAddress(addr);
// Test getting active connections
var active = context.pool.getActiveConnections() catch {
_ = context.errors.fetchAdd(1, .monotonic);
return;
};
active.deinit(context.allocator);
}
/// Worker function for concurrent socket manager operations
fn socketManagerWorker(context: *SocketManagerThreadContext) void {
// Store fds instead of pointers to avoid invalidation when ArrayList grows
var socket_fds = std.ArrayList(std.posix.fd_t){};
defer {
// Clean up sockets created by this thread using fd-based removal
for (socket_fds.items) |fd| {
context.manager.removeSocketByFd(fd);
}
socket_fds.deinit(context.allocator);
}
var i: usize = 0;
while (i < context.operations) : (i += 1) {
// Create socket (alternate between TCP and UDP)
const sock = if (i % 2 == 0)
context.manager.createTcpSocket() catch {
_ = context.errors.fetchAdd(1, .monotonic);
continue;
}
else
context.manager.createUdpSocket() catch {
_ = context.errors.fetchAdd(1, .monotonic);
continue;
};
// Store the fd immediately (before pointer might become invalid due to ArrayList growth)
// Note: After storing, the sock pointer may become invalid if another thread
// causes the SocketManager's ArrayList to reallocate
const fd = sock.fd;
socket_fds.append(context.allocator, fd) catch {
_ = context.errors.fetchAdd(1, .monotonic);
continue;
};
// Small delay to increase chance of race conditions
Thread.sleep(1 * time.ns_per_ms);
_ = context.success_count.fetchAdd(1, .monotonic);
}
}
test "BufferPool: concurrent acquire and release" {
const config = Buffer.PoolConfig{
.min_chunk_size = 256,
.max_chunk_size = 4096,
.initial_chunks = 8,
.max_chunks = 64,
};
var pool = try Buffer.BufferPool.init(config, testing.allocator);
defer pool.deinit();
const test_config = TestConfig{
.num_threads = 4,
.operations_per_thread = 20,
};
var threads: [4]Thread = undefined;
var contexts: [4]BufferPoolThreadContext = undefined;
// Initialize contexts
for (&contexts, 0..) |*ctx, i| {
ctx.* = .{
.pool = &pool,
.thread_id = i,
.operations = test_config.operations_per_thread,
.allocator = testing.allocator,
.errors = std.atomic.Value(u32).init(0),
.success_count = std.atomic.Value(u32).init(0),
};
}
// Spawn threads
for (&threads, 0..) |*thread, i| {
thread.* = try Thread.spawn(.{}, bufferPoolWorker, .{&contexts[i]});
}
// Wait for all threads to complete
for (&threads) |*thread| {
thread.join();
}
// Verify results
var total_errors: u32 = 0;
var total_success: u32 = 0;
for (&contexts) |*ctx| {
total_errors += ctx.errors.load(.monotonic);
total_success += ctx.success_count.load(.monotonic);
}
std.debug.print("\n[BufferPool] Successful operations: {}, Errors: {}\n", .{ total_success, total_errors });
// Check pool statistics
const stats = pool.stats();
std.debug.print("[BufferPool] Pool stats - Total chunks: {}, Used: {}, Free: {}\n", .{ stats.total_chunks, stats.used_chunks, stats.free_chunks });
// All buffers should be released
try testing.expectEqual(@as(usize, 0), stats.used_chunks);
// Should have no errors from data corruption
try testing.expectEqual(@as(u32, 0), total_errors);
}
test "BufferPool: stress test with rapid allocation/deallocation" {
const config = Buffer.PoolConfig{
.min_chunk_size = 128,
.max_chunk_size = 2048,
.initial_chunks = 2,
.max_chunks = 64,
};
var pool = try Buffer.BufferPool.init(config, testing.allocator);
defer pool.deinit();
const test_config = TestConfig{
.num_threads = 16,
.operations_per_thread = 25,
};
var threads: [16]Thread = undefined;
var contexts: [16]BufferPoolThreadContext = undefined;
// Initialize contexts
for (&contexts, 0..) |*ctx, i| {
ctx.* = .{
.pool = &pool,
.thread_id = i,
.operations = test_config.operations_per_thread,
.allocator = testing.allocator,
.errors = std.atomic.Value(u32).init(0),
.success_count = std.atomic.Value(u32).init(0),
};
}
// Spawn threads
for (&threads, 0..) |*thread, i| {
thread.* = try Thread.spawn(.{}, bufferPoolWorker, .{&contexts[i]});
}
// Wait for all threads
for (&threads) |*thread| {
thread.join();
}
// Verify all buffers released
const stats = pool.stats();
std.debug.print("[BufferPool Stress] Total chunks: {}, Used: {}, Free: {}\n", .{ stats.total_chunks, stats.used_chunks, stats.free_chunks });
try testing.expectEqual(@as(usize, 0), stats.used_chunks);
}
test "ConnectionPool: concurrent create and remove operations" {
const conn_config = Connection.ConnectionConfig{
.connection_type = .tcp,
.buffer_size = 1024,
};
var pool = Connection.ConnectionPool.init(conn_config, testing.allocator);
defer pool.deinit();
const test_config = TestConfig{
.num_threads = 6,
.operations_per_thread = 20,
};
var threads: [6]Thread = undefined;
var contexts: [6]ConnectionPoolThreadContext = undefined;
// Initialize contexts
for (&contexts, 0..) |*ctx, i| {
ctx.* = .{
.pool = &pool,
.thread_id = i,
.operations = test_config.operations_per_thread,
.allocator = testing.allocator,
.errors = std.atomic.Value(u32).init(0),
.success_count = std.atomic.Value(u32).init(0),
};
}
// Spawn threads
for (&threads, 0..) |*thread, i| {
thread.* = try Thread.spawn(.{}, connectionPoolWorker, .{&contexts[i]});
}
// Wait for all threads
for (&threads) |*thread| {
thread.join();
}
// Verify results
var total_errors: u32 = 0;
var total_success: u32 = 0;
for (&contexts) |*ctx| {
total_errors += ctx.errors.load(.monotonic);
total_success += ctx.success_count.load(.monotonic);
}
std.debug.print("\n[ConnectionPool] Successful operations: {}, Errors: {}\n", .{ total_success, total_errors });
// Get pool statistics
const stats = pool.getPoolStats();
std.debug.print("[ConnectionPool] Total connections: {}, Active: {}, Disconnected: {}\n", .{ stats.total_connections, stats.active_connections, stats.disconnected_connections });
// All connections should be removed by workers
try testing.expectEqual(@as(usize, 0), stats.total_connections);
}
test "ConnectionPool: concurrent findConnectionByAddress" {
const conn_config = Connection.ConnectionConfig{
.connection_type = .tcp,
};
var pool = Connection.ConnectionPool.init(conn_config, testing.allocator);
defer pool.deinit();
// Pre-create some connections
const conn1 = try pool.createConnection(.tcp);
const conn2 = try pool.createConnection(.udp);
const conn3 = try pool.createConnection(.tcp);
_ = conn1;
_ = conn2;
_ = conn3;
_ = TestConfig{
.num_threads = 8,
.operations_per_thread = 100,
};
const ReadWorker = struct {
fn run(p: *Connection.ConnectionPool) void {
var i: usize = 0;
while (i < 100) : (i += 1) {
const addr = Address.parse("127.0.0.1:9999") catch unreachable;
_ = p.findConnectionByAddress(addr);
Thread.sleep(500 * time.ns_per_us); // 0.5ms
}
}
};
var threads: [8]Thread = undefined;
for (&threads) |*thread| {
thread.* = try Thread.spawn(.{}, ReadWorker.run, .{&pool});
}
for (&threads) |*thread| {
thread.join();
}
// Verify pool is still intact
const stats = pool.getPoolStats();
try testing.expectEqual(@as(usize, 3), stats.total_connections);
}
test "SocketManager: concurrent socket creation and removal" {
var manager = Socket.SocketManager.init(testing.allocator);
defer manager.deinit();
const test_config = TestConfig{
.num_threads = 6,
.operations_per_thread = 20,
};
var threads: [6]Thread = undefined;
var contexts: [6]SocketManagerThreadContext = undefined;
// Initialize contexts
for (&contexts, 0..) |*ctx, i| {
ctx.* = .{
.manager = &manager,
.thread_id = i,
.operations = test_config.operations_per_thread,
.allocator = testing.allocator,
.errors = std.atomic.Value(u32).init(0),
.success_count = std.atomic.Value(u32).init(0),
};
}
// Spawn threads
for (&threads, 0..) |*thread, i| {
thread.* = try Thread.spawn(.{}, socketManagerWorker, .{&contexts[i]});
}
// Wait for all threads
for (&threads) |*thread| {
thread.join();
}
// Verify results
var total_errors: u32 = 0;
var total_success: u32 = 0;
for (&contexts) |*ctx| {
total_errors += ctx.errors.load(.monotonic);
total_success += ctx.success_count.load(.monotonic);
}
std.debug.print("\n[SocketManager] Successful operations: {}, Errors: {}\n", .{ total_success, total_errors });
// All sockets should be removed by workers
try testing.expectEqual(@as(usize, 0), manager.sockets.items.len);
}
test "SocketManager: concurrent getActiveSockets" {
var manager = Socket.SocketManager.init(testing.allocator);
defer manager.deinit();
// Pre-create some sockets
const sock1 = try manager.createTcpSocket();
const sock2 = try manager.createUdpSocket();
const sock3 = try manager.createTcpSocket();
_ = sock1;
_ = sock2;
_ = sock3;
const ReadWorker = struct {
fn run(mgr: *Socket.SocketManager, alloc: std.mem.Allocator) void {
var i: usize = 0;
while (i < 50) : (i += 1) {
const active = mgr.getActiveSockets() catch return;
alloc.free(active);
Thread.sleep(1 * time.ns_per_ms);
}
}
};
var threads: [8]Thread = undefined;
for (&threads) |*thread| {
thread.* = try Thread.spawn(.{}, ReadWorker.run, .{ &manager, testing.allocator });
}
for (&threads) |*thread| {
thread.join();
}
// Verify manager is still intact
try testing.expectEqual(@as(usize, 3), manager.sockets.items.len);
}
test "BufferPool: verify no memory leaks under concurrent load" {
const config = Buffer.PoolConfig{
.min_chunk_size = 512,
.max_chunk_size = 8192,
.initial_chunks = 4,
.max_chunks = 32,
};
var pool = try Buffer.BufferPool.init(config, testing.allocator);
defer pool.deinit();
const Worker = struct {
fn run(p: *Buffer.BufferPool, thread_id: usize) void {
var buffers: [10][]u8 = undefined;
var acquired: usize = 0;
// Acquire multiple buffers
while (acquired < 10) : (acquired += 1) {
buffers[acquired] = p.acquire(512 + thread_id * 64) catch break;
}
// Release all acquired buffers (important: release what we got, even if we didn't get all)
var i: usize = 0;
while (i < acquired) : (i += 1) {
p.release(buffers[i]);
}
}
};
var threads: [10]Thread = undefined;
for (&threads, 0..) |*thread, i| {
thread.* = try Thread.spawn(.{}, Worker.run, .{ &pool, i });
}
for (&threads) |*thread| {
thread.join();
}
const stats = pool.stats();
std.debug.print("[Memory Leak Test] Total chunks: {}, Used: {}, Free: {}\n", .{ stats.total_chunks, stats.used_chunks, stats.free_chunks });
// All buffers must be released
try testing.expectEqual(@as(usize, 0), stats.used_chunks);
}
test "Mixed operations: ConnectionPool + BufferPool concurrency" {
// Test interaction between connection pool and buffer pool under load
const conn_config = Connection.ConnectionConfig{
.connection_type = .tcp,
.buffer_size = 2048,
};
var conn_pool = Connection.ConnectionPool.init(conn_config, testing.allocator);
defer conn_pool.deinit();
const MixedWorker = struct {
fn run(pool: *Connection.ConnectionPool, _: usize) void {
var i: usize = 0;
while (i < 30) : (i += 1) {
const conn = pool.createConnection(.tcp) catch return;
// Create buffers through the connection
var send_buf = conn.createSendBuffer() catch {
pool.removeConnection(conn);
return;
};
var recv_buf = conn.createReceiveBuffer() catch {
send_buf.release();
pool.removeConnection(conn);
return;
};
// Simulate some work
const test_data = "Thread data";
send_buf.write(test_data) catch {};
Thread.sleep(1 * time.ns_per_ms);
// Release buffers BEFORE removing the connection
recv_buf.release();
send_buf.release();
pool.removeConnection(conn);
}
}
};
var threads: [6]Thread = undefined;
for (&threads, 0..) |*thread, i| {
thread.* = try Thread.spawn(.{}, MixedWorker.run, .{ &conn_pool, i });
}
for (&threads) |*thread| {
thread.join();
}
const stats = conn_pool.getPoolStats();
std.debug.print("[Mixed Test] Connections remaining: {}\n", .{stats.total_connections});
try testing.expectEqual(@as(usize, 0), stats.total_connections);
}