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

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());
}