Path: redb-route/redb.Route/Components/MockComponent.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route/Components/MockComponent.cs ---- using System.Collections.Concurrent; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Components; /// /// Mock component for testing. Scheme: "mock". /// Captures all received exchanges so tests can assert on them. /// Supports count expectations, latch-based waiting, and body predicates. /// URI: mock://name?expectedMessageCount=0 /// public class MockComponent : ComponentBase { private readonly ConcurrentDictionary _endpoints = new(StringComparer.OrdinalIgnoreCase); /// public override string Scheme => "mock"; /// public override IEndpoint CreateEndpoint(EndpointUri uri) { ArgumentNullException.ThrowIfNull(uri); var options = new MockEndpointOptions(); options.BindFromUri(uri.RawParameters); options.Validate(); return _endpoints.GetOrAdd(uri.NormalizedKey, _ => new MockEndpoint(uri, this, options)); } /// /// Gets a mock endpoint by name (e.g., "result" for "mock://result"). /// Returns null if not found. /// /// Endpoint name (path portion of the URI). /// Mock endpoint or null. public MockEndpoint? GetEndpoint(string name) { var key = $"mock://{name}"; return _endpoints.TryGetValue(key, out var ep) ? ep : null; } } /// /// Options for mock endpoints. /// public class MockEndpointOptions : EndpointOptions { /// Expected number of messages. 0 = no expectation (default: 0). public int ExpectedMessageCount { get; set; } /// public override void Validate() { } } /// /// Mock endpoint. Captures received exchanges for testing. /// public partial class MockEndpoint : EndpointBase { private readonly ConcurrentQueue _received = new(); private readonly SemaphoreSlim _latch = new(0); private readonly MockEndpointOptions _mockOptions; /// Creates a mock endpoint. public MockEndpoint(EndpointUri uri, MockComponent component, MockEndpointOptions options) : base(uri, component, options) { _mockOptions = options; } /// Gets all received exchanges in order. public IReadOnlyList ReceivedExchanges => [.. _received]; /// Gets the number of received exchanges. public int ReceivedCount => _received.Count; /// Gets the expected message count (from options). public int ExpectedMessageCount => _mockOptions.ExpectedMessageCount; /// /// Waits until the expected number of messages are received, or until timeout. /// /// Maximum wait time. /// Cancellation token. /// True if the expected count was reached; false on timeout. public async Task WaitForSatisfied(TimeSpan timeout, CancellationToken ct = default) { if (_mockOptions.ExpectedMessageCount <= 0) return true; using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct); cts.CancelAfter(timeout); try { while (ReceivedCount < _mockOptions.ExpectedMessageCount) { await _latch.WaitAsync(cts.Token).ConfigureAwait(false); } return true; } catch (OperationCanceledException) { return ReceivedCount >= _mockOptions.ExpectedMessageCount; } } /// Resets all captured exchanges, the latch counter, expectations and scripted responses. public void Reset() { while (_received.TryDequeue(out _)) { } // Drain semaphore while (_latch.CurrentCount > 0) _latch.Wait(0); ResetExpectations(); } /// Records an exchange (called by MockProducer/MockConsumer). internal void RecordExchange(IExchange exchange) { _received.Enqueue(exchange); _latch.Release(); } /// public override IProducer CreateProducer() => new MockProducer(this); /// public override IConsumer CreateConsumer(IProcessor processor) { ArgumentNullException.ThrowIfNull(processor); return new MockConsumer(this, processor); } } /// /// Mock producer. Records the exchange and optionally invokes a registered consumer. /// public class MockProducer : IProducer { private readonly MockEndpoint _endpoint; private ILogger? _logger; /// Creates a mock producer. public MockProducer(MockEndpoint endpoint) { _endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint)); _logger = (endpoint.Component as ComponentBase)?.Logger; } /// public Task Process(IExchange exchange, CancellationToken ct = default) => _endpoint.OnMessageAsync(exchange, ct); /// public Task Start(CancellationToken ct = default) { _logger?.LogInformation("Mock producer started: {Name}", EndpointUri.ForLog(_endpoint.Uri.NormalizedKey, _logger)); return Task.CompletedTask; } /// public Task Stop(CancellationToken ct = default) { _logger?.LogInformation("Mock producer stopped: {Name}", EndpointUri.ForLog(_endpoint.Uri.NormalizedKey, _logger)); return Task.CompletedTask; } } /// /// Mock consumer. Delegates to the inner processor and records the exchange. /// public class MockConsumer : IConsumer { private readonly MockEndpoint _endpoint; public IEndpoint Endpoint => _endpoint; private readonly IProcessor _processor; private ILogger? _logger; /// Creates a mock consumer. public MockConsumer(MockEndpoint endpoint, IProcessor processor) { _endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint)); _processor = processor ?? throw new ArgumentNullException(nameof(processor)); _logger = (endpoint.Component as ComponentBase)?.Logger; } /// public Task Start(CancellationToken ct = default) => Task.CompletedTask; /// public Task Stop(CancellationToken ct = default) => Task.CompletedTask; }