using Microsoft.Extensions.DependencyInjection; using StellaOps.Router.Common.Enums; using StellaOps.Router.Common.Models; using StellaOps.Router.Transport.InMemory; using Xunit; namespace StellaOps.Router.Transport.InMemory.Tests; public class CancelFlowTests { private readonly InMemoryConnectionRegistry _registry; private readonly InMemoryTransportServer _server; private readonly InMemoryTransportClient _client; public CancelFlowTests() { var services = new ServiceCollection(); services.AddLogging(); services.AddInMemoryTransport(); var provider = services.BuildServiceProvider(); _registry = provider.GetRequiredService(); _server = provider.GetRequiredService(); _client = provider.GetRequiredService(); } [Fact] public async Task SendCancelAsync_SendsCancelFrame() { // Arrange var instance = new InstanceDescriptor { InstanceId = "inst-1", ServiceName = "test-service", Version = "1.0.0", Region = "eu1" }; await _server.StartAsync(CancellationToken.None); await _client.ConnectAsync(instance, [], CancellationToken.None); var connectionId = _registry.ConnectionIds.First(); _server.StartListeningToConnection(connectionId); var connections = _registry.GetAllConnections(); var connection = connections[0]; var correlationId = Guid.NewGuid(); // Act await _client.SendCancelAsync(connection, correlationId, "Test cancellation"); // Wait for processing await Task.Delay(50); // Assert - no exception means cancel was sent successfully Assert.Equal(1, _registry.Count); } [Fact] public async Task OnCancelReceived_IsInvoked() { // Arrange var instance = new InstanceDescriptor { InstanceId = "inst-1", ServiceName = "test-service", Version = "1.0.0", Region = "eu1" }; await _server.StartAsync(CancellationToken.None); await _client.ConnectAsync(instance, [], CancellationToken.None); var connectionId = _registry.ConnectionIds.First(); _server.StartListeningToConnection(connectionId); Guid? receivedCorrelationId = null; _client.OnCancelReceived += (corrId, reason) => { receivedCorrelationId = corrId; return Task.CompletedTask; }; var correlationId = Guid.NewGuid(); // Send a cancel frame from server to client var cancelFrame = new Frame { Type = FrameType.Cancel, CorrelationId = correlationId.ToString("N"), Payload = ReadOnlyMemory.Empty }; await _server.SendToMicroserviceAsync(connectionId, cancelFrame, CancellationToken.None); // Wait for processing await Task.Delay(100); // Assert Assert.Equal(correlationId, receivedCorrelationId); } }