Path: redb-route/redb.Route/Components/MockEndpoint.Expectations.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/MockEndpoint.Expectations.cs
----
using System.Diagnostics;
using System.Text;
using redb.Route.Abstractions;
using redb.Route.Predicates;
namespace redb.Route.Components;
///
/// Expectations, assertions and scripted responses of the mock endpoint (Apache Camel
/// MockEndpoint parity). Expectations are fluent and cumulative;
/// waits until all of them hold or the timeout elapses and then fails with every unmet expectation
/// and the bodies actually received.
///
public partial class MockEndpoint
{
private readonly object _sync = new();
private readonly List _expectations = [];
private readonly List _responses = [];
private readonly List _captured = [];
private TaskCompletionSource _changed = NewSignal();
private int _messageNumber;
// ── Receive path (called by MockProducer) ─────────────────────────────────
/// Records the message, wakes waiters, then applies the scripted responses that target it.
internal async Task OnMessageAsync(IExchange exchange, CancellationToken ct)
{
int number;
MockResponse[] responses;
lock (_sync)
{
number = ++_messageNumber;
_captured.Add(MockReceived.Capture(exchange));
responses = _responses.Where(r => r.AppliesTo(number)).ToArray();
}
RecordExchange(exchange);
Interlocked.Exchange(ref _changed, NewSignal()).TrySetResult(true);
foreach (var response in responses)
await response.ApplyAsync(exchange, ct).ConfigureAwait(false);
}
private static TaskCompletionSource NewSignal() => new(TaskCreationOptions.RunContinuationsAsynchronously);
private void ResetExpectations()
{
lock (_sync)
{
_expectations.Clear();
_responses.Clear();
_captured.Clear();
_messageNumber = 0;
}
}
// ── Expectations ──────────────────────────────────────────────────────────
/// Expects exactly messages.
public MockEndpoint ExpectMessageCount(int count) => Add(new MessageCountExpectation(Positive(count), minimum: false));
/// Expects at least messages.
public MockEndpoint ExpectMinimumMessageCount(int count) => Add(new MessageCountExpectation(Positive(count), minimum: true));
/// Expects exactly these bodies, in this order (numbers compare across CLR types).
public MockEndpoint ExpectBodies(params object?[] bodies) => Add(new BodiesExpectation(bodies ?? [], anyOrder: false));
/// Expects exactly these bodies, in any order.
public MockEndpoint ExpectBodiesInAnyOrder(params object?[] bodies) => Add(new BodiesExpectation(bodies ?? [], anyOrder: true));
/// Expects every message to carry header equal to .
public MockEndpoint ExpectHeader(string name, object? value) => Add(new KeyValueExpectation("Header", Required(name), value, every: true));
/// Expects at least one message to carry header equal to .
public MockEndpoint ExpectHeaderReceived(string name, object? value) => Add(new KeyValueExpectation("Header", Required(name), value, every: false));
/// Expects every message to carry exchange property equal to .
public MockEndpoint ExpectProperty(string key, object? value) => Add(new KeyValueExpectation("Property", Required(key), value, every: true));
/// Expects to hold on every message.
public MockEndpoint Expect(Func predicate, string? description = null)
{
ArgumentNullException.ThrowIfNull(predicate);
return Add(new PredicateExpectation(e => Task.FromResult(predicate(e)), description ?? ""));
}
/// Expects to hold on every message (awaited, so async predicates work).
public MockEndpoint Expect(IPredicate predicate, string? description = null)
{
ArgumentNullException.ThrowIfNull(predicate);
return Add(new PredicateExpectation(predicate.MatchesAsync, description ?? predicate.GetType().Name));
}
///
/// Expects the route-language condition ("header.priority == 'high' and body.total > 100")
/// to hold on every message; compiled through the same PredicateFactory as Filter(string).
///
public MockEndpoint Expect(string condition)
{
ArgumentException.ThrowIfNullOrWhiteSpace(condition);
return Add(new PredicateExpectation(PredicateFactory.FromString(condition).MatchesAsync, $"'{condition}'"));
}
private MockEndpoint Add(MockExpectation expectation)
{
lock (_sync) _expectations.Add(expectation);
return this;
}
private static int Positive(int count) => count >= 0 ? count : throw new ArgumentOutOfRangeException(nameof(count));
private static string Required(string name) { ArgumentException.ThrowIfNullOrWhiteSpace(name); return name; }
// ── Scripted responses ────────────────────────────────────────────────────
/// Scripts what happens to the -th message (1-based): reply body, delay, exception.
public MockResponse Whenever(int messageNumber)
{
if (messageNumber < 1) throw new ArgumentOutOfRangeException(nameof(messageNumber), "Message numbers are 1-based.");
var response = new MockResponse(messageNumber);
lock (_sync) _responses.Add(response);
return response;
}
/// Scripts what happens to every message.
public MockResponse WheneverAny()
{
var response = new MockResponse(null);
lock (_sync) _responses.Add(response);
return response;
}
// ── Assertions ────────────────────────────────────────────────────────────
/// Returns true when every expectation currently holds (no waiting).
public async Task IsSatisfiedAsync() => (await EvaluateAsync().ConfigureAwait(false)).Count == 0;
///
/// Waits up to for every expectation to hold, then throws
/// listing each unmet expectation and the bodies received.
/// An expectedMessageCount URI option counts as an expectation when no explicit count was set.
///
public async Task AssertIsSatisfiedAsync(TimeSpan timeout, CancellationToken ct = default)
{
var clock = Stopwatch.StartNew();
while (true)
{
var signal = Volatile.Read(ref _changed).Task;
var failures = await EvaluateAsync().ConfigureAwait(false);
if (failures.Count == 0) return;
var remaining = timeout - clock.Elapsed;
if (remaining <= TimeSpan.Zero)
throw new MockAssertionException(FormatFailures(failures));
await Task.WhenAny(signal, Task.Delay(remaining, ct)).ConfigureAwait(false);
ct.ThrowIfCancellationRequested();
}
}
/// Waits the full , then throws if the expectations turned out to be satisfied.
public async Task AssertIsNotSatisfiedAsync(TimeSpan timeout, CancellationToken ct = default)
{
await Task.Delay(timeout, ct).ConfigureAwait(false);
var failures = await EvaluateAsync().ConfigureAwait(false);
if (failures.Count == 0)
throw new MockAssertionException($"{Uri.NormalizedKey} expectations were satisfied but were expected not to be ({ReceivedCount} message(s) received)");
}
private async Task> EvaluateAsync()
{
MockExpectation[] expectations;
MockReceived[] received;
lock (_sync)
{
expectations = _expectations.ToArray();
received = _captured.ToArray();
}
var effective = expectations.ToList();
if (_mockOptions.ExpectedMessageCount > 0 && !expectations.Any(e => e is MessageCountExpectation { IsMinimum: false }))
effective.Insert(0, new MessageCountExpectation(_mockOptions.ExpectedMessageCount, minimum: false));
var failures = new List();
foreach (var expectation in effective)
{
var failure = await expectation.EvaluateAsync(received).ConfigureAwait(false);
if (failure is not null) failures.Add(failure);
}
return failures;
}
private string FormatFailures(List failures)
{
MockReceived[] received;
lock (_sync) received = _captured.ToArray();
var sb = new StringBuilder();
foreach (var failure in failures)
sb.Append(Uri.NormalizedKey).Append(' ').AppendLine(failure);
sb.Append(" received ").Append(received.Length).AppendLine(" message(s):");
for (var i = 0; i < received.Length; i++)
sb.Append(" ").Append(i + 1).Append(": ").AppendLine(MockValues.Describe(received[i].Body));
return sb.ToString().TrimEnd();
}
}