//! Comprehensive tests for allocator safety and memory management //! //! This test file verifies: //! - Functions using allocators properly handle OOM //! - Undefined variables are properly initialized //! - All allocations are properly freed //! - Memory leak detection using std.testing.allocator const std = @import("std"); const testing = std.testing; // Import modules to test const core = @import("core"); const Error = core.errors.Error; const Address = core.Address; const ErrorResult = core.errors.ErrorResult; const ErrorContext = core.errors.ErrorContext; const BufferPool = core.buffer.BufferPool; const PoolConfig = core.buffer.PoolConfig; const StreamBuffer = core.buffer.StreamBuffer; const files = @import("files"); const TransferMessage = files.transfer.TransferMessage; const FileMetadata = files.file.FileMetadata; const PieceHash = files.hash.PieceHash; const protocol = @import("protocol"); const CryptoManager = protocol.crypto.CryptoManager; /// Test that ErrorResult.create properly handles allocator parameter test "ErrorResult.create uses passed allocator" { const context = ErrorContext.init("test_op", "test_component"); // Test with testing allocator const result = try ErrorResult.create( Error.ConnectionRefused, "Test error message", context, "test.zig", 42, "testFunction", testing.allocator, ); defer testing.allocator.free(result.info.context); try testing.expect(result.err == Error.ConnectionRefused); try testing.expect(result.info.context.len > 0); } /// Test that ErrorResult.create handles OOM gracefully test "ErrorResult.create handles OOM" { var fail_allocator = testing.FailingAllocator.init(testing.allocator, .{ .fail_index = 0 }); const allocator = fail_allocator.allocator(); const context = ErrorContext.init("test_op", "test_component"); const result = ErrorResult.create( Error.ConnectionRefused, "Test error message", context, "test.zig", 42, "testFunction", allocator, ); // Should return OutOfMemory error try testing.expectError(Error.OutOfMemory, result); } /// Test that Address.toString uses passed allocator test "Address.toString uses passed allocator" { const addr = try Address.parse("192.168.1.100:8080"); // Test with testing allocator const str = try addr.toString(testing.allocator); defer testing.allocator.free(str); try testing.expect(str.len > 0); try testing.expect(std.mem.indexOf(u8, str, "192.168.1.100") != null); } /// Test that Address.toString handles OOM gracefully test "Address.toString handles OOM" { var fail_allocator = testing.FailingAllocator.init(testing.allocator, .{ .fail_index = 0 }); const allocator = fail_allocator.allocator(); const addr = try Address.parse("192.168.1.100:8080"); const result = addr.toString(allocator); // Should return OutOfMemory error try testing.expectError(Error.OutOfMemory, result); } /// Test buffer-based Address.toStringBuf doesn't allocate test "Address.toStringBuf doesn't allocate" { const addr = try Address.parse("192.168.1.100:8080"); var buf: [128]u8 = undefined; const str = addr.toStringBuf(&buf); try testing.expect(str.len > 0); try testing.expect(std.mem.indexOf(u8, str, "192.168.1.100") != null); } /// Test that TransferMessage.handshake uses passed allocator test "TransferMessage.handshake uses passed allocator" { var msg = TransferMessage.handshake("peer1", "client1", testing.allocator); defer msg.deinit(testing.allocator); try testing.expect(msg.message_type == .handshake); try testing.expect(msg.data.len > 0); } /// Test that TransferMessage.metadataResponse uses passed allocator test "TransferMessage.metadataResponse uses passed allocator" { const piece_hashes = try testing.allocator.alloc(PieceHash, 2); defer testing.allocator.free(piece_hashes); for (piece_hashes) |*hash| { hash.* = [_]u8{0} ** 32; } const metadata = try FileMetadata.create( "test.bin", 1024, piece_hashes, testing.allocator, ); var msg = TransferMessage.metadataResponse("peer1", metadata, testing.allocator); defer msg.deinit(testing.allocator); try testing.expect(msg.message_type == .metadata_response); try testing.expect(msg.data.len > 0); } /// Test that TransferMessage.pieceData uses passed allocator test "TransferMessage.pieceData uses passed allocator" { const test_data = "Test piece data"; const hash = [_]u8{1} ** 32; var msg = TransferMessage.pieceData("peer1", 0, test_data, hash, testing.allocator); defer msg.deinit(testing.allocator); try testing.expect(msg.message_type == .piece_data); try testing.expect(msg.data.len > 0); } /// Test that BufferPool properly initializes chunks test "BufferPool allocates and frees chunks properly" { 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(); // Verify initial chunks were allocated const stats = pool.stats(); try testing.expect(stats.total_chunks >= 1); // At least some chunks should be allocated // Acquire and release buffers const buf1 = try pool.acquire(32); const buf2 = try pool.acquire(64); pool.release(buf1); pool.release(buf2); // All buffers should be freed when pool is deinit'd } /// Test that StreamBuffer properly manages memory test "StreamBuffer allocates and frees properly" { var buffer = try StreamBuffer.init(testing.allocator, 100); defer buffer.deinit(); const test_data = "Hello, World!"; try buffer.write(test_data); 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]); } /// Test that undefined variables are properly initialized test "Variables are properly initialized (not undefined)" { // Test that we can safely use initialized arrays var arr1: [32]u8 = [_]u8{0} ** 32; try testing.expect(arr1[0] == 0); try testing.expect(arr1[31] == 0); var arr2: [4]u8 = [_]u8{0} ** 4; try testing.expect(arr2[0] == 0); try testing.expect(arr2[3] == 0); // Test that CryptoManager initializes its key properly var crypto = CryptoManager.init(testing.allocator); defer crypto.deinit(); // The key should be initialized (not undefined) // We can't test the exact value as it's random, but we can verify it's accessible try testing.expect(crypto.local_key.len == 32); } /// Test that TransferMessage.deinit properly frees memory test "TransferMessage.deinit frees all allocated memory" { // Create a message with allocated data const msg = TransferMessage.handshake("peer1", "client1", testing.allocator); // Copy message to stack to test deinit var msg_copy = msg; msg_copy.deinit(testing.allocator); // If there was a memory leak, testing.allocator would catch it } /// Test memory leak detection with complex operations test "Complex operations don't leak memory" { // Create and destroy multiple objects to test for leaks // Test 1: Multiple address conversions { const addr = try Address.parse("192.168.1.100:8080"); const str1 = try addr.toString(testing.allocator); defer testing.allocator.free(str1); const str2 = try addr.toString(testing.allocator); defer testing.allocator.free(str2); } // Test 2: Multiple transfer messages { const msg1 = TransferMessage.handshake("peer1", "client1", testing.allocator); defer testing.allocator.free(msg1.data); const msg2 = TransferMessage.handshake("peer2", "client2", testing.allocator); defer testing.allocator.free(msg2.data); } // Test 3: Buffer pool operations { const config = PoolConfig{ .min_chunk_size = 64, .initial_chunks = 2, }; var pool = BufferPool.init(config, testing.allocator); defer pool.deinit(); const buf1 = try pool.acquire(32); const buf2 = try pool.acquire(64); pool.release(buf1); pool.release(buf2); } // Test 4: Stream buffer operations { var buffer = try StreamBuffer.init(testing.allocator, 100); defer buffer.deinit(); try buffer.write("test data"); var read_buf: [100]u8 = undefined; _ = try buffer.read(&read_buf); } } /// Test that failed allocations don't cause undefined behavior test "Failed allocations don't cause undefined behavior" { var fail_allocator = testing.FailingAllocator.init(testing.allocator, .{ .fail_index = 0 }); const allocator = fail_allocator.allocator(); // Test Address.toString OOM { const addr = try Address.parse("192.168.1.100:8080"); const result = addr.toString(allocator); try testing.expectError(Error.OutOfMemory, result); } // Test ErrorResult.create OOM { const context = ErrorContext.init("test", "test"); const result = ErrorResult.create( Error.NetworkError, "test", context, "test.zig", 1, "test", allocator, ); try testing.expectError(Error.OutOfMemory, result); } } /// Test that all initialization uses proper zero-initialization instead of undefined test "All critical arrays use zero-initialization" { // These tests verify that arrays are initialized to zeros, not undefined // Test 1: Fixed-size arrays var arr1: [32]u8 = [_]u8{0} ** 32; for (arr1) |byte| { try testing.expectEqual(@as(u8, 0), byte); } var arr2: [4]u8 = [_]u8{0} ** 4; for (arr2) |byte| { try testing.expectEqual(@as(u8, 0), byte); } // Test 2: After memcpy, values should be predictable var dest: [32]u8 = [_]u8{0} ** 32; const src = [_]u8{1} ** 32; @memcpy(&dest, &src); for (dest) |byte| { try testing.expectEqual(@as(u8, 1), byte); } }