Bundle: redb-route / tests/redb.Route.Tests (tests.redb.Route.Tests.txt), 257 files
Snapshot: 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
Index: https://redbase.app/src/dev-2026-12-06/redb-route/_index.txt
====
Path: redb-route/tests/redb.Route.Tests/Aggregation/AggregationStrategiesTests.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/tests/redb.Route.Tests/Aggregation/AggregationStrategiesTests.cs
----
using redb.Route.Abstractions;
using redb.Route.Aggregation;
using redb.Route.Core;
using redb.Route.TestKit;
namespace redb.Route.Tests.Aggregation;
///
/// The strategy library: each strategy in unit form (null-first as Split calls it, and seeded as
/// Multicast / Aggregate call it) and end-to-end on Aggregate, Multicast, Split and Enrich.
///
public class AggregationStrategiesTests
{
private static readonly TimeSpan Wait = TimeSpan.FromSeconds(2);
private static IExchange Ex(object? body, params (string Key, object? Value)[] headers)
{
var e = Exchange.Create(new Message(body), null);
foreach (var (k, v) in headers) e.In.Headers[k] = v;
return e;
}
// ── Unit: null-first (Split) and seeded (Multicast / Aggregate) ─────────────
[Fact]
public void GroupedBody_NullFirst_AndSeeded()
{
var s = AggregationStrategies.GroupedBody();
var fromNull = s(null!, Ex("a"));
s(fromNull, Ex("b"));
fromNull.In.Body.Should().BeEquivalentTo(new List { "a", "b" });
var seeded = s(Ex("x"), Ex("y"));
s(seeded, Ex("z"));
seeded.In.Body.Should().BeEquivalentTo(new List { "x", "y", "z" });
}
[Fact]
public void GroupedBodyTyped_And_TypeMismatch()
{
var s = AggregationStrategies.GroupedBody();
var acc = s(Ex(1), Ex(2));
acc.In.Body.Should().BeEquivalentTo(new List { 1, 2 });
var act = () => s(acc, Ex("three"));
act.Should().Throw().WithMessage("GroupedBody*");
}
[Fact]
public void GroupedExchange_UseLatest_UseOriginal()
{
var a = Ex("a"); var b = Ex("b");
AggregationStrategies.GroupedExchange()(a, b).In.Body.Should().BeEquivalentTo(new List { a, b });
AggregationStrategies.UseLatest()(Ex("old"), Ex("new")).In.Body.Should().Be("new");
AggregationStrategies.UseOriginal()(Ex("old"), Ex("new")).In.Body.Should().Be("old");
AggregationStrategies.UseOriginal()(null!, Ex("only")).In.Body.Should().Be("only");
}
[Fact]
public void Concat_MergeHeaders_IntoHeader_IntoProperty()
{
var concat = AggregationStrategies.Concat(", ");
var acc = concat(null!, Ex("a"));
concat(acc, Ex("b"));
concat(acc, Ex(3));
acc.In.Body.Should().Be("a, b, 3");
var merged = AggregationStrategies.MergeHeaders()(Ex("keep", ("h1", 1)), Ex("drop", ("h1", 2), ("h2", 3)));
merged.In.Body.Should().Be("keep");
merged.In.Headers["h1"].Should().Be(2, "the later header wins");
merged.In.Headers["h2"].Should().Be(3);
var enriched = AggregationStrategies.IntoHeader("customer")(Ex("order"), Ex("Acme"));
enriched.In.Body.Should().Be("order");
enriched.In.Headers["customer"].Should().Be("Acme");
var withProp = AggregationStrategies.IntoProperty("lookup")(Ex("order"), Ex(42));
withProp.Properties["lookup"].Should().Be(42);
}
[Fact]
public void Sum_Max_Min_OverExpression_NullFirst_AndSeeded()
{
var sum = AggregationStrategies.Sum("header.amount");
var acc = sum(null!, Ex("o1", ("amount", 10)));
sum(acc, Ex("o2", ("amount", 2.5m)));
sum(acc, Ex("o3", ("amount", "7.5")));
acc.In.Body.Should().Be(20m);
var seededMax = AggregationStrategies.Max("header.amount")(Ex("o1", ("amount", 3)), Ex("o2", ("amount", 9)));
seededMax.In.Body.Should().Be(9m);
var min = AggregationStrategies.Min("body.price");
var minAcc = min(Ex(new { price = 5 }), Ex(new { price = 2 }));
min(minAcc, Ex(new { price = 8 }));
minAcc.In.Body.Should().Be(2m);
var bad = () => AggregationStrategies.Sum("header.missing")(null!, Ex("x"));
bad.Should().Throw().WithMessage("*evaluated to null*");
}
[Theory]
[InlineData("groupedBody")]
[InlineData("GroupedExchange")]
[InlineData("useLatest")]
[InlineData("useOriginal")]
[InlineData("mergeHeaders")]
[InlineData("concat:;")]
[InlineData("intoHeader:customer")]
[InlineData("intoProperty:lookup")]
[InlineData("sum:header.amount")]
[InlineData("max:header.amount")]
[InlineData("min:header.amount")]
public void ByName_ResolvesEveryDocumentedName(string name)
=> AggregationStrategies.ByName(name).Should().NotBeNull();
[Theory]
[InlineData("nope")]
[InlineData("intoHeader")]
[InlineData("sum:")]
public void ByName_RejectsUnknownOrIncomplete(string name)
{
var act = () => AggregationStrategies.ByName(name);
act.Should().Throw();
}
// ── End-to-end ───────────────────────────────────────────────────────────────
[Fact]
public async Task Aggregate_WithGroupedBody_CompletesByCount()
{
await using var ctx = new RouteContext().AddRoutes(b => b
.From("direct://agg")
.Aggregate(e => "all", AggregationStrategies.GroupedBody(), agg => agg.In.Body is List { Count: >= 3 })
.To("mock://agg-out")
.EndAggregate());
await ctx.Start();
foreach (var body in new[] { "a", "b", "c" })
await ctx.SendBody("direct://agg", body);
await ctx.Mock("mock://agg-out").ExpectMessageCount(1).AssertIsSatisfiedAsync(Wait);
ctx.Mock("mock://agg-out").ReceivedExchanges[0].In.Body.Should().BeEquivalentTo(new List { "a", "b", "c" });
}
[Fact]
public async Task Aggregate_WithSum_CompletesByTotal()
{
await using var ctx = new RouteContext().AddRoutes(b => b
.From("direct://sum")
.Aggregate(e => "all", AggregationStrategies.Sum("header.amount"), agg => agg.In.Body is decimal d && d >= 100)
.To("mock://sum-out")
.EndAggregate());
await ctx.Start();
await ctx.SendBodyAndHeader("direct://sum", "o1", "amount", 40);
await ctx.SendBodyAndHeader("direct://sum", "o2", "amount", 70);
await ctx.Mock("mock://sum-out").ExpectBodies(110m).AssertIsSatisfiedAsync(Wait);
}
[Fact]
public async Task Multicast_WithConcat_AndWithoutStrategy()
{
await using var ctx = new RouteContext().AddRoutes(b =>
{
b.From("direct://a").SetBody("A");
b.From("direct://b").SetBody("B");
b.From("direct://mc").Multicast().AggregationStrategy(AggregationStrategies.Concat("+")).To("direct://a").To("direct://b").EndMulticast().To("mock://mc-out");
b.From("direct://mc-plain").Multicast().To("direct://a").To("direct://b").EndMulticast().To("mock://mc-plain-out");
});
await ctx.Start();
await ctx.SendBody("direct://mc", "orig");
await ctx.SendBody("direct://mc-plain", "orig");
await ctx.Mock("mock://mc-out").ExpectBodies("A+B").AssertIsSatisfiedAsync(Wait);
// Pinned: without a strategy the original body stays; the targets' results are not merged back.
await ctx.Mock("mock://mc-plain-out").ExpectBodies("orig").AssertIsSatisfiedAsync(Wait);
}
/// Code review 2026-09-01: bodies are cloned by reference, so a strategy must never append to a list it did not create.
[Fact]
public async Task Multicast_GroupedBody_DoesNotMutateAnIncomingList()
{
await using var ctx = new RouteContext().AddRoutes(b =>
{
b.From("direct://keep").SetHeader("seen", true); // keeps the incoming list as its body
b.From("direct://replace").SetBody("B");
b.From("direct://mc-list").Multicast().AggregationStrategy(AggregationStrategies.GroupedBody())
.To("direct://keep").To("direct://replace").EndMulticast().To("mock://mc-list-out");
});
await ctx.Start();
var incoming = new List { "x", "y" };
await ctx.SendBody("direct://mc-list", incoming);
await ctx.Mock("mock://mc-list-out").ExpectMessageCount(1).AssertIsSatisfiedAsync(Wait);
incoming.Should().Equal("x", "y"); // the caller's list is shared by every branch clone and must stay untouched
var grouped = (List)ctx.Mock("mock://mc-list-out").ReceivedExchanges[0].In.Body!;
grouped.Should().HaveCount(2);
grouped[0].Should().BeSameAs(incoming, "the first branch's body is the incoming list itself");
grouped[1].Should().Be("B");
}
/// Code review 2026-09-01: the clone whose body the strategy handed to the original must not be disposed together with that body.
[Fact]
public async Task Multicast_UseLatest_DoesNotDisposeTheAdoptedStreamBody()
{
await using var ctx = new RouteContext().AddRoutes(b =>
{
b.From("direct://stream-branch").Process(e => e.In.Body = new MemoryStream("reply"u8.ToArray()));
b.From("direct://mc-stream").Multicast().AggregationStrategy(AggregationStrategies.UseLatest()).To("direct://stream-branch").EndMulticast();
});
await ctx.Start();
using var template = new ProducerTemplate(ctx);
template.Start();
var exchange = Exchange.Create(new Message("in"), null); // caller-owned: the template does not dispose it
await template.SendAsync("direct://mc-stream", exchange);
var body = exchange.In.Body.Should().BeOfType().Subject;
body.CanRead.Should().BeTrue("the aggregated clone's body now belongs to the original exchange");
}
/// Code review 2026-09-01: a numeric body on the seeded first exchange is not the running total; it goes through the expression like every other.
[Fact]
public async Task Sum_OverExchangesWithNumericBodies_SumsTheExpression_NotTheBodies()
{
await using var ctx = new RouteContext().AddRoutes(b => b
.From("direct://sum-bodies")
.Aggregate(_ => "all", AggregationStrategies.Sum("header.amount"), agg => agg.In.Body is decimal d && d >= 3)
.To("mock://sum-bodies-out")
.EndAggregate());
await ctx.Start();
await ctx.SendBodyAndHeader("direct://sum-bodies", 100, "amount", 1);
await ctx.SendBodyAndHeader("direct://sum-bodies", 200, "amount", 2);
await ctx.Mock("mock://sum-bodies-out").ExpectBodies(3m).AssertIsSatisfiedAsync(Wait);
}
[Fact]
public async Task Split_WithGroupedBody_CollectsProcessedFragments()
{
await using var ctx = new RouteContext().AddRoutes(b => b
.From("direct://split")
.Split(e => (IEnumerable)e.In.Body!)
.AggregationStrategy(AggregationStrategies.GroupedBody())
.SetBody(e => ((string)e.In.Body!).ToUpperInvariant())
.EndSplit()
.To("mock://split-out"));
await ctx.Start();
await ctx.SendBody("direct://split", new object?[] { "a", "b" });
await ctx.Mock("mock://split-out").ExpectMessageCount(1).AssertIsSatisfiedAsync(Wait);
ctx.Mock("mock://split-out").ReceivedExchanges[0].In.Body.Should().BeEquivalentTo(new List { "A", "B" });
}
[Fact]
public async Task Enrich_WithoutStrategy_IsUseLatest()
{
await using var ctx = new RouteContext().AddRoutes(b => b
.From("direct://enrich").Enrich("mock://svc").To("mock://enrich-out"));
await ctx.Start();
ctx.Mock("mock://svc").WheneverAny().SetBody("reply").SetHeader("from-svc", true);
await ctx.SendBody("direct://enrich", "question");
await ctx.Mock("mock://enrich-out").ExpectBodies("reply").ExpectHeader("from-svc", true).AssertIsSatisfiedAsync(Wait);
}
[Fact]
public async Task Enrich_WithIntoHeader_KeepsBody()
{
await using var ctx = new RouteContext().AddRoutes(b => b
.From("direct://enrich-h").Enrich("mock://crm", AggregationStrategies.IntoHeader("customer")).To("mock://enrich-h-out"));
await ctx.Start();
ctx.Mock("mock://crm").WheneverAny().SetBody("Acme Ltd");
await ctx.SendBody("direct://enrich-h", "order-1");
await ctx.Mock("mock://enrich-h-out").ExpectBodies("order-1").ExpectHeader("customer", "Acme Ltd").AssertIsSatisfiedAsync(Wait);
}
[Fact]
public async Task PollEnrich_WithoutStrategy_TakesThePolledMessage()
{
await using var ctx = new RouteContext().AddRoutes(b =>
{
b.From("direct://poll").PollEnrich("direct://poll-source", TimeSpan.FromSeconds(5)).To("mock://poll-out");
b.From("direct://poll-source").SetBody("polled").SetHeader("from-poll", true);
});
await ctx.Start();
await ctx.SendBody("direct://poll", "original");
await ctx.Mock("mock://poll-out").ExpectBodies("polled").ExpectHeader("from-poll", true).AssertIsSatisfiedAsync(Wait);
}
}
Path: redb-route/tests/redb.Route.Tests/Batching/BatchCollectorTests.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/tests/redb.Route.Tests/Batching/BatchCollectorTests.cs
----
using AwesomeAssertions;
using redb.Route.Batching;
namespace redb.Route.Tests.Batching;
///
/// The batch collection contract: size, idle timeout restarted by every message, hard interval from the first
/// message, and a stop mid-batch. The transport is scripted on a clock of its own, so no test waits.
///
public class BatchCollectorTests
{
/// A clock the scripted transport moves.
private sealed class ManualTime : TimeProvider
{
public DateTimeOffset Now { get; set; } = new(2026, 11, 17, 12, 0, 0, TimeSpan.Zero);
public override DateTimeOffset GetUtcNow() => Now;
}
///
/// Messages that arrive at given offsets from the start. A receive call takes the arrivals due within its wait, up to
/// perCall of them (1 like Kafka's poll, 10 like SQS), moving the clock to the last one taken, or moves the
/// clock by the whole wait when none is due.
///
private sealed class ScriptedTransport(ManualTime time, int perCall, params int[] arrivalsMs)
{
private readonly DateTimeOffset _start = time.Now;
private int _next;
public List Waits { get; } = [];
public ValueTask Receive(List into, int max, TimeSpan wait, CancellationToken ct)
{
ct.ThrowIfCancellationRequested();
Waits.Add(wait);
var until = time.Now + wait;
var added = 0;
while (added < Math.Min(max, perCall) && _next < arrivalsMs.Length
&& _start.AddMilliseconds(arrivalsMs[_next]) <= until)
{
var at = _start.AddMilliseconds(arrivalsMs[_next]);
if (at > time.Now) time.Now = at;
into.Add(_next++);
added++;
}
if (added == 0)
time.Now = until;
return ValueTask.FromResult(added);
}
}
private static BatchCollector Collector(ManualTime time, ScriptedTransport transport, int max, int pollMs, int? intervalMs = null)
=> new(new BatchOptions(max, TimeSpan.FromMilliseconds(pollMs), intervalMs is { } i ? TimeSpan.FromMilliseconds(i) : null),
transport.Receive, time);
[Fact]
public async Task Collect_StopsAtMaxMessages()
{
var time = new ManualTime();
var transport = new ScriptedTransport(time, 1, 0, 10, 20, 30, 40);
var batch = await Collector(time, transport, max: 3, pollMs: 1000).CollectAsync(CancellationToken.None);
batch.Items.Should().Equal(0, 1, 2);
batch.Interrupted.Should().BeFalse();
}
[Fact]
public async Task Collect_SeveralPerCall_NeverTakesMoreThanMax()
{
var time = new ManualTime();
var transport = new ScriptedTransport(time, 10, 0, 0, 0, 0, 0, 0, 0);
var batch = await Collector(time, transport, max: 4, pollMs: 1000).CollectAsync(CancellationToken.None);
batch.Items.Should().Equal(0, 1, 2, 3);
}
[Fact]
public async Task Collect_IdleTimeout_RestartsWithEveryMessage()
{
// Messages 400 ms apart under a 500 ms idle timeout keep the batch open; the 900 ms gap closes it.
var time = new ManualTime();
var transport = new ScriptedTransport(time, 1, 0, 400, 800, 1200, 2100);
var batch = await Collector(time, transport, max: 100, pollMs: 500).CollectAsync(CancellationToken.None);
batch.Items.Should().Equal(0, 1, 2, 3);
(time.Now - new DateTimeOffset(2026, 11, 17, 12, 0, 0, TimeSpan.Zero)).Should().Be(TimeSpan.FromMilliseconds(1700));
}
[Fact]
public async Task Collect_Interval_IsAHardLimitFromTheFirstMessage()
{
// A steady stream never goes idle; the 1000 ms interval from the first message closes the batch.
var time = new ManualTime();
var arrivals = Enumerable.Range(0, 50).Select(i => 300 + i * 100).ToArray();
var transport = new ScriptedTransport(time, 1, arrivals);
var batch = await Collector(time, transport, max: 100, pollMs: 500, intervalMs: 1000).CollectAsync(CancellationToken.None);
batch.Items.Should().HaveCount(11, "the messages at 300, 400, ... 1300 ms fall within 1000 ms of the first");
transport.Waits.Should().OnlyContain(w => w <= TimeSpan.FromMilliseconds(1000));
}
[Fact]
public async Task Collect_NothingWithinPollTimeout_ReturnsAnEmptyBatch()
{
var time = new ManualTime();
var transport = new ScriptedTransport(time, 1, 5000);
var batch = await Collector(time, transport, max: 10, pollMs: 1000).CollectAsync(CancellationToken.None);
batch.Items.Should().BeEmpty();
batch.Interrupted.Should().BeFalse();
transport.Waits.Should().Equal(TimeSpan.FromMilliseconds(1000));
}
[Fact]
public async Task Collect_StopMidBatch_ReturnsWhatItHas_Interrupted()
{
var time = new ManualTime();
using var stop = new CancellationTokenSource();
var received = 0;
BatchReceive receive = (into, _, _, ct) =>
{
ct.ThrowIfCancellationRequested();
into.Add(received++);
if (received == 2)
stop.Cancel();
return ValueTask.FromResult(1);
};
var batch = await new BatchCollector(new BatchOptions(10, TimeSpan.FromSeconds(1)), receive, time).CollectAsync(stop.Token);
batch.Items.Should().Equal(0, 1);
batch.Interrupted.Should().BeTrue();
}
[Fact]
public async Task Collect_StopWhileWaitingForTheFirst_IsNotInterrupted()
{
using var stop = new CancellationTokenSource();
BatchReceive receive = async (_, _, _, ct) =>
{
await stop.CancelAsync();
ct.ThrowIfCancellationRequested();
return 0;
};
var batch = await new BatchCollector(new BatchOptions(10, TimeSpan.FromSeconds(1)), receive).CollectAsync(stop.Token);
batch.Items.Should().BeEmpty();
batch.Interrupted.Should().BeFalse("nothing was taken from the broker, so nothing is given back");
}
}
Path: redb-route/tests/redb.Route.Tests/Batching/BatchDispatcherTests.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/tests/redb.Route.Tests/Batching/BatchDispatcherTests.cs
----
using AwesomeAssertions;
using redb.Route.Abstractions;
using redb.Route.Batching;
using redb.Route.Core;
using redb.Route.Processors;
namespace redb.Route.Tests.Batching;
///
/// The batch exchange and the settle boundary: body a list of (one message too), shared transport
/// headers, the route run once, and exactly one settlement after it.
///
public class BatchDispatcherTests
{
private sealed record Record(string Body, string Topic, int Partition);
private sealed class RecordingSettlement : IBatchSettlement
{
public List Calls { get; } = [];
public Exception? Failure { get; private set; }
public bool ScopeOpenAtSettle { get; private set; }
private bool _scopeOpen;
public ValueTask BeforeRouteAsync(IExchange batch, IReadOnlyList items, CancellationToken ct)
{
Calls.Add("before");
_scopeOpen = true;
return ValueTask.FromResult(new Scope(this));
}
public ValueTask AcceptAsync(IExchange batch, IReadOnlyList items, CancellationToken ct)
{
ScopeOpenAtSettle = _scopeOpen;
Calls.Add($"accept:{items.Count}");
return ValueTask.CompletedTask;
}
public ValueTask RejectAsync(IExchange batch, IReadOnlyList items, Exception failure, CancellationToken ct)
{
ScopeOpenAtSettle = _scopeOpen;
Failure = failure;
Calls.Add($"reject:{items.Count}");
return ValueTask.CompletedTask;
}
public ValueTask ReturnAsync(IReadOnlyList items, CancellationToken ct)
{
Calls.Add($"return:{items.Count}");
return ValueTask.CompletedTask;
}
private sealed class Scope(RecordingSettlement owner) : IDisposable
{
public void Dispose()
{
owner._scopeOpen = false;
owner.Calls.Add("scope-closed");
}
}
}
private static IMessage ToMessage(Record record, IExchange _)
{
var message = new Message(record.Body);
message.Headers["topic"] = record.Topic;
message.Headers["partition"] = record.Partition;
return message;
}
private static BatchDispatcher Dispatcher(IProcessor route, IBatchSettlement settlement) =>
new(route, settlement, ToMessage, scopeFactory: null, sharedHeaders: ["topic", "partition"]);
[Fact]
public async Task Dispatch_BodyIsAListOfMessages_RouteRunsOnce_AcceptedOnceAfterTheRoute()
{
var runs = new List();
object? body = null;
var settlement = new RecordingSettlement();
var route = new DelegateProcessor(ex =>
{
runs.Add(ex);
body = ex.In.Body;
settlement.Calls.Add("route");
});
var outcome = await Dispatcher(route, settlement)
.DispatchAsync([new("a", "t", 0), new("b", "t", 1)], default, CancellationToken.None);
outcome.Should().Be(BatchOutcome.Accepted);
runs.Should().ContainSingle().Which.Pattern.Should().Be(ExchangePattern.InOnly);
body.Should().BeOfType>().Which.Select(m => m.Body).Should().Equal("a", "b");
settlement.Calls.Should().Equal("before", "route", "scope-closed", "accept:2");
settlement.ScopeOpenAtSettle.Should().BeFalse();
}
[Fact]
public async Task Dispatch_OneMessage_IsStillAList()
{
object? body = null;
var outcome = await Dispatcher(new DelegateProcessor(ex => body = ex.In.Body), new RecordingSettlement())
.DispatchAsync([new("only", "t", 0)], default, CancellationToken.None);
outcome.Should().Be(BatchOutcome.Accepted);
body.Should().BeOfType>().Which.Should().ContainSingle().Which.Body.Should().Be("only");
}
[Fact]
public async Task Dispatch_SharedHeaders_OnlyWhenEveryMessageAgrees_NoSizeHeader()
{
IMessage? batch = null;
await Dispatcher(new DelegateProcessor(ex => batch = ex.In), new RecordingSettlement())
.DispatchAsync([new("a", "orders", 0), new("b", "orders", 1)], default, CancellationToken.None);
batch!.Headers.Should().ContainKey("topic").WhoseValue.Should().Be("orders");
batch.Headers.Should().NotContainKey("partition", "the messages come from two partitions");
batch.Headers.Should().HaveCount(1, "the size is body.Count, not a header");
}
[Fact]
public async Task Dispatch_FailureLeftOnTheExchange_IsRejectedOnce()
{
var settlement = new RecordingSettlement();
var failure = new InvalidOperationException("boom");
var outcome = await Dispatcher(new DelegateProcessor(ex => ex.Exception = failure), settlement)
.DispatchAsync([new("a", "t", 0), new("b", "t", 0)], default, CancellationToken.None);
outcome.Should().Be(BatchOutcome.Rejected);
settlement.Calls.Should().Equal("before", "scope-closed", "reject:2");
settlement.Failure.Should().BeSameAs(failure);
}
[Fact]
public async Task Dispatch_FailureThrownByTheRoute_IsRejectedOnce()
{
var settlement = new RecordingSettlement();
var outcome = await Dispatcher(new DelegateProcessor(_ => throw new TimeoutException("slow")), settlement)
.DispatchAsync([new("a", "t", 0)], default, CancellationToken.None);
outcome.Should().Be(BatchOutcome.Rejected);
settlement.Calls.Should().Equal("before", "scope-closed", "reject:1");
settlement.Failure.Should().BeOfType();
}
[Fact]
public async Task Dispatch_HandledFailure_IsAccepted()
{
var settlement = new RecordingSettlement();
var route = new DelegateProcessor(ex =>
{
ex.Exception = new InvalidOperationException("handled");
ex.ExceptionHandled = true;
});
var outcome = await Dispatcher(route, settlement).DispatchAsync([new("a", "t", 0)], default, CancellationToken.None);
outcome.Should().Be(BatchOutcome.Accepted);
}
[Fact]
public async Task Dispatch_CancelledWhileTheRouteRuns_IsReturned_AndTheCancellationIsThrown()
{
using var processing = new CancellationTokenSource();
var settlement = new RecordingSettlement();
var route = new DelegateProcessor(async (_, ct) =>
{
await processing.CancelAsync();
ct.ThrowIfCancellationRequested();
});
var act = () => Dispatcher(route, settlement).DispatchAsync([new("a", "t", 0), new("b", "t", 0)], default, processing.Token);
await act.Should().ThrowAsync();
settlement.Calls.Should().Equal("before", "scope-closed", "return:2");
}
[Fact]
public async Task Dispatch_EmptyBatch_IsRefused()
{
var act = () => Dispatcher(new DelegateProcessor(_ => { }), new RecordingSettlement())
.DispatchAsync([], default, CancellationToken.None);
await act.Should().ThrowAsync();
}
}
Path: redb-route/tests/redb.Route.Tests/Batching/BatchOptionsTests.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/tests/redb.Route.Tests/Batching/BatchOptionsTests.cs
----
using AwesomeAssertions;
using redb.Route.Batching;
namespace redb.Route.Tests.Batching;
/// The batch options of an endpoint: batch mode only by batching=true , start failures named.
public class BatchOptionsTests
{
[Fact]
public void Resolve_BatchingOff_NoOptions_IsNull()
{
BatchOptions.Resolve("kafka:orders", batching: false, maxBatchMessages: null, pollTimeoutMs: 1000,
batchingIntervalMs: null, defaultMaxBatchMessages: 500).Should().BeNull();
}
[Theory]
[InlineData(10, null, "maxBatchMessages")]
[InlineData(null, 2000, "batchingIntervalMs")]
public void Resolve_BatchOptionWithoutBatching_FailsTheStart(int? max, int? interval, string option)
{
var act = () => BatchOptions.Resolve("kafka:orders", false, max, 1000, interval, 500);
act.Should().Throw()
.WithMessage($"*kafka:orders*{option}*batching=true*");
}
[Fact]
public void Resolve_BatchingOn_AppliesTheConnectorDefault()
{
var options = BatchOptions.Resolve("kafka:orders", true, null, 1000, null, 500)!;
options.MaxMessages.Should().Be(500);
options.PollTimeout.Should().Be(TimeSpan.FromSeconds(1));
options.Interval.Should().BeNull();
}
[Fact]
public void Resolve_BatchingOn_TakesTheOptions()
{
var options = BatchOptions.Resolve("kafka:orders", true, 20, 300, 5000, 500)!;
options.MaxMessages.Should().Be(20);
options.PollTimeout.Should().Be(TimeSpan.FromMilliseconds(300));
options.Interval.Should().Be(TimeSpan.FromSeconds(5));
}
[Theory]
[InlineData(0, 1000, null, "maxBatchMessages")]
[InlineData(10, 0, null, "pollTimeoutMs")]
[InlineData(10, 1000, 0, "batchingIntervalMs")]
public void Resolve_ValueOutOfRange_FailsTheStart_NamingTheEndpoint(int max, int poll, int? interval, string option)
{
var act = () => BatchOptions.Resolve("rabbitmq:orders", true, max, poll, interval, 500);
act.Should().Throw().WithMessage($"*rabbitmq:orders*{option}*");
}
}
Path: redb-route/tests/redb.Route.Tests/CancellationStatisticsTests.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/tests/redb.Route.Tests/CancellationStatisticsTests.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
namespace redb.Route.Tests;
///
/// A cooperative cancellation is not a route error (BR-10). A dashboard that closes mid-poll
/// cancels the caller's token; the exchange is abandoned, not failed — yet the statistics wrapper
/// counted it into Errors , so a healthy management route turned red on the Error-Prone
/// panel, and endpoint health degraded for five minutes per closed browser tab.
///
/// The rule, applied at every counting and event site: an
/// with the caller's token cancelled is a cancellation (counted in Cancelled , notified to
/// nobody); an OCE while the caller's token is still live is an internal failure and stays an
/// error. This is the same reading the error-handling layer has always had — retry never retries
/// cancellation, the dead-letter channel never parks it, OnException never handles it.
///
///
public sealed class CancellationStatisticsTests
{
private static IEndpointStatistics Stats(RouteContext context, string uri)
=> (IEndpointStatistics)context.GetEndpoint(uri);
private static async Task StartedProducer(RouteContext context, string uri)
{
await context.Start();
var producer = context.GetEndpoint(uri).CreateProducer();
await producer.Start();
return producer;
}
// ── The consumer-side wrapper (StatisticsProcessor) ──
[Fact]
public async Task A_cooperative_cancellation_is_counted_as_cancelled_not_as_an_error()
{
using var cts = new CancellationTokenSource();
await using var context = new RouteContext();
context.AddRoutes(r => r.From("direct:coop").Process((_, ct) =>
{
cts.Cancel();
throw new OperationCanceledException(ct);
}));
var producer = await StartedProducer(context, "direct:coop");
var act = () => producer.Process(new Exchange(new Message("m")), cts.Token);
await act.Should().ThrowAsync();
var stats = Stats(context, "direct:coop");
stats.Errors.Should().Be(0, "the caller walked away; the route did nothing wrong");
stats.Cancelled.Should().Be(1, "the abandonment is a signal of its own — a storm of these is exactly what the panel case would have shown");
stats.HealthStatus.Should().Be(EndpointHealthStatus.Healthy,
"one closed dashboard must not degrade endpoint health for five minutes");
}
[Fact]
public async Task An_internal_cancellation_with_a_live_caller_stays_an_error()
{
await using var context = new RouteContext();
context.AddRoutes(r => r.From("direct:internal")
.Process(_ => throw new OperationCanceledException()));
var producer = await StartedProducer(context, "direct:internal");
var act = () => producer.Process(new Exchange(new Message("m")), CancellationToken.None);
await act.Should().ThrowAsync();
var stats = Stats(context, "direct:internal");
stats.Errors.Should().Be(1, "a route-side timeout is the route's own failure to answer in time");
stats.Cancelled.Should().Be(0);
}
[Fact]
public async Task A_cancellation_parked_on_the_exchange_reads_the_same_as_a_thrown_one()
{
// The wrapper has a second counting branch: an exception set on the exchange without a
// throw (a parallel branch aggregates its failure there). The same rule applies to it.
using var cts = new CancellationTokenSource();
await using var context = new RouteContext();
context.AddRoutes(r => r.From("direct:parked").Process((exchange, ct) =>
{
cts.Cancel();
exchange.Exception = new OperationCanceledException(ct);
return Task.CompletedTask;
}));
var producer = await StartedProducer(context, "direct:parked");
await producer.Process(new Exchange(new Message("m")), cts.Token);
var stats = Stats(context, "direct:parked");
stats.Errors.Should().Be(0);
stats.Cancelled.Should().Be(1);
}
// ── The producer-side funnel (CountedSend) ──
[Fact]
public async Task A_cancelled_send_does_not_error_the_target_endpoint()
{
// Mirrors StatisticsOwnershipTests.TemplateSend_Failure_CountsBothLegs: direct: is one
// endpoint object playing both roles, so a cooperative cancellation lands on it twice —
// the send leg (CountedSend) and the pipeline leg (StatisticsProcessor) — in Cancelled,
// and exactly zero times in Errors.
using var cts = new CancellationTokenSource();
await using var context = new RouteContext();
context.AddRoutes(r =>
{
r.From("direct:outer").To("direct:coop-target");
r.From("direct:coop-target").Process((_, ct) =>
{
cts.Cancel();
throw new OperationCanceledException(ct);
});
});
var producer = await StartedProducer(context, "direct:outer");
var act = () => producer.Process(new Exchange(new Message("m")), cts.Token);
await act.Should().ThrowAsync();
var target = Stats(context, "direct:coop-target");
target.Errors.Should().Be(0, "neither leg failed; the caller cancelled both");
target.Cancelled.Should().Be(2, "exactly two legs, as with errors: the send cancellation + the pipeline cancellation");
var outer = Stats(context, "direct:outer");
outer.Errors.Should().Be(0);
outer.Cancelled.Should().Be(1);
}
// ── The lifecycle event layer (ExchangeEventsProcessor) ──
private sealed class CountingListener : IRouteLifecycleListener
{
public int Received;
public int Completed;
public int Failed;
public Task OnExchangeReceived(string routeId, IExchange exchange, CancellationToken ct)
{
Interlocked.Increment(ref Received);
return Task.CompletedTask;
}
public Task OnExchangeCompleted(string routeId, IExchange exchange, CancellationToken ct)
{
Interlocked.Increment(ref Completed);
return Task.CompletedTask;
}
public Task OnExchangeFailed(string routeId, IExchange exchange, Exception exception, CancellationToken ct)
{
Interlocked.Increment(ref Failed);
return Task.CompletedTask;
}
}
[Fact]
public async Task Listeners_do_not_hear_failed_for_a_cooperative_cancellation()
{
// An abandoned exchange is neither completed nor failed; the listener hears it arrive and
// then hears nothing, which is the truthful account of what happened.
var listener = new CountingListener();
using var cts = new CancellationTokenSource();
await using var context = new RouteContext();
context.AddLifecycleListener(listener);
context.AddRoutes(r => r.From("direct:coop-events").Process((_, ct) =>
{
cts.Cancel();
throw new OperationCanceledException(ct);
}));
var producer = await StartedProducer(context, "direct:coop-events");
var act = () => producer.Process(new Exchange(new Message("m")), cts.Token);
await act.Should().ThrowAsync();
listener.Received.Should().Be(1);
listener.Failed.Should().Be(0, "a client cancellation is not a route failure, NotifyBuilder must not count it as a failure");
listener.Completed.Should().Be(0);
}
[Fact]
public async Task Listeners_still_hear_failed_for_an_internal_cancellation()
{
var listener = new CountingListener();
await using var context = new RouteContext();
context.AddLifecycleListener(listener);
context.AddRoutes(r => r.From("direct:internal-events")
.Process(_ => throw new OperationCanceledException()));
var producer = await StartedProducer(context, "direct:internal-events");
var act = () => producer.Process(new Exchange(new Message("m")), CancellationToken.None);
await act.Should().ThrowAsync();
listener.Failed.Should().Be(1);
}
}
Path: redb-route/tests/redb.Route.Tests/Cluster/CapturingLoggerProvider.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/tests/redb.Route.Tests/Cluster/CapturingLoggerProvider.cs
----
using System.Collections.Concurrent;
using Microsoft.Extensions.Logging;
namespace redb.Route.Tests.Cluster;
///
/// Test-only logger provider that captures every log entry into an in-memory list,
/// for assertions on warning messages emitted during route compilation.
///
internal sealed class CapturingLoggerProvider : ILoggerProvider
{
public ConcurrentBag Entries { get; } = new();
public ILogger CreateLogger(string categoryName) => new Logger(this, categoryName);
public void Dispose() { }
internal sealed record LogEntry(string Category, LogLevel Level, string Message, Exception? Exception);
private sealed class Logger : ILogger
{
private readonly CapturingLoggerProvider _owner;
private readonly string _category;
public Logger(CapturingLoggerProvider owner, string category)
{
_owner = owner;
_category = category;
}
public IDisposable? BeginScope(TState state) where TState : notnull => null;
public bool IsEnabled(LogLevel logLevel) => true;
public void Log(LogLevel logLevel, EventId eventId, TState state,
Exception? exception, Func formatter)
{
_owner.Entries.Add(new LogEntry(_category, logLevel, formatter(state, exception), exception));
}
}
}
Path: redb-route/tests/redb.Route.Tests/Cluster/RoutePolicyDescriptorTests.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/tests/redb.Route.Tests/Cluster/RoutePolicyDescriptorTests.cs
----
using AwesomeAssertions;
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Configuration;
using redb.Route.Core;
using redb.Route.Definitions;
namespace redb.Route.Tests.Cluster;
///
/// Verifies reports the effective cluster
/// policy: AllNodes for standalone routes, ClusterLeader when a
/// is registered, Custom for explicit policies.
///
public class RoutePolicyDescriptorTests : IAsyncLifetime
{
private readonly RouteContext _context;
private readonly CapturingLoggerProvider _capture = new();
public RoutePolicyDescriptorTests()
{
var lf = LoggerFactory.Create(b => b.AddProvider(_capture).SetMinimumLevel(LogLevel.Debug));
_context = new RouteContext(loggerFactory: lf, options: new RouteEngineOptions { StartupChecks = true });
}
public Task InitializeAsync() => Task.CompletedTask;
public async Task DisposeAsync()
{
await _context.DisposeAsync();
GC.SuppressFinalize(this);
}
[Fact]
public async Task Standalone_route_reports_AllNodes()
{
_context.AddRoutes(r => r.From("direct://a").RouteId("a").Process(_ => { }));
await _context.Start();
var d = _context.GetRoutePolicy("a");
d.RequestedCluster.Should().BeFalse();
d.EffectivePolicy.Should().Be("AllNodes");
d.PolicyFactoryType.Should().BeNull();
}
[Fact]
public async Task Cluster_route_without_factory_reports_AllNodes_with_warning_reason()
{
_context.AddRoutes(r => r.From("direct://b").RouteId("b").Cluster(true).Process(_ => { }));
await _context.Start();
var d = _context.GetRoutePolicy("b");
d.RequestedCluster.Should().BeTrue();
d.EffectivePolicy.Should().Be("AllNodes");
d.PolicyFactoryType.Should().BeNull();
d.Reason.Should().Contain("no IRoutePolicyFactory");
}
[Fact]
public async Task Cluster_route_with_factory_reports_ClusterLeader()
{
_context.AddRoutePolicyFactory(new StubFactory());
_context.AddRoutes(r => r.From("direct://c").RouteId("c").Cluster(true).Process(_ => { }));
await _context.Start();
var d = _context.GetRoutePolicy("c");
d.RequestedCluster.Should().BeTrue();
d.EffectivePolicy.Should().Be("ClusterLeader");
d.PolicyFactoryType.Should().Contain(nameof(StubFactory));
}
[Fact]
public async Task Cluster_route_declined_by_a_factory_reports_AllNodes_and_the_decline()
{
_context.AddRoutePolicyFactory(new DecliningFactory());
_context.AddRoutes(r => r.From("direct://d").RouteId("d").Cluster(true).Process(_ => { }));
await _context.Start();
var d = _context.GetRoutePolicy("d");
d.RequestedCluster.Should().BeTrue();
d.EffectivePolicy.Should().Be("AllNodes");
d.Reason.Should().Contain("declined");
_capture.Entries.Should().NotContain(e => e.Message.Contains("no IRoutePolicyFactory is registered"),
"a factory is registered; it declined the route and says why itself");
}
[Fact]
public void Unknown_route_returns_AllNodes_NotFound_reason()
{
var d = _context.GetRoutePolicy("ghost");
d.EffectivePolicy.Should().Be("AllNodes");
d.Reason.Should().Be("Route not found");
}
private sealed class StubFactory : IRoutePolicyFactory
{
public IRoutePolicy? CreateRoutePolicy(IRouteContext context, string routeId, RouteDefinition definition)
=> new StubPolicy();
}
private sealed class DecliningFactory : IRoutePolicyFactory
{
public IRoutePolicy? CreateRoutePolicy(IRouteContext context, string routeId, RouteDefinition definition) => null;
}
private sealed class StubPolicy : IRoutePolicy { }
}
Path: redb-route/tests/redb.Route.Tests/Cluster/StartupWarningTests.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/tests/redb.Route.Tests/Cluster/StartupWarningTests.cs
----
using AwesomeAssertions;
using Microsoft.Extensions.Logging;
using redb.Route.Configuration;
using redb.Route.Core;
namespace redb.Route.Tests.Cluster;
///
/// Verifies the startup-check warning emitted when a route declares .Cluster(true)
/// but no is registered.
///
public class StartupWarningTests : IAsyncLifetime
{
private readonly CapturingLoggerProvider _capture = new();
private readonly RouteContext _context;
public StartupWarningTests()
{
var lf = LoggerFactory.Create(b => b.AddProvider(_capture).SetMinimumLevel(LogLevel.Debug));
_context = new RouteContext(loggerFactory: lf, options: new RouteEngineOptions { StartupChecks = true });
}
public Task InitializeAsync() => Task.CompletedTask;
public async Task DisposeAsync()
{
await _context.DisposeAsync();
GC.SuppressFinalize(this);
}
[Fact]
public async Task Cluster_route_without_factory_emits_warning_once()
{
_context.AddRoutes(r => r.From("direct://x").RouteId("x").Cluster(true).Process(_ => { }));
await _context.Start();
_capture.Entries
.Count(e => e.Level == LogLevel.Warning && e.Message.Contains("no IRoutePolicyFactory"))
.Should().Be(1);
}
[Fact]
public async Task Standalone_route_emits_no_warning()
{
_context.AddRoutes(r => r.From("direct://y").RouteId("y").Process(_ => { }));
await _context.Start();
_capture.Entries.Should().NotContain(e =>
e.Level == LogLevel.Warning && e.Message.Contains("IRoutePolicyFactory"));
}
[Fact]
public async Task StartupChecks_disabled_silences_the_warning()
{
await _context.DisposeAsync();
var lf = LoggerFactory.Create(b => b.AddProvider(_capture).SetMinimumLevel(LogLevel.Debug));
await using var ctx = new RouteContext(
loggerFactory: lf,
options: new RouteEngineOptions { StartupChecks = false });
ctx.AddRoutes(r => r.From("direct://z").RouteId("z").Cluster(true).Process(_ => { }));
await ctx.Start();
_capture.Entries.Should().NotContain(e =>
e.Level == LogLevel.Warning && e.Message.Contains("IRoutePolicyFactory"));
}
}
Path: redb-route/tests/redb.Route.Tests/Components/BeanComponentTests.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/tests/redb.Route.Tests/Components/BeanComponentTests.cs
----
using AwesomeAssertions;
using redb.Route.Abstractions;
using redb.Route.Core;
namespace redb.Route.Tests.Components;
// ── Public bean targets (bean: works through exported types only) ────────────
/// Sync bean with one suitable method returning a value.
public class GreeterBean
{
/// Bound from the URI query.
public string Prefix { get; set; } = "hello";
public string Greet(IExchange exchange) => $"{Prefix}:{exchange.In.Body}";
}
///
/// Counts its instances for the one test of endpoint sharing. A type of its own: the counter is process-wide, and a
/// type other test classes also create (GreeterBean, by BeanStepSugarTests running in parallel) adds their instances
/// to the count now and then.
///
public class CountedGreeterBean
{
public static int Instances;
public CountedGreeterBean() => Interlocked.Increment(ref Instances);
/// Bound from the URI query.
public string Prefix { get; set; } = "hello";
public string Greet(IExchange exchange) => $"{Prefix}:{exchange.In.Body}";
}
/// Bean with several suitable methods — method= is mandatory.
public class MultiBean
{
public void First(IExchange exchange) => exchange.In.Headers["called"] = "first";
public void Second(IExchange exchange) => exchange.In.Headers["called"] = "second";
}
/// Async bean: Task and Task<T> shapes, with the (IExchange, ct) priority form.
public class AsyncBean
{
public async Task Handle(IExchange exchange, CancellationToken ct)
{
await Task.Yield();
return $"async:{exchange.In.Body}";
}
public async Task Touch(IExchange exchange)
{
await Task.Yield();
exchange.In.Headers["touched"] = true;
}
public async ValueTask HandleValue(IExchange exchange)
{
await Task.Delay(20);
return $"value:{exchange.In.Body}";
}
public async ValueTask TouchValue(IExchange exchange)
{
await Task.Delay(20);
exchange.In.Headers["touched"] = true;
}
}
/// Void bean: the body must stay untouched.
public class VoidBean
{
public void Mark(IExchange exchange) => exchange.In.Headers["marked"] = true;
}
/// Bean with a secret-bearing property: the key must join the URI redaction set.
public class SecretBean
{
[Sensitive]
public string? ApiKey { get; set; }
public void Call(IExchange exchange) => exchange.In.Headers["apiKeyLength"] = ApiKey?.Length ?? 0;
}
internal class InternalBean
{
public void Handle(IExchange exchange) { }
}
/// Param-binding targets: ordinary typed parameters, overloads, ct, async.
public class CalcBean
{
public int Add(int a, int b) => a + b;
public string Add(string a, string b, string c) => a + b + c; // a different argument count
public string Upper(string text) => text.ToUpperInvariant();
public async Task Fetch(string id, CancellationToken ct)
{
await Task.Yield();
return $"row-{id}";
}
public int Answer() => 42;
// Ambient parameters: the exchange, its In message and the token are bound by type and are not counted
// among the arguments.
public string Require(IExchange exchange, string permission) => $"{permission}:{exchange.In.Body}";
public string Describe(IMessage message, string suffix) => $"{message.Body}+{suffix}";
public string Stamp(CancellationToken ct, string tag) => $"{tag}:{ct.CanBeCanceled}";
}
///
/// The bean: component. Both URI forms, method selection, return-value
/// semantics, property binding through the shared converter, [Sensitive] redaction, instance
/// caching by normalized URI, and the loud errors the plan demands.
///
public class BeanComponentTests : IAsyncLifetime
{
private readonly RouteContext _context = new();
public Task InitializeAsync() => Task.CompletedTask;
public async Task DisposeAsync()
{
await _context.DisposeAsync();
GC.SuppressFinalize(this);
}
private static string Q(Type t) => $"{t.FullName}, {t.Assembly.GetName().Name}";
private static IExchange Msg(object? body, params (string Name, object? Value)[] headers)
{
var exchange = new Exchange(new Message(body));
foreach (var (name, value) in headers) exchange.In.Headers[name] = value;
return exchange;
}
private async Task StartAndProducer(string fromUri)
{
await _context.Start();
var producer = _context.GetEndpoint(fromUri).CreateProducer();
await producer.Start();
return producer;
}
///
/// A static To's endpoint is created when its route starts (engine-wide behaviour, as Camel resolves a static
/// to(...) at startup, not a bean: special case), so a bad bean: target fails the start, with the same message it
/// used to give on the first send.
///
private Task> FirstSend(string fromUri)
=> Task.FromResult>(async () =>
{
var producer = await StartAndProducer(fromUri);
await producer.Process(new Exchange(new Message("x")));
});
// ── Registry form ────────────────────────────────────────────────────────
[Fact]
public async Task RegistryForm_InvokesTheRegisteredObject_AndResultBecomesTheBody()
{
_context.AddToRegistry("greeter", new GreeterBean { Prefix = "reg" });
_context.AddRoutes(r => r.From("direct://bean-reg").To("bean:#greeter?method=Greet"));
var producer = await StartAndProducer("direct://bean-reg");
var exchange = new Exchange(new Message("bob"));
await producer.Process(exchange);
exchange.In.Body.Should().Be("reg:bob");
}
[Fact]
public async Task RegistryForm_MissingObject_FailsTheStartNamingTheReference()
{
_context.AddRoutes(r => r.From("direct://bean-regx").To("bean:#absent?method=Greet"));
var act = await FirstSend("direct://bean-regx");
(await act.Should().ThrowAsync())
.WithMessage("*#absent*not in the context registry*");
}
// ── Type form ────────────────────────────────────────────────────────────
[Fact]
public async Task TypeForm_CreatesInstance_BindsProperties_AndResultBecomesTheBody()
{
_context.AddRoutes(r => r.From("direct://bean-type")
.To($"bean:{Q(typeof(GreeterBean))}?method=Greet&prefix=hi"));
var producer = await StartAndProducer("direct://bean-type");
var exchange = new Exchange(new Message("ann"));
await producer.Process(exchange);
exchange.In.Body.Should().Be("hi:ann");
}
[Fact]
public async Task TypeForm_MethodOptional_WhenExactlyOneSuitableMethod()
{
_context.AddRoutes(r => r.From("direct://bean-single")
.To($"bean:{Q(typeof(VoidBean))}"));
var producer = await StartAndProducer("direct://bean-single");
var exchange = new Exchange(new Message("x"));
await producer.Process(exchange);
exchange.In.Headers.Should().ContainKey("marked");
exchange.In.Body.Should().Be("x", "void must not touch the body");
}
[Fact]
public async Task TypeForm_AmbiguousMethods_ErrorListsTheCandidates()
{
_context.AddRoutes(r => r.From("direct://bean-multi")
.To($"bean:{Q(typeof(MultiBean))}"));
var act = await FirstSend("direct://bean-multi");
(await act.Should().ThrowAsync())
.WithMessage("*several suitable methods*First*Second*");
}
[Fact]
public async Task TypeForm_VersionPinnedName_IsRefusedWithExplanation()
{
_context.AddRoutes(r => r.From("direct://bean-ver")
.To("bean:Acme.X, Acme, Version=1.0.0.0, PublicKeyToken=null?method=Handle"));
var act = await FirstSend("direct://bean-ver");
(await act.Should().ThrowAsync())
.WithMessage("*pins an assembly version*");
}
[Fact]
public async Task TypeForm_NonPublicType_GetsItsOwnMessage()
{
_context.AddRoutes(r => r.From("direct://bean-int")
.To($"bean:{Q(typeof(InternalBean))}"));
var act = await FirstSend("direct://bean-int");
(await act.Should().ThrowAsync())
.WithMessage("*found but is not public*");
}
[Fact]
public async Task TypeForm_UnknownType_SaysNotFound()
{
_context.AddRoutes(r => r.From("direct://bean-unk")
.To("bean:Acme.No.Such.Type, Acme.Missing"));
var act = await FirstSend("direct://bean-unk");
(await act.Should().ThrowAsync())
.WithMessage("*was not found in the loaded assemblies*");
}
[Fact]
public async Task TypeForm_UnknownProperty_ErrorNamesTheWritableOnes()
{
_context.AddRoutes(r => r.From("direct://bean-prop")
.To($"bean:{Q(typeof(GreeterBean))}?method=Greet&nosuch=1"));
var act = await FirstSend("direct://bean-prop");
(await act.Should().ThrowAsync())
.WithMessage("*no writable public property 'nosuch'*Prefix*");
}
// ── Async shapes ─────────────────────────────────────────────────────────
[Fact]
public async Task AsyncTaskOfT_AwaitsAndPutsTheResultIntoTheBody()
{
_context.AddRoutes(r => r.From("direct://bean-async")
.To($"bean:{Q(typeof(AsyncBean))}?method=Handle"));
var producer = await StartAndProducer("direct://bean-async");
var exchange = new Exchange(new Message("m"));
await producer.Process(exchange);
exchange.In.Body.Should().Be("async:m");
}
[Fact]
public async Task AsyncTask_AwaitsAndLeavesTheBody()
{
_context.AddRoutes(r => r.From("direct://bean-task")
.To($"bean:{Q(typeof(AsyncBean))}?method=Touch"));
var producer = await StartAndProducer("direct://bean-task");
var exchange = new Exchange(new Message("m"));
await producer.Process(exchange);
exchange.In.Headers.Should().ContainKey("touched");
exchange.In.Body.Should().Be("m");
}
[Fact]
public async Task AsyncValueTaskOfT_AwaitsAndPutsTheResultIntoTheBody()
{
_context.AddRoutes(r => r.From("direct://bean-valuetask-t")
.To($"bean:{Q(typeof(AsyncBean))}?method=HandleValue"));
var producer = await StartAndProducer("direct://bean-valuetask-t");
var exchange = new Exchange(new Message("m"));
await producer.Process(exchange);
exchange.In.Body.Should().Be("value:m", "a ValueTask is awaited like a Task, not put into the body");
}
[Fact]
public async Task AsyncValueTask_AwaitsAndLeavesTheBody()
{
_context.AddRoutes(r => r.From("direct://bean-valuetask")
.To($"bean:{Q(typeof(AsyncBean))}?method=TouchValue"));
var producer = await StartAndProducer("direct://bean-valuetask");
var exchange = new Exchange(new Message("m"));
await producer.Process(exchange);
exchange.In.Headers.Should().ContainKey("touched", "the method is awaited before the step ends");
exchange.In.Body.Should().Be("m");
}
// ── Lifetime and redaction ───────────────────────────────────────────────
[Fact]
public async Task SameUri_SharesOneInstance_DifferentParametersGetTheirOwn()
{
var before = CountedGreeterBean.Instances;
_context.AddRoutes(r => r.From("direct://bean-life")
.To($"bean:{Q(typeof(CountedGreeterBean))}?method=Greet&prefix=a")
.To($"bean:{Q(typeof(CountedGreeterBean))}?method=Greet&prefix=a")
.To($"bean:{Q(typeof(CountedGreeterBean))}?method=Greet&prefix=b"));
var producer = await StartAndProducer("direct://bean-life");
await producer.Process(new Exchange(new Message("x")));
(CountedGreeterBean.Instances - before).Should().Be(2,
"equal URIs share one endpoint (and instance); a different parameter set is another endpoint");
}
// ── Camel-style parameter binding — method=name(arg, ...) ────────────────
[Fact]
public async Task Binding_TypedParameters_FromHeaderExpressions()
{
_context.AddRoutes(r => r.From("direct://bean-bind")
.To($"bean:{Q(typeof(CalcBean))}?method=Add(${{header.a}}, ${{header.b}})"));
var producer = await StartAndProducer("direct://bean-bind");
var exchange = Msg("x", ("a", 40), ("b", 2));
await producer.Process(exchange);
exchange.In.Body.Should().Be(42);
}
[Fact]
public async Task Binding_BodyExpression_ConvertsToTheParameterType()
{
_context.AddRoutes(r => r.From("direct://bean-bindb")
.To($"bean:{Q(typeof(CalcBean))}?method=Upper(${{body}})"));
var producer = await StartAndProducer("direct://bean-bindb");
var exchange = Msg("hello");
await producer.Process(exchange);
exchange.In.Body.Should().Be("HELLO");
}
[Fact]
public async Task Binding_OverloadPickedByArgumentCount()
{
_context.AddRoutes(r => r.From("direct://bean-bind3")
.To($"bean:{Q(typeof(CalcBean))}?method=Add(${{header.a}}, '-', ${{header.b}})"));
var producer = await StartAndProducer("direct://bean-bind3");
var exchange = Msg("x", ("a", "left"), ("b", "right"));
await producer.Process(exchange);
exchange.In.Body.Should().Be("left-right");
}
[Fact]
public async Task Binding_TrailingCancellationToken_IsFilledAutomatically()
{
_context.AddRoutes(r => r.From("direct://bean-bindct")
.To($"bean:{Q(typeof(CalcBean))}?method=Fetch(${{header.id}})"));
var producer = await StartAndProducer("direct://bean-bindct");
var exchange = Msg("x", ("id", 7));
await producer.Process(exchange);
exchange.In.Body.Should().Be("row-7");
}
[Fact]
public async Task Binding_EmptyArgumentList_CallsAParameterlessMethod()
{
_context.AddRoutes(r => r.From("direct://bean-bind0")
.To($"bean:{Q(typeof(CalcBean))}?method=Answer()"));
var producer = await StartAndProducer("direct://bean-bind0");
var exchange = Msg("x");
await producer.Process(exchange);
exchange.In.Body.Should().Be(42);
}
[Fact]
public async Task Binding_ExchangeParameter_IsInjectedByType()
{
// The headline case: bean:#x?method=Require('incident.view') with Require(IExchange, string).
// The exchange is supplied by the binding, so only 'incident.view' is read from the URI.
_context.AddRoutes(r => r.From("direct://bean-bindexchange")
.To($"bean:{Q(typeof(CalcBean))}?method=Require('incident.view')"));
var producer = await StartAndProducer("direct://bean-bindexchange");
var exchange = Msg("u-42");
await producer.Process(exchange);
exchange.In.Body.Should().Be("incident.view:u-42");
}
[Fact]
public async Task Binding_MessageParameter_IsInjectedByType()
{
_context.AddRoutes(r => r.From("direct://bean-bindmessage")
.To($"bean:{Q(typeof(CalcBean))}?method=Describe('tag')"));
var producer = await StartAndProducer("direct://bean-bindmessage");
var exchange = Msg("hello");
await producer.Process(exchange);
exchange.In.Body.Should().Be("hello+tag");
}
[Fact]
public async Task Binding_CancellationToken_IsInjectedWhereverItStands()
{
// The token is filled by the binding like the exchange, not only as a trailing parameter.
_context.AddRoutes(r => r.From("direct://bean-bindct-first")
.To($"bean:{Q(typeof(CalcBean))}?method=Stamp('id')"));
var producer = await StartAndProducer("direct://bean-bindct-first");
using var cts = new CancellationTokenSource();
var exchange = Msg("x");
await producer.Process(exchange, cts.Token);
exchange.In.Body.Should().Be("id:True");
}
[Fact]
public async Task Binding_WrongArgumentCount_ErrorSaysSo()
{
_context.AddRoutes(r => r.From("direct://bean-bindx")
.To($"bean:{Q(typeof(CalcBean))}?method=Upper(${{body}}, ${{header.a}})"));
var act = await FirstSend("direct://bean-bindx");
(await act.Should().ThrowAsync())
.WithMessage("*no public method 'Upper' taking 2 argument*");
}
[Fact]
public async Task Binding_NullIntoValueTypeParameter_FailsWithTheParameterName()
{
_context.AddRoutes(r => r.From("direct://bean-bindn")
.To($"bean:{Q(typeof(CalcBean))}?method=Add(${{header.missing}}, ${{header.b}})"));
var producer = await StartAndProducer("direct://bean-bindn");
var act = () => producer.Process(Msg("x", ("b", 2)));
(await act.Should().ThrowAsync())
.WithMessage("*parameter 'a'*value type*");
}
[Fact]
public async Task SensitiveProperty_JoinsTheUriRedactionSet()
{
_context.AddRoutes(r => r.From("direct://bean-secret")
.To($"bean:{Q(typeof(SecretBean))}?apiKey=super-secret-123"));
var producer = await StartAndProducer("direct://bean-secret");
var exchange = new Exchange(new Message("x"));
await producer.Process(exchange);
exchange.In.Headers["apiKeyLength"].Should().Be("super-secret-123".Length);
EndpointUri.IsSensitiveKey("ApiKey").Should().BeTrue("[Sensitive] on a bean property must redact the URI parameter");
}
}
Path: redb-route/tests/redb.Route.Tests/Components/BeanStepSugarTests.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/tests/redb.Route.Tests/Components/BeanStepSugarTests.cs
----
using AwesomeAssertions;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Definitions;
namespace redb.Route.Tests.Components;
///
/// .Bean(reference, method) , Camel's bean(ref, method) : sugar over the bean: URI. It adds the
/// same that To("bean:...") adds, so both meet at one endpoint; the older forms
/// (To("bean:") , .Bean<T>(lambda) ) are untouched.
///
public class BeanStepSugarTests : IAsyncLifetime
{
private readonly RouteContext _context = new();
public Task InitializeAsync() => Task.CompletedTask;
public async Task DisposeAsync()
{
await _context.DisposeAsync();
GC.SuppressFinalize(this);
}
private string[] ToUrisOf(Action routes)
{
_context.AddRoutes(routes);
var builder = _context.RouteBuilders.Last();
if (!builder.IsBuilt)
builder.InternalBuild(_context);
return builder.Definitions.Single().Outputs.OfType().Select(t => t.Uri).ToArray();
}
private async Task StartAndProducer(string fromUri)
{
await _context.Start();
var producer = _context.GetEndpoint(fromUri).CreateProducer();
await producer.Start();
return producer;
}
[Theory]
[InlineData("#greeter", "Greet", "bean:#greeter?method=Greet")]
[InlineData("#greeter", null, "bean:#greeter")]
[InlineData("Acme.Orders.Pricing, Acme.Orders", "Gross(${header.qty}, ${header.price})",
"bean:Acme.Orders.Pricing, Acme.Orders?method=Gross(${header.qty}, ${header.price})")]
public void Bean_AddsTheToDefinitionOfTheBeanUri(string reference, string? method, string expected)
{
ToUrisOf(r => r.From("direct://sugar").Bean(reference, method)).Should().Equal(expected);
}
[Fact]
public void Bean_AndTo_YieldTheSameUri()
{
var sugar = ToUrisOf(r => r.From("direct://sugar-a").Bean("#greeter", "Greet"));
var uri = ToUrisOf(r => r.From("direct://sugar-b").To("bean:#greeter?method=Greet"));
sugar.Should().Equal(uri);
}
[Fact]
public void Bean_EncodesOnlyTheCharactersTheUriParseWouldBreak()
{
ToUrisOf(r => r.From("direct://sugar-amp").Bean("#rules", "Check(${header.a} AND 5%)"))
.Should().Equal("bean:#rules?method=Check(${header.a} AND 5%25)");
ToUrisOf(r => r.From("direct://sugar-amp2").Bean("#rules", "Check('a&b')"))
.Should().Equal("bean:#rules?method=Check('a%26b')");
}
[Theory]
[InlineData("Gross(${header.a} AND ${header.b})", "bean:#rules?method=Gross(${header.a} AND ${header.b})")]
[InlineData("Check('a&b')", "bean:#rules?method=Check('a%26b')")]
[InlineData("Check('5%', ${body})", "bean:#rules?method=Check('5%25', ${body})")]
public void Bean_MethodArrivesAtTheEndpointAsWritten_AsTheHandWrittenUriDoes(string method, string handWritten)
{
// The engine reads method= from the parsed URI: the sugar and the hand-written form must parse alike,
// and the value the bean binding sees is the method exactly as the caller wrote it.
var sugar = EndpointUriParser.Parse(Route.Components.Bean.BeanComponent.UriFor("#rules", method));
var manual = EndpointUriParser.Parse(handWritten);
sugar.NormalizedKey.Should().Be(manual.NormalizedKey);
sugar.RawParameters["method"].Should().Be(method);
manual.RawParameters["method"].Should().Be(method);
}
[Fact]
public void Bean_ReferenceWithAQuery_IsRefused()
{
var act = () => ToUrisOf(r => r.From("direct://sugar-q").Bean("#greeter?method=Greet"));
act.Should().Throw().WithMessage("*contains '?'*second argument*");
}
[Fact]
public async Task Bean_CallsTheRegisteredObject_AndTheResultBecomesTheBody()
{
_context.AddToRegistry("greeter", new GreeterBean { Prefix = "sugar" });
_context.AddRoutes(r => r.From("direct://sugar-run").Bean("#greeter", "Greet"));
var producer = await StartAndProducer("direct://sugar-run");
var exchange = new Exchange(new Message("bob"));
await producer.Process(exchange);
exchange.In.Body.Should().Be("sugar:bob");
}
[Fact]
public async Task Bean_InsideAScope_KeepsTheScopeType()
{
// The step returns the scope, as To does: EndFilter() must still be reachable after it.
_context.AddToRegistry("greeter", new GreeterBean { Prefix = "scoped" });
_context.AddRoutes(r => r.From("direct://sugar-scope")
.Filter("header.go == 'yes'")
.Bean("#greeter", "Greet")
.EndFilter());
var producer = await StartAndProducer("direct://sugar-scope");
var pass = new Exchange(new Message("in"));
pass.In.Headers["go"] = "yes";
await producer.Process(pass);
var skip = new Exchange(new Message("out"));
skip.In.Headers["go"] = "no";
await producer.Process(skip);
pass.In.Body.Should().Be("scoped:in");
skip.In.Body.Should().Be("out");
}
}
Path: redb-route/tests/redb.Route.Tests/Components/BuiltInComponentRestartTests.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/tests/redb.Route.Tests/Components/BuiltInComponentRestartTests.cs
----
using AwesomeAssertions;
using Microsoft.Extensions.DependencyInjection;
using redb.Route.Abstractions;
using redb.Route.Components;
using redb.Route.Core;
namespace redb.Route.Tests.Components;
///
/// Every component built into redb.Route keeps working after Stop() and Start() of the same route context.
/// The context keeps its components and their cached endpoints across the restart, so state an endpoint holds (a queue,
/// a compiled schema or stylesheet, a timer, a reference to a route) must not be closed for good by the stop (redb-route
/// issue #12 was seda: ).
///
public sealed class BuiltInComponentRestartTests : IAsyncLifetime
{
private readonly RouteContext _context;
private readonly string _dir = Directory.CreateTempSubdirectory("redb-restart-").FullName;
public BuiltInComponentRestartTests()
{
var services = new ServiceCollection();
services.AddSingleton(new SharedVmRegistry());
_context = new RouteContext(services.BuildServiceProvider(), "restart");
}
public Task InitializeAsync() => Task.CompletedTask;
// IAsyncLifetime, not IAsyncDisposable: xUnit 2 never calls DisposeAsync of IAsyncDisposable on a test class, so the
// context (timers, Quartz, listeners) and the temporary directory outlived every test.
public async Task DisposeAsync()
{
await _context.DisposeAsync();
Directory.Delete(_dir, recursive: true);
}
private async Task SendAsync(string uri, object body)
{
var producer = _context.GetEndpoint(uri).CreateProducer();
await producer.Start();
var exchange = new Exchange(new Message { Body = body });
await producer.Process(exchange);
return exchange;
}
private static async Task WaitForAsync(Func condition, string because)
{
var deadline = DateTime.UtcNow.AddSeconds(10);
while (!condition() && DateTime.UtcNow < deadline)
await Task.Delay(20);
condition().Should().BeTrue(because);
}
/// Runs , restarts the context, and runs it again.
private async Task BeforeAndAfterRestartAsync(Func check)
{
await _context.Start();
await check(1);
await _context.Stop();
await _context.Start();
await check(2);
}
[Fact]
public async Task Direct()
{
var received = 0;
_context.AddRoutes(r => r.From("direct://in").Process(_ => Interlocked.Increment(ref received)));
await BeforeAndAfterRestartAsync(async round =>
{
await SendAsync("direct://in", "x");
Volatile.Read(ref received).Should().Be(round, "direct delivers after a restart");
});
}
[Fact]
public async Task Seda()
{
var received = 0;
_context.AddRoutes(r => r.From("seda://in").Process(_ => Interlocked.Increment(ref received)));
await BeforeAndAfterRestartAsync(async round =>
{
await SendAsync("seda://in", "x");
await WaitForAsync(() => Volatile.Read(ref received) == round, "seda delivers after a restart");
});
}
[Fact]
public async Task Vm()
{
var received = 0;
_context.AddRoutes(r => r.From("vm://in").Process(_ => Interlocked.Increment(ref received)));
await BeforeAndAfterRestartAsync(async round =>
{
await SendAsync("vm://in", "x");
await WaitForAsync(() => Volatile.Read(ref received) == round, "vm delivers after a restart");
});
}
[Fact]
public async Task DirectVm()
{
var received = 0;
_context.AddRoutes(r => r.From("direct-vm://in").Process(_ => Interlocked.Increment(ref received)));
await BeforeAndAfterRestartAsync(async round =>
{
await SendAsync("direct-vm://in", "x");
Volatile.Read(ref received).Should().Be(round, "direct-vm delivers after a restart");
});
}
[Fact]
public async Task Timer()
{
var fired = 0;
_context.AddRoutes(r => r.From("timer://tick?period=50").Process(_ => Interlocked.Increment(ref fired)));
await BeforeAndAfterRestartAsync(async _ =>
{
var before = Volatile.Read(ref fired);
await WaitForAsync(() => Volatile.Read(ref fired) > before, "timer fires after a restart");
});
}
[Fact]
public async Task Log()
{
var after = 0;
_context.AddRoutes(r => r.From("direct://log").To("log://restart?showBody=true")
.Process(_ => Interlocked.Increment(ref after)));
await BeforeAndAfterRestartAsync(async round =>
{
await SendAsync("direct://log", "x");
Volatile.Read(ref after).Should().Be(round, "log passes the exchange on after a restart");
});
}
[Fact]
public async Task Mock()
{
_context.AddRoutes(r => r.From("direct://mock").To("mock://result"));
await BeforeAndAfterRestartAsync(async round =>
{
await SendAsync("direct://mock", "x");
((MockEndpoint)_context.GetEndpoint("mock://result")).ReceivedCount.Should().Be(round,
"mock accepts after a restart");
});
}
public sealed class Greeter
{
public void Greet(IExchange exchange) => exchange.In.Body = "hi " + exchange.In.Body;
}
[Fact]
public async Task Bean()
{
_context.AddToRegistry("greeter", new Greeter());
_context.AddRoutes(r => r.From("direct://bean").To("bean:#greeter?method=Greet"));
await BeforeAndAfterRestartAsync(async _ =>
(await SendAsync("direct://bean", "bob")).In.Body.Should().Be("hi bob", "bean is called after a restart"));
}
[Fact]
public async Task ControlBus()
{
_context.AddRoutes(r =>
{
r.From("direct://worker").RouteId("worker").Process(_ => { });
r.From("direct://control").To("controlbus:route?routeId=worker&action=status");
});
await BeforeAndAfterRestartAsync(async _ =>
(await SendAsync("direct://control", "x")).In.Body.Should().Be("Started",
"controlbus sees the route of the new start after a restart"));
}
[Fact]
public async Task Validator()
{
var schema = Path.Combine(_dir, "person.json");
await File.WriteAllTextAsync(schema,
"""{ "type": "object", "required": ["name"], "properties": { "name": { "type": "string" } } }""");
_context.AddComponent(new redb.Route.Validation.ValidatorComponent());
_context.AddRoutes(r => r.From("direct://validate").To($"validator:{schema}"));
await BeforeAndAfterRestartAsync(async _ =>
{
(await SendAsync("direct://validate", """{ "name": "bob" }""")).Exception.Should().BeNull(
"validator passes a valid document after a restart");
var invalid = () => SendAsync("direct://validate", """{ "age": 3 }""");
await invalid.Should().ThrowAsync(
"validator rejects an invalid document after a restart");
});
}
[Fact]
public async Task Xslt()
{
var stylesheet = Path.Combine(_dir, "upper.xslt");
await File.WriteAllTextAsync(stylesheet, """
""");
_context.AddRoutes(r => r.From("direct://xslt").To($"xslt:{stylesheet}"));
await BeforeAndAfterRestartAsync(async _ =>
(await SendAsync("direct://xslt", "x ")).In.Body?.ToString().Should().Be("x ",
"xslt transforms after a restart"));
}
}
Path: redb-route/tests/redb.Route.Tests/Components/ComponentConstructionTests.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/tests/redb.Route.Tests/Components/ComponentConstructionTests.cs
----
using AwesomeAssertions;
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Components;
using redb.Route.Core;
using redb.Route.Extensions;
namespace redb.Route.Tests.Components;
///
/// The one rule by which a scanned component type is created, shared by the engine's AddComponents and the XML
/// catalog command: a constructor callable without arguments (none, or only optional ones), and a report naming every
/// component left out, so a scheme never drops out in silence.
///
public sealed class ComponentConstructionTests
{
/// A component whose only constructor needs an argument, as mcp's did.
public sealed class NeedsArgumentComponent(string required) : ComponentBase
{
public override string Scheme => "needs-" + required;
public override IEndpoint CreateEndpoint(EndpointUri uri) => throw new NotSupportedException();
}
/// A component whose constructor throws.
public sealed class ThrowingComponent : ComponentBase
{
public ThrowingComponent() => throw new InvalidOperationException("no config");
public override string Scheme => "throwing";
public override IEndpoint CreateEndpoint(EndpointUri uri) => throw new NotSupportedException();
}
/// A component whose constructor has only optional parameters, as HttpComponent(string scheme = "http") .
public sealed class OptionalArgumentComponent(string scheme = "optional-arg") : ComponentBase
{
public override string Scheme => scheme;
public override IEndpoint CreateEndpoint(EndpointUri uri) => throw new NotSupportedException();
}
[Fact]
public void A_component_without_an_argument_free_constructor_is_reported_with_its_reason()
{
var skipped = new List<(Type Type, string Reason)>();
var components = ComponentConstruction
.Create([typeof(NeedsArgumentComponent), typeof(TimerComponent), typeof(LogComponent)],
(type, reason) => skipped.Add((type, reason)))
.ToList();
components.Select(c => c.Scheme).Should().BeEquivalentTo(["timer", "log"], "log's constructor has only optional parameters");
skipped.Should().Equal((typeof(NeedsArgumentComponent), ComponentConstruction.NoArgumentFreeConstructor));
}
[Fact]
public void A_constructor_that_throws_is_reported_with_its_reason()
{
var skipped = new List<(Type Type, string Reason)>();
ComponentConstruction.Create([typeof(ThrowingComponent)], (type, reason) => skipped.Add((type, reason)))
.Should().BeEmpty();
skipped.Should().Equal((typeof(ThrowingComponent), "constructor failed (no config)"));
}
[Fact]
public void Abstract_types_and_non_components_are_not_reported()
{
var skipped = new List<(Type Type, string Reason)>();
ComponentConstruction.Create([typeof(ComponentBase), typeof(string)], (type, reason) => skipped.Add((type, reason)))
.Should().BeEmpty();
skipped.Should().BeEmpty();
}
[Fact]
public void AddComponents_registers_a_component_whose_constructor_has_only_optional_parameters()
{
var ctx = new RouteContext();
ctx.AddComponents(typeof(OptionalArgumentComponent).Assembly);
ctx.HasComponent("optional-arg").Should().BeTrue(
"the engine's scan follows the catalog's rule: http's constructor has only an optional scheme");
}
[Fact]
public void AddComponents_names_each_component_it_leaves_out_in_a_warning()
{
var provider = new RecordingLoggerProvider();
using var factory = LoggerFactory.Create(b => b.AddProvider(provider));
var ctx = new RouteContext(loggerFactory: factory);
ctx.AddComponents(typeof(ThrowingComponent).Assembly);
provider.Warnings.Should().Contain(w => w.Contains(typeof(ThrowingComponent).FullName!) && w.Contains("no config"));
provider.Warnings.Should().Contain(w =>
w.Contains(typeof(NeedsArgumentComponent).FullName!) && w.Contains(ComponentConstruction.NoArgumentFreeConstructor));
ctx.HasComponent("throwing").Should().BeFalse();
}
private sealed class RecordingLoggerProvider : ILoggerProvider
{
public readonly List Warnings = [];
public ILogger CreateLogger(string categoryName) => new Recorder(this);
public void Dispose() { }
private sealed class Recorder(RecordingLoggerProvider owner) : ILogger
{
public IDisposable? BeginScope(TState state) where TState : notnull => null;
public bool IsEnabled(LogLevel logLevel) => true;
public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception,
Func formatter)
{
if (logLevel == LogLevel.Warning)
lock (owner.Warnings)
owner.Warnings.Add(formatter(state, exception));
}
}
}
}
Path: redb-route/tests/redb.Route.Tests/Components/ContextRestartQueueTests.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/tests/redb.Route.Tests/Components/ContextRestartQueueTests.cs
----
using System.Threading.Channels;
using AwesomeAssertions;
using redb.Route.Abstractions;
using redb.Route.Core;
namespace redb.Route.Tests.Components;
///
/// In-memory queues of a route context across Stop() and Start() of the same instance (redb-route issue
/// #12): the context keeps its components and endpoints, so a queue that the stop closed for good left every hop
/// behind it dead while the routes reported Started.
///
public sealed class ContextRestartQueueTests : IAsyncLifetime
{
private readonly RouteContext _context = new();
public Task InitializeAsync() => Task.CompletedTask;
// IAsyncLifetime, not IAsyncDisposable: xUnit 2 never calls DisposeAsync of IAsyncDisposable on a test class.
public async Task DisposeAsync() => await _context.DisposeAsync();
private async Task SendAsync(string uri, object body)
{
var producer = _context.GetEndpoint(uri).CreateProducer();
await producer.Start();
await producer.Process(new Exchange(new Message { Body = body }));
}
private static async Task WaitForAsync(Func condition, string because)
{
var deadline = DateTime.UtcNow.AddSeconds(10);
while (!condition() && DateTime.UtcNow < deadline)
await Task.Delay(20);
condition().Should().BeTrue(because);
}
[Fact]
public async Task Seda_delivers_after_the_context_is_stopped_and_started_again()
{
var received = 0;
_context.AddRoutes(r => r.From("direct://input").To("seda://queue"));
_context.AddRoutes(r => r.From("seda://queue").Process(_ => Interlocked.Increment(ref received)));
await _context.Start();
await SendAsync("direct://input", "first");
await WaitForAsync(() => Volatile.Read(ref received) == 1, "seda delivers before the stop");
await _context.Stop();
await _context.Start();
await SendAsync("direct://input", "second");
await WaitForAsync(() => Volatile.Read(ref received) == 2,
"after Stop and Start of the same context the seda queue delivers again");
}
[Fact]
public async Task Seda_stop_finishes_the_queue_and_the_start_opens_a_new_one()
{
var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var processed = new List();
_context.AddRoutes(r => r.From("seda://waiting").Process(async (IExchange e, CancellationToken _) =>
{
await gate.Task;
lock (processed) processed.Add((string)e.In.Body!);
}));
await _context.Start();
// The first exchange is in the route when the context stops; the other two wait in the queue.
foreach (var body in new[] { "a", "b", "c" })
await SendAsync("seda://waiting", body);
var stopping = _context.Stop();
gate.SetResult();
await stopping;
lock (processed) processed.Should().Equal(["a", "b", "c"], "the stop finishes what is already in the queue");
var whileStopped = () => SendAsync("seda://waiting", "refused");
await whileStopped.Should().ThrowAsync("a stopped queue refuses visibly");
await _context.Start();
await SendAsync("seda://waiting", "d");
await WaitForAsync(() => { lock (processed) return processed.Count == 4; },
"after the start the queue is new and accepts");
lock (processed) processed.Should().Equal("a", "b", "c", "d");
}
[Fact]
public async Task Seda_refuses_a_send_once_the_context_is_disposed()
{
_context.AddRoutes(r => r.From("seda://closed").Process(_ => { }));
await _context.Start();
var producer = _context.GetEndpoint("seda://closed").CreateProducer();
await producer.Start();
await _context.DisposeAsync();
var send = () => producer.Process(new Exchange(new Message { Body = "late" }));
await send.Should().ThrowAsync("a send to the queue of a closed context is visible, it is not lost");
}
[Fact]
public async Task Threads_delivers_after_the_context_is_stopped_and_started_again()
{
var received = 0;
_context.AddRoutes(r => r.From("direct://pooled")
.Threads(2)
.Process(_ => Interlocked.Increment(ref received))
.End());
await _context.Start();
await SendAsync("direct://pooled", "first");
await WaitForAsync(() => Volatile.Read(ref received) == 1, "the Threads pool processes before the stop");
await _context.Stop();
await _context.Start();
await SendAsync("direct://pooled", "second");
await WaitForAsync(() => Volatile.Read(ref received) == 2,
"after Stop and Start of the same context the Threads pool processes again");
}
}
Path: redb-route/tests/redb.Route.Tests/Components/InterContextHeaderCharacterizationTests.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/tests/redb.Route.Tests/Components/InterContextHeaderCharacterizationTests.cs
----
using Microsoft.Extensions.DependencyInjection;
using redb.Route.Abstractions;
using redb.Route.Components;
using redb.Route.Core;
namespace redb.Route.Tests.Components;
///
/// What crosses between two contexts today: pinned before the header filter strategy reaches direct-vm: and
/// vm: . direct-vm: hands the called context the
/// caller's own exchange: every header goes, and every header the called route sets or removes is the caller's when
/// the call returns. vm: hands it a copy: every header goes, and nothing comes back.
///
public sealed class InterContextHeaderCharacterizationTests : IAsyncLifetime
{
private readonly ServiceProvider _sp;
public InterContextHeaderCharacterizationTests()
{
var services = new ServiceCollection();
services.AddSingleton(new SharedVmRegistry());
_sp = services.BuildServiceProvider();
}
public Task InitializeAsync() => Task.CompletedTask;
public async Task DisposeAsync()
{
await _sp.DisposeAsync();
GC.SuppressFinalize(this);
}
private static Exchange Sample()
{
var exchange = new Exchange(new Message("body"));
exchange.In.Headers["X-Corr"] = "c1";
exchange.In.Headers["Authorization"] = "Bearer secret";
exchange.In.Headers["redbHttp.Method"] = "DELETE";
return exchange;
}
[Fact]
public async Task DirectVm_TheCalledContextWorksOnTheCallersExchange()
{
IExchange? seen = null;
Dictionary? headersSeen = null;
await using var callee = new RouteContext(_sp, "callee");
await using var caller = new RouteContext(_sp, "caller");
callee.AddRoutes(r => r.From("direct-vm://hdr-char").Process(e =>
{
seen = e;
headersSeen = new Dictionary(e.In.Headers);
e.In.Headers.Remove("X-Corr");
e.In.Headers["X-From-Callee"] = "set";
}));
caller.AddRoutes(r => r.From("direct://hdr-char-trigger").To("direct-vm://hdr-char"));
await callee.Start();
await caller.Start();
var exchange = Sample();
var producer = caller.GetEndpoint("direct://hdr-char-trigger").CreateProducer();
await producer.Start();
await producer.Process(exchange);
await producer.Stop();
seen.Should().BeSameAs(exchange, "direct-vm is zero-copy: the called context gets the caller's exchange");
headersSeen!.Keys.Should().Contain(["X-Corr", "Authorization", "redbHttp.Method"], "every header goes");
exchange.In.Headers.Should().NotContainKey("X-Corr", "a header the called route removed is gone for the caller");
exchange.In.Headers["X-From-Callee"].Should().Be("set", "a header the called route set is the caller's");
}
[Fact]
public async Task Vm_TheCalledContextWorksOnACopy()
{
var received = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
await using var callee = new RouteContext(_sp, "callee");
await using var caller = new RouteContext(_sp, "caller");
callee.AddRoutes(r => r.From("vm://hdr-char").Process(e =>
{
e.In.Headers["X-From-Callee"] = "set";
received.TrySetResult(e);
}));
caller.AddRoutes(r => r.From("direct://hdr-char-trigger").To("vm://hdr-char"));
await callee.Start();
await caller.Start();
var exchange = Sample();
var producer = caller.GetEndpoint("direct://hdr-char-trigger").CreateProducer();
await producer.Start();
await producer.Process(exchange);
await producer.Stop();
var copy = await received.Task.WaitAsync(TimeSpan.FromSeconds(5));
copy.Should().NotBeSameAs(exchange, "vm hands over a copy");
copy.In.Headers.Keys.Should().Contain(["X-Corr", "Authorization", "redbHttp.Method"], "every header goes");
exchange.In.Headers.Should().NotContainKey("X-From-Callee", "nothing comes back from an asynchronous call");
}
}
Path: redb-route/tests/redb.Route.Tests/Components/InterContextHeaderFilterStrategyTests.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/tests/redb.Route.Tests/Components/InterContextHeaderFilterStrategyTests.cs
----
using Microsoft.Extensions.DependencyInjection;
using redb.Route.Abstractions;
using redb.Route.Components;
using redb.Route.Core;
using redb.Route.Processors;
namespace redb.Route.Tests.Components;
///
/// headerFilterStrategy=#name on the calling side of direct-vm: and vm:
/// direct-vm: then runs the called context on a copy:
/// the callee sees the headers the strategy lets out, and the caller keeps its own headers and takes the reply's body,
/// the reply headers the strategy lets in, the properties and the outcome. vm: filters the copy it hands over.
///
public sealed class InterContextHeaderFilterStrategyTests : IAsyncLifetime
{
private readonly ServiceProvider _sp;
public InterContextHeaderFilterStrategyTests()
{
var services = new ServiceCollection();
services.AddSingleton(new SharedVmRegistry());
_sp = services.BuildServiceProvider();
}
public Task InitializeAsync() => Task.CompletedTask;
public async Task DisposeAsync()
{
await _sp.DisposeAsync();
GC.SuppressFinalize(this);
}
private static DefaultHeaderFilterStrategy NoSecretsOutNoInternalsIn() => new()
{
OutFilter = ["Authorization"],
InFilter = ["X-Internal"],
};
private static Exchange Sample()
{
var exchange = new Exchange(new Message("request"));
exchange.In.Headers["X-Corr"] = "c1";
exchange.In.Headers["Authorization"] = "Bearer secret";
return exchange;
}
private async Task Call(RouteContext caller, Exchange exchange)
{
var producer = caller.GetEndpoint("direct://trigger").CreateProducer();
await producer.Start();
await producer.Process(exchange);
await producer.Stop();
return exchange;
}
[Fact]
public async Task DirectVm_TheCalleeSeesWhatTheStrategyLetsOut_AndTheCallerKeepsItsOwnHeaders()
{
IExchange? seen = null;
Dictionary? headersSeen = null;
await using var callee = new RouteContext(_sp, "callee");
await using var caller = new RouteContext(_sp, "caller");
caller.AddToRegistry("filter", NoSecretsOutNoInternalsIn());
callee.AddRoutes(r => r.From("direct-vm://hdr-strategy").Process(e =>
{
seen = e;
headersSeen = new Dictionary(e.In.Headers);
e.In.Headers.Remove("X-Corr");
e.In.Headers["X-From-Callee"] = "set";
e.In.Headers["X-Internal"] = "callee only";
e.Properties["callee.property"] = 42;
e.In.Body = "reply";
}));
caller.AddRoutes(r => r.From("direct://trigger").To("direct-vm://hdr-strategy?headerFilterStrategy=#filter"));
await callee.Start();
await caller.Start();
var exchange = await Call(caller, Sample());
seen.Should().NotBeSameAs(exchange, "under a strategy the called context works on a copy");
headersSeen!.Should().ContainKey("X-Corr");
headersSeen.Should().NotContainKey("Authorization", "the strategy keeps it from the callee");
exchange.In.Body.Should().Be("reply");
exchange.In.Headers["X-Corr"].Should().Be("c1", "the caller keeps its own headers, the callee removed only its copy");
exchange.In.Headers["Authorization"].Should().Be("Bearer secret", "the caller's own header never left it");
exchange.In.Headers["X-From-Callee"].Should().Be("set", "a reply header the strategy lets in comes back");
exchange.In.Headers.Should().NotContainKey("X-Internal", "the strategy keeps it from the caller");
exchange.Properties["callee.property"].Should().Be(42, "properties come back, as with the zero-copy call");
}
[Theory]
[InlineData("")]
[InlineData("?headerFilterStrategy=#filter")]
public async Task DirectVm_AFailingCallee_EndsTheCallTheSameWayWithOrWithoutAStrategy(string options)
{
await using var callee = new RouteContext(_sp, "callee");
await using var caller = new RouteContext(_sp, "caller");
caller.AddToRegistry("filter", NoSecretsOutNoInternalsIn());
callee.AddRoutes(r => r.From("direct-vm://hdr-strategy-fail")
.Process(_ => throw new InvalidOperationException("callee failed")));
caller.AddRoutes(r => r.From("direct://trigger").To("direct-vm://hdr-strategy-fail" + options));
await callee.Start();
await caller.Start();
var exchange = Sample();
var producer = caller.GetEndpoint("direct://trigger").CreateProducer();
await producer.Start();
Exception? thrown = null;
try { await producer.Process(exchange); }
catch (Exception ex) { thrown = ex; }
await producer.Stop();
var failure = thrown ?? exchange.Exception;
failure.Should().NotBeNull();
(failure as InvalidOperationException ?? failure!.InnerException).Should().BeOfType()
.Which.Message.Should().Be("callee failed");
}
[Fact]
public async Task DirectVm_AnUnknownParameterIsRefused()
{
await using var caller = new RouteContext(_sp, "caller");
var act = () => caller.GetEndpoint("direct-vm://hdr-strategy?headerFilterStategy=#filter");
act.Should().Throw().WithMessage("*headerFilterStategy*");
}
[Theory]
[InlineData("direct-vm")]
[InlineData("vm")]
public async Task OnAConsumer_TheOptionIsRefused(string scheme)
{
await using var callee = new RouteContext(_sp, "callee");
callee.AddToRegistry("filter", NoSecretsOutNoInternalsIn());
var act = () => callee.GetEndpoint($"{scheme}://hdr-strategy-consumer?headerFilterStrategy=#filter")
.CreateConsumer(new DelegateProcessor((IExchange _) => { }));
act.Should().Throw().WithMessage("*sets headerFilterStrategy, which applies to the * side*");
}
[Fact]
public async Task Vm_TheCopyCarriesWhatTheStrategyLetsOut()
{
var received = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
await using var callee = new RouteContext(_sp, "callee");
await using var caller = new RouteContext(_sp, "caller");
caller.AddToRegistry("filter", NoSecretsOutNoInternalsIn());
callee.AddRoutes(r => r.From("vm://hdr-strategy").Process(e => received.TrySetResult(e)));
caller.AddRoutes(r => r.From("direct://trigger").To("vm://hdr-strategy?headerFilterStrategy=#filter"));
await callee.Start();
await caller.Start();
var exchange = await Call(caller, Sample());
var copy = await received.Task.WaitAsync(TimeSpan.FromSeconds(5));
copy.In.Headers["X-Corr"].Should().Be("c1");
copy.In.Headers.Should().NotContainKey("Authorization", "the strategy keeps it from the other context");
exchange.In.Headers["Authorization"].Should().Be("Bearer secret", "the caller's own exchange is untouched");
}
}
Path: redb-route/tests/redb.Route.Tests/Components/LogComponentTests.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/tests/redb.Route.Tests/Components/LogComponentTests.cs
----
using AwesomeAssertions;
using Microsoft.Extensions.Logging;
using NSubstitute;
using redb.Route.Abstractions;
using redb.Route.Components;
using redb.Route.Core;
namespace redb.Route.Tests.Components;
///
/// Tests for the Log component.
///
public class LogComponentTests
{
[Fact]
public void Component_HasCorrectScheme()
{
var component = new LogComponent();
component.Scheme.Should().Be("log");
}
[Fact]
public void CreateEndpoint_ReturnsLogEndpoint()
{
var component = new LogComponent();
var uri = EndpointUriParser.Parse("log://MyCategory");
var endpoint = component.CreateEndpoint(uri);
endpoint.Should().BeOfType();
}
[Fact]
public void CreateEndpoint_SameUri_ReturnsSameInstance()
{
var component = new LogComponent();
var uri1 = EndpointUriParser.Parse("log://cat");
var uri2 = EndpointUriParser.Parse("log://cat");
component.CreateEndpoint(uri1).Should().BeSameAs(component.CreateEndpoint(uri2));
}
[Fact]
public void Options_DefaultValues()
{
var opts = new LogEndpointOptions();
opts.Level.Should().Be("Information");
opts.ShowHeaders.Should().BeTrue();
opts.ShowBody.Should().BeTrue();
}
[Fact]
public void Options_Level_DefaultIsInformation()
{
var opts = new LogEndpointOptions { Level = "Warning" };
opts.Level.Should().Be("Warning");
}
[Theory]
[InlineData("Trace", LogLevel.Trace)]
[InlineData("Debug", LogLevel.Debug)]
[InlineData("Information", LogLevel.Information)]
[InlineData("Warning", LogLevel.Warning)]
[InlineData("Error", LogLevel.Error)]
[InlineData("Critical", LogLevel.Critical)]
[InlineData("None", LogLevel.None)]
[InlineData("information", LogLevel.Information)]
[InlineData("TRACE", LogLevel.Trace)]
[InlineData("DEBUG", LogLevel.Debug)]
[InlineData("INFO", LogLevel.Information)]
[InlineData("WARN", LogLevel.Warning)]
[InlineData("ERROR", LogLevel.Error)]
[InlineData("OFF", LogLevel.None)]
[InlineData("warn", LogLevel.Warning)]
[InlineData("Off", LogLevel.None)]
public void Level_TakesTheDotNetAndTheCamelNames_InAnyCase(string name, LogLevel expected)
{
var endpoint = (LogEndpoint)new LogComponent().CreateEndpoint(EndpointUriParser.Parse($"log://lvl-{name}?level={name}"));
endpoint.LogOptions.ParsedLevel.Should().Be(expected);
}
[Theory]
[InlineData("Info2")]
[InlineData("Notice")]
[InlineData("2")]
[InlineData("Verbose")]
public void Level_RefusesAnyOtherName_WhenTheEndpointIsCreated(string name)
{
var act = () => new LogComponent().CreateEndpoint(EndpointUriParser.Parse($"log://bad-{name}?level={name}"));
act.Should().Throw()
.WithMessage($"*level '{name}' is not a log level*INFO, WARN, ERROR, OFF*");
}
[Fact]
public async Task ARouteWithAnUnknownLevel_DoesNotStart()
{
await using var context = new RouteContext();
context.AddRoutes(r => r.From("direct://bad-level").To("log://bad?level=Notice"));
var act = () => context.Start();
await act.Should().ThrowAsync();
}
[Fact]
public void LogEndpoint_CreateConsumer_ThrowsNotSupported()
{
var component = new LogComponent();
var ep = (LogEndpoint)component.CreateEndpoint(EndpointUriParser.Parse("log://test"));
var processor = Substitute.For();
var act = () => ep.CreateConsumer(processor);
act.Should().Throw();
}
[Fact]
public void LogEndpoint_CreateProducer_ReturnsLogProducer()
{
var component = new LogComponent();
var ep = (LogEndpoint)component.CreateEndpoint(EndpointUriParser.Parse("log://test"));
ep.CreateProducer().Should().BeOfType();
}
[Fact]
public async Task LogProducer_NoLoggerFactory_DoesNotThrow()
{
var component = new LogComponent(loggerFactory: null);
var ep = (LogEndpoint)component.CreateEndpoint(EndpointUriParser.Parse("log://nologger"));
var producer = ep.CreateProducer();
await producer.Start();
var exchange = new Exchange(new Message { Body = "test" });
var act = async () => await producer.Process(exchange);
await act.Should().NotThrowAsync();
}
[Fact]
public async Task LogProducer_WithLoggerFactory_LogsBody()
{
var logger = Substitute.For();
logger.IsEnabled(Arg.Any()).Returns(true);
var loggerFactory = Substitute.For();
loggerFactory.CreateLogger(Arg.Any()).Returns(logger);
var component = new LogComponent(loggerFactory);
var ep = (LogEndpoint)component.CreateEndpoint(EndpointUriParser.Parse("log://test"));
var producer = ep.CreateProducer();
await producer.Start();
var exchange = new Exchange(new Message { Body = "my-body-content" });
await producer.Process(exchange);
// Verify Log was called at least once
logger.ReceivedWithAnyArgs().Log(
default, default, default(object)!, default, default!);
}
[Fact]
public async Task LogProducer_WithHeaders_LogsHeaders()
{
var logger = Substitute.For();
logger.IsEnabled(Arg.Any()).Returns(true);
var loggerFactory = Substitute.For();
loggerFactory.CreateLogger(Arg.Any()).Returns(logger);
var component = new LogComponent(loggerFactory);
var ep = (LogEndpoint)component.CreateEndpoint(
EndpointUriParser.Parse("log://headertest?showBody=true&showHeaders=true"));
var producer = ep.CreateProducer();
await producer.Start();
var msg = new Message { Body = "body" };
msg.Headers["Key1"] = "Value1";
var exchange = new Exchange(msg);
await producer.Process(exchange);
logger.ReceivedWithAnyArgs().Log(
default, default, default(object)!, default, default!);
}
[Fact]
public async Task LogProducer_ShowBodyFalse_SkipsBody()
{
var logger = Substitute.For();
logger.IsEnabled(Arg.Any()).Returns(true);
var loggerFactory = Substitute.For();
loggerFactory.CreateLogger(Arg.Any()).Returns(logger);
var component = new LogComponent(loggerFactory);
var ep = (LogEndpoint)component.CreateEndpoint(
EndpointUriParser.Parse("log://nobody?showBody=false&showHeaders=false"));
var producer = ep.CreateProducer();
var exchange = new Exchange(new Message { Body = "secret" });
await producer.Process(exchange);
// Still logs, just "(empty exchange)" because both are disabled
logger.ReceivedWithAnyArgs().Log(
default, default, default(object)!, default, default!);
}
[Fact]
public async Task LogProducer_CustomLevel_UsesConfiguredLevel()
{
var logger = Substitute.For();
logger.IsEnabled(LogLevel.Warning).Returns(true);
var loggerFactory = Substitute.For();
loggerFactory.CreateLogger(Arg.Any()).Returns(logger);
var component = new LogComponent(loggerFactory);
var ep = (LogEndpoint)component.CreateEndpoint(
EndpointUriParser.Parse("log://warn?level=Warning"));
// The level option is configured via URI parameter;
// We verify behavior by checking that the logger gets called with the right level
// when we use the endpoint via a route. Unit level: just verify creation doesn't throw.
ep.Should().NotBeNull();
}
[Fact]
public void LogEndpoint_Category_CreatesLoggerWithCorrectName()
{
var loggerFactory = Substitute.For();
loggerFactory.CreateLogger(Arg.Any()).Returns(Substitute.For());
var component = new LogComponent(loggerFactory);
component.CreateEndpoint(EndpointUriParser.Parse("log://MyCategory"));
loggerFactory.Received().CreateLogger("redb.Route.Log.MyCategory");
}
[Fact]
public void LogEndpoint_EmptyCategory_UsesDefaultName()
{
var loggerFactory = Substitute.For();
loggerFactory.CreateLogger(Arg.Any()).Returns(Substitute.For());
var component = new LogComponent(loggerFactory);
// Just "log://" with no path
component.CreateEndpoint(EndpointUriParser.Parse("log://"));
loggerFactory.Received().CreateLogger("redb.Route.Log");
}
}
Path: redb-route/tests/redb.Route.Tests/Components/MockComponentTests.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/tests/redb.Route.Tests/Components/MockComponentTests.cs
----
using AwesomeAssertions;
using redb.Route.Abstractions;
using redb.Route.Components;
using redb.Route.Core;
namespace redb.Route.Tests.Components;
///
/// Tests for the Mock component.
///
public class MockComponentTests : IAsyncLifetime
{
private readonly RouteContext _context = new();
public Task InitializeAsync() => Task.CompletedTask;
public async Task DisposeAsync()
{
await _context.DisposeAsync();
GC.SuppressFinalize(this);
}
[Fact]
public void Component_HasCorrectScheme()
{
var component = new MockComponent();
component.Scheme.Should().Be("mock");
}
[Fact]
public void CreateEndpoint_ReturnsMockEndpoint()
{
var component = new MockComponent();
var uri = EndpointUriParser.Parse("mock://result");
var endpoint = component.CreateEndpoint(uri);
endpoint.Should().BeOfType();
}
[Fact]
public void CreateEndpoint_SameUri_ReturnsSameInstance()
{
var component = new MockComponent();
var uri1 = EndpointUriParser.Parse("mock://abc");
var uri2 = EndpointUriParser.Parse("mock://abc");
component.CreateEndpoint(uri1).Should().BeSameAs(component.CreateEndpoint(uri2));
}
[Fact]
public void GetEndpoint_ReturnsExistingEndpoint()
{
var component = new MockComponent();
var uri = EndpointUriParser.Parse("mock://result");
var created = component.CreateEndpoint(uri);
var found = component.GetEndpoint("result");
found.Should().BeSameAs(created);
}
[Fact]
public void GetEndpoint_ReturnsNull_WhenNotFound()
{
var component = new MockComponent();
component.GetEndpoint("missing").Should().BeNull();
}
[Fact]
public void MockEndpoint_InitialState_Empty()
{
var component = new MockComponent();
var ep = (MockEndpoint)component.CreateEndpoint(EndpointUriParser.Parse("mock://test"));
ep.ReceivedCount.Should().Be(0);
ep.ReceivedExchanges.Should().BeEmpty();
}
[Fact]
public void MockEndpoint_Options_DefaultExpectedCount()
{
var opts = new MockEndpointOptions();
opts.ExpectedMessageCount.Should().Be(0);
}
[Fact]
public async Task MockProducer_CapturesExchange()
{
var component = new MockComponent();
var ep = (MockEndpoint)component.CreateEndpoint(EndpointUriParser.Parse("mock://capture"));
var producer = ep.CreateProducer();
await producer.Start();
var exchange = new Exchange(new Message { Body = "hello" });
await producer.Process(exchange);
ep.ReceivedCount.Should().Be(1);
ep.ReceivedExchanges[0].In.Body.Should().Be("hello");
}
[Fact]
public async Task MockProducer_CapturesMultipleExchanges()
{
var component = new MockComponent();
var ep = (MockEndpoint)component.CreateEndpoint(EndpointUriParser.Parse("mock://multi"));
var producer = ep.CreateProducer();
await producer.Start();
for (int i = 0; i < 5; i++)
await producer.Process(new Exchange(new Message { Body = $"msg-{i}" }));
ep.ReceivedCount.Should().Be(5);
}
[Fact]
public async Task Mock_InRoute_CapturesDeliveredExchanges()
{
_context.AddRoutes(r =>
{
r.From("direct://source")
.SetHeader("X-Test", "value")
.To("mock://result");
});
await _context.Start();
var mockEndpoint = (MockEndpoint)_context.GetEndpoint("mock://result");
var producer = _context.GetEndpoint("direct://source").CreateProducer();
await producer.Start();
await producer.Process(new Exchange(new Message { Body = "test-body" }));
mockEndpoint.ReceivedCount.Should().Be(1);
mockEndpoint.ReceivedExchanges[0].In.Body.Should().Be("test-body");
mockEndpoint.ReceivedExchanges[0].In.Headers["X-Test"].Should().Be("value");
}
[Fact]
public async Task Mock_WaitForSatisfied_ReturnsTrue_WhenCountReached()
{
var component = new MockComponent();
var ep = (MockEndpoint)component.CreateEndpoint(
EndpointUriParser.Parse("mock://wait?expectedMessageCount=3"));
var producer = ep.CreateProducer();
await producer.Start();
ep.ExpectedMessageCount.Should().Be(3);
// Send 3 messages
for (int i = 0; i < 3; i++)
await producer.Process(new Exchange(new Message { Body = i }));
var satisfied = await ep.WaitForSatisfied(TimeSpan.FromSeconds(5));
satisfied.Should().BeTrue();
}
[Fact]
public async Task Mock_WaitForSatisfied_ReturnsFalse_OnTimeout()
{
var component = new MockComponent();
var ep = (MockEndpoint)component.CreateEndpoint(
EndpointUriParser.Parse("mock://timeout?expectedMessageCount=10"));
var producer = ep.CreateProducer();
await producer.Start();
// Only send 1 message (expected 10)
await producer.Process(new Exchange(new Message { Body = "one" }));
var satisfied = await ep.WaitForSatisfied(TimeSpan.FromMilliseconds(100));
satisfied.Should().BeFalse();
}
[Fact]
public async Task Mock_WaitForSatisfied_NoExpectation_ReturnsTrue()
{
var component = new MockComponent();
var ep = (MockEndpoint)component.CreateEndpoint(EndpointUriParser.Parse("mock://noexpect"));
var satisfied = await ep.WaitForSatisfied(TimeSpan.FromSeconds(1));
satisfied.Should().BeTrue();
}
[Fact]
public async Task Mock_Reset_ClearsReceivedExchanges()
{
var component = new MockComponent();
var ep = (MockEndpoint)component.CreateEndpoint(EndpointUriParser.Parse("mock://reset"));
var producer = ep.CreateProducer();
await producer.Start();
await producer.Process(new Exchange(new Message { Body = "a" }));
await producer.Process(new Exchange(new Message { Body = "b" }));
ep.ReceivedCount.Should().Be(2);
ep.Reset();
ep.ReceivedCount.Should().Be(0);
ep.ReceivedExchanges.Should().BeEmpty();
}
[Fact]
public async Task Mock_MultipleRoutes_CapturesSeparately()
{
_context.AddRoutes(r =>
{
r.From("direct://a")
.To("mock://result-a");
});
_context.AddRoutes(r =>
{
r.From("direct://b")
.To("mock://result-b");
});
await _context.Start();
var mockA = (MockEndpoint)_context.GetEndpoint("mock://result-a");
var mockB = (MockEndpoint)_context.GetEndpoint("mock://result-b");
var producerA = _context.GetEndpoint("direct://a").CreateProducer();
await producerA.Start();
var producerB = _context.GetEndpoint("direct://b").CreateProducer();
await producerB.Start();
await producerA.Process(new Exchange(new Message { Body = "from-a" }));
await producerB.Process(new Exchange(new Message { Body = "from-b-1" }));
await producerB.Process(new Exchange(new Message { Body = "from-b-2" }));
mockA.ReceivedCount.Should().Be(1);
mockB.ReceivedCount.Should().Be(2);
}
}
Path: redb-route/tests/redb.Route.Tests/Components/SedaComponentTests.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/tests/redb.Route.Tests/Components/SedaComponentTests.cs
----
using AwesomeAssertions;
using redb.Route.Abstractions;
using redb.Route.Components;
using redb.Route.Core;
namespace redb.Route.Tests.Components;
///
/// Tests for the SEDA (Staged Event-Driven Architecture) component.
///
public class SedaComponentTests : IAsyncLifetime
{
private readonly RouteContext _context = new();
public Task InitializeAsync() => Task.CompletedTask;
public async Task DisposeAsync()
{
await _context.DisposeAsync();
GC.SuppressFinalize(this);
}
[Fact]
public void Component_HasCorrectScheme()
{
var component = new SedaComponent();
component.Scheme.Should().Be("seda");
}
[Fact]
public void CreateEndpoint_ReturnsSedaEndpoint()
{
var component = new SedaComponent();
var uri = EndpointUriParser.Parse("seda://myqueue");
var endpoint = component.CreateEndpoint(uri);
endpoint.Should().BeOfType();
}
[Fact]
public void CreateEndpoint_SameUri_ReturnsSameInstance()
{
var component = new SedaComponent();
var uri1 = EndpointUriParser.Parse("seda://myqueue");
var uri2 = EndpointUriParser.Parse("seda://myqueue");
var ep1 = component.CreateEndpoint(uri1);
var ep2 = component.CreateEndpoint(uri2);
ep1.Should().BeSameAs(ep2);
}
[Fact]
public void Endpoint_Unbounded_ReturnsNegativeOneForQueueSize()
{
var component = new SedaComponent();
var uri = EndpointUriParser.Parse("seda://test?size=0");
var endpoint = (SedaEndpoint)component.CreateEndpoint(uri);
// Unbounded channels don't support Count, so CurrentQueueSize returns -1
endpoint.CurrentQueueSize.Should().Be(-1);
}
[Fact]
public void Options_DefaultValues()
{
var opts = new SedaEndpointOptions();
opts.ResolvedConcurrentConsumers.Should().Be(1, "the default stays 1, as in Camel/Spring/Azure");
opts.Size.Should().Be(1000, "bounded by default, as Camel's seda: an unbounded queue is an explicit size=0");
opts.Timeout.Should().Be(30000);
}
[Fact]
public void Endpoint_WithoutSize_IsBounded()
{
var component = new SedaComponent();
var endpoint = (SedaEndpoint)component.CreateEndpoint(EndpointUriParser.Parse("seda://default-bound"));
endpoint.CurrentQueueSize.Should().Be(0, "a bounded queue counts its items; an unbounded one reports -1");
}
[Fact]
public void Options_Validate_ThrowsOnInvalidConcurrentConsumers()
{
var opts = new SedaEndpointOptions { ConcurrentConsumers = "0" };
var act = () => opts.Validate();
act.Should().Throw().WithMessage("*concurrentConsumers*");
}
[Fact]
public void Options_Validate_ThrowsOnNegativeSize()
{
var opts = new SedaEndpointOptions { Size = -1 };
var act = () => opts.Validate();
act.Should().Throw();
}
[Fact]
public async Task Seda_AsyncDelivery_ProducerReturnsImmediately()
{
var received = new List();
_context.AddRoutes(r =>
{
r.From("direct://input")
.To("seda://queue1");
});
_context.AddRoutes(r =>
{
r.From("seda://queue1")
.Process(e => received.Add(e.In.Body));
});
await _context.Start();
var producer = _context.GetEndpoint("direct://input").CreateProducer();
await producer.Start();
await producer.Process(new Exchange(new Message { Body = "msg1" }));
await producer.Process(new Exchange(new Message { Body = "msg2" }));
// Give the async consumer a moment to process
await WaitForCondition(() => received.Count >= 2, TimeSpan.FromSeconds(5));
received.Should().HaveCount(2);
received.Should().Contain("msg1");
received.Should().Contain("msg2");
}
[Fact]
public async Task Seda_ConcurrentConsumers_ProcessInParallel()
{
var processed = new System.Collections.Concurrent.ConcurrentBag();
_context.AddRoutes(r =>
{
r.From("direct://parallel-input")
.To("seda://parallel-queue?concurrentConsumers=3");
});
_context.AddRoutes(r =>
{
r.From("seda://parallel-queue?concurrentConsumers=3")
.Process(async (e, ct) =>
{
await Task.Delay(50, ct);
processed.Add(e.In.Body!.ToString()!);
});
});
await _context.Start();
var producer = _context.GetEndpoint("direct://parallel-input").CreateProducer();
await producer.Start();
// Send 6 messages
for (int i = 0; i < 6; i++)
await producer.Process(new Exchange(new Message { Body = $"msg-{i}" }));
await WaitForCondition(() => processed.Count >= 6, TimeSpan.FromSeconds(5));
processed.Should().HaveCount(6);
}
[Fact]
public void Seda_BoundedQueue_CreatesBoundedEndpoint()
{
var component = new SedaComponent();
var uri = EndpointUriParser.Parse("seda://bounded?size=5");
var endpoint = (SedaEndpoint)component.CreateEndpoint(uri);
endpoint.CurrentQueueSize.Should().Be(0);
}
[Fact]
public async Task Seda_ProcessedCount_Increments()
{
var received = new List();
_context.AddRoutes(r =>
{
r.From("direct://count-input")
.To("seda://count-queue");
});
_context.AddRoutes(r =>
{
r.From("seda://count-queue")
.Process(e => received.Add(e.In.Body));
});
await _context.Start();
var producer = _context.GetEndpoint("direct://count-input").CreateProducer();
await producer.Start();
await producer.Process(new Exchange(new Message { Body = "a" }));
await producer.Process(new Exchange(new Message { Body = "b" }));
await producer.Process(new Exchange(new Message { Body = "c" }));
await WaitForCondition(() => received.Count >= 3, TimeSpan.FromSeconds(5));
received.Should().HaveCount(3);
}
[Fact]
public async Task Seda_StopConsumer_GracefulShutdown()
{
_context.AddRoutes(r =>
{
r.From("seda://graceful")
.Process(_ => { });
});
await _context.Start();
// Should stop without hanging
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
await _context.Stop(cts.Token);
}
[Fact]
public async Task Seda_OrderPreservation_SingleConsumer()
{
var received = new List();
_context.AddRoutes(r =>
{
r.From("direct://order-in")
.To("seda://order-queue");
});
_context.AddRoutes(r =>
{
r.From("seda://order-queue")
.Process(e => received.Add((int)e.In.Body!));
});
await _context.Start();
var producer = _context.GetEndpoint("direct://order-in").CreateProducer();
await producer.Start();
for (int i = 0; i < 10; i++)
await producer.Process(new Exchange(new Message { Body = i }));
await WaitForCondition(() => received.Count >= 10, TimeSpan.FromSeconds(5));
// With a single consumer, order should be preserved
received.Should().BeInAscendingOrder();
}
private static async Task WaitForCondition(Func condition, TimeSpan timeout)
{
using var cts = new CancellationTokenSource(timeout);
while (!condition())
{
cts.Token.ThrowIfCancellationRequested();
await Task.Delay(10, cts.Token);
}
}
}
Path: redb-route/tests/redb.Route.Tests/Components/TimerComponentTests.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/tests/redb.Route.Tests/Components/TimerComponentTests.cs
----
using redb.Route.Abstractions;
using redb.Route.Components;
using redb.Route.Core;
namespace redb.Route.Tests.Components;
///
/// Tests for , ,
/// , and .
///
public class TimerComponentTests
{
[Fact]
public void Scheme_IsTimer()
{
var component = new TimerComponent();
component.Scheme.Should().Be("timer");
}
[Fact]
public void CreateEndpoint_ReturnsTimerEndpoint()
{
var component = new TimerComponent();
var uri = EndpointUriParser.Parse("timer://heartbeat?period=500");
var endpoint = component.CreateEndpoint(uri);
endpoint.Should().BeOfType();
}
[Fact]
public void CreateEndpoint_NullUri_Throws()
{
var component = new TimerComponent();
var act = () => component.CreateEndpoint(null!);
act.Should().Throw();
}
// ── Options unit tests (direct construction) ──
[Fact]
public void Options_DefaultValues()
{
var opts = new TimerEndpointOptions();
opts.Period.Should().Be(1000);
opts.Delay.Should().Be(0);
opts.RepeatCount.Should().Be(-1);
}
[Fact]
public void Options_Validate_ThrowsOnZeroPeriod()
{
var opts = new TimerEndpointOptions { Period = 0 };
var act = () => opts.Validate();
act.Should().Throw();
}
[Fact]
public void Options_Validate_ThrowsOnNegativePeriod()
{
var opts = new TimerEndpointOptions { Period = -100 };
var act = () => opts.Validate();
act.Should().Throw();
}
[Fact]
public void Options_Validate_PassesForValidPeriod()
{
var opts = new TimerEndpointOptions { Period = 500 };
var act = () => opts.Validate();
act.Should().NotThrow();
}
[Fact]
public void CreateEndpoint_InvalidPeriod_Throws()
{
var component = new TimerComponent();
var uri = EndpointUriParser.Parse("timer://tick?period=0");
var act = () => component.CreateEndpoint(uri);
act.Should().Throw();
}
[Fact]
public void CreateEndpoint_NegativePeriod_Throws()
{
var component = new TimerComponent();
var uri = EndpointUriParser.Parse("timer://bad?period=-100");
var act = () => component.CreateEndpoint(uri);
act.Should().Throw();
}
[Fact]
public void CreateProducer_ThrowsNotSupported()
{
var component = new TimerComponent();
var uri = EndpointUriParser.Parse("timer://tick");
var endpoint = component.CreateEndpoint(uri);
var act = () => endpoint.CreateProducer();
act.Should().Throw();
}
[Fact]
public void CreateConsumer_ReturnsTimerConsumer()
{
var component = new TimerComponent();
var uri = EndpointUriParser.Parse("timer://tick?repeatCount=1");
var endpoint = component.CreateEndpoint(uri);
var processor = Substitute.For();
var consumer = endpoint.CreateConsumer(processor);
consumer.Should().BeOfType();
}
[Fact]
public void CreateConsumer_NullProcessor_Throws()
{
var component = new TimerComponent();
var uri = EndpointUriParser.Parse("timer://tick");
var endpoint = component.CreateEndpoint(uri);
var act = () => endpoint.CreateConsumer(null!);
act.Should().Throw();
}
[Fact]
public async Task Consumer_FiresProcessorRepeatCountTimes()
{
var component = new TimerComponent();
var uri = EndpointUriParser.Parse("timer://test?period=50&repeatCount=3");
var endpoint = component.CreateEndpoint(uri);
var exchanges = new List();
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(Task.CompletedTask)
.AndDoes(ci => exchanges.Add(ci.Arg()));
var consumer = endpoint.CreateConsumer(processor);
await consumer.Start();
// Wait for timer to complete (3 fires × 50ms + margin)
await Task.Delay(500);
await consumer.Stop();
exchanges.Should().HaveCount(3);
}
[Fact]
public async Task Consumer_SetsTimerHeaders()
{
var component = new TimerComponent();
var uri = EndpointUriParser.Parse("timer://myTimer?period=50&repeatCount=1");
var endpoint = component.CreateEndpoint(uri);
IExchange? captured = null;
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(Task.CompletedTask)
.AndDoes(ci => captured = ci.Arg());
var consumer = endpoint.CreateConsumer(processor);
await consumer.Start();
await Task.Delay(300);
await consumer.Stop();
captured.Should().NotBeNull();
captured!.In.Headers.Should().ContainKey("CamelTimerName");
captured.In.Headers["CamelTimerName"].Should().Be("myTimer");
captured.In.Headers.Should().ContainKey("CamelTimerFiredTime");
captured.In.Headers.Should().ContainKey("CamelTimerCounter");
captured.In.Headers["CamelTimerCounter"].Should().Be(0);
}
[Fact]
public async Task Consumer_RespectsInitialDelay()
{
var component = new TimerComponent();
// Use large delay (2s) so even under heavy CPU load the 200ms early-check has 10x margin
var uri = EndpointUriParser.Parse("timer://delayed?period=50&delay=2000&repeatCount=1");
var endpoint = component.CreateEndpoint(uri);
var firedTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(Task.CompletedTask)
.AndDoes(_ => firedTcs.TrySetResult());
var consumer = endpoint.CreateConsumer(processor);
await consumer.Start();
// At 200ms the 2000ms delay hasn't elapsed yet (10x margin)
var earlyResult = await Task.WhenAny(firedTcs.Task, Task.Delay(200));
earlyResult.Should().NotBe(firedTcs.Task, "initial delay of 2000ms has not elapsed");
// Wait for timer to fire (generous 5s timeout)
var lateResult = await Task.WhenAny(firedTcs.Task, Task.Delay(5000));
await consumer.Stop();
lateResult.Should().Be(firedTcs.Task, "timer should have fired after initial delay");
}
[Fact]
public async Task Consumer_StopCancelsLoop()
{
var component = new TimerComponent();
var uri = EndpointUriParser.Parse("timer://infinite?period=50");
var endpoint = component.CreateEndpoint(uri);
var count = 0;
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(Task.CompletedTask)
.AndDoes(_ => Interlocked.Increment(ref count));
var consumer = endpoint.CreateConsumer(processor);
await consumer.Start();
await Task.Delay(200);
await consumer.Stop();
var countAfterStop = count;
await Task.Delay(200);
// Should not have fired more after stop
count.Should().Be(countAfterStop);
countAfterStop.Should().BeGreaterThan(0);
}
[Fact]
public async Task Consumer_FireCount_TracksCompletedFires()
{
var component = new TimerComponent();
var uri = EndpointUriParser.Parse("timer://counter?period=50&repeatCount=3");
var endpoint = component.CreateEndpoint(uri);
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(Task.CompletedTask);
var consumer = (TimerConsumer)endpoint.CreateConsumer(processor);
await consumer.Start();
await Task.Delay(500);
await consumer.Stop();
consumer.FireCount.Should().Be(3);
}
[Fact]
public async Task Consumer_ExchangePattern_IsInOnly()
{
var component = new TimerComponent();
var uri = EndpointUriParser.Parse("timer://pattern?period=50&repeatCount=1");
var endpoint = component.CreateEndpoint(uri);
IExchange? captured = null;
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(Task.CompletedTask)
.AndDoes(ci => captured = ci.Arg());
var consumer = endpoint.CreateConsumer(processor);
await consumer.Start();
await Task.Delay(300);
await consumer.Stop();
captured.Should().NotBeNull();
captured!.Pattern.Should().Be(ExchangePattern.InOnly);
}
}
Path: redb-route/tests/redb.Route.Tests/Components/VmComponentTests.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/tests/redb.Route.Tests/Components/VmComponentTests.cs
----
using System.Collections.Concurrent;
using AwesomeAssertions;
using Microsoft.Extensions.DependencyInjection;
using redb.Route.Abstractions;
using redb.Route.Components;
using redb.Route.Core;
namespace redb.Route.Tests.Components;
///
/// Tests for DirectVm (cross-context synchronous) component.
///
public class DirectVmComponentTests : IAsyncLifetime
{
private readonly SharedVmRegistry _registry = new();
private readonly ServiceProvider _sp;
public DirectVmComponentTests()
{
var sc = new ServiceCollection();
sc.AddSingleton(_registry);
_sp = sc.BuildServiceProvider();
}
public Task InitializeAsync() => Task.CompletedTask;
public async Task DisposeAsync()
{
_sp.Dispose();
GC.SuppressFinalize(this);
}
private RouteContext CreateContext(string id) => new(_sp, id);
[Fact]
public void Component_HasCorrectScheme()
{
var component = new DirectVmComponent();
component.Scheme.Should().Be("direct-vm");
}
[Fact]
public void CreateEndpoint_ReturnsDirectVmEndpoint()
{
var component = new DirectVmComponent();
var uri = EndpointUriParser.Parse("direct-vm://myep");
var endpoint = component.CreateEndpoint(uri);
endpoint.Should().BeOfType();
}
[Fact]
public void CreateEndpoint_SameUri_ReturnsSameInstance()
{
var component = new DirectVmComponent();
var uri1 = EndpointUriParser.Parse("direct-vm://myep");
var uri2 = EndpointUriParser.Parse("direct-vm://myep");
var ep1 = component.CreateEndpoint(uri1);
var ep2 = component.CreateEndpoint(uri2);
ep1.Should().BeSameAs(ep2);
}
[Fact]
public async Task CrossContext_ProducerInvokesConsumer()
{
object? received = null;
await using var ctxA = CreateContext("ctx-a");
await using var ctxB = CreateContext("ctx-b");
// Context A: consumer on direct-vm://shared
ctxA.AddRoutes(r =>
{
r.From("direct-vm://shared")
.Process(e => received = e.In.Body);
});
// Context B: producer sends to direct-vm://shared
ctxB.AddRoutes(r =>
{
r.From("direct://trigger")
.To("direct-vm://shared");
});
await ctxA.Start();
await ctxB.Start();
var producer = ctxB.GetEndpoint("direct://trigger").CreateProducer();
await producer.Start();
await producer.Process(new Exchange(new Message { Body = "hello-vm" }));
received.Should().Be("hello-vm");
}
[Fact]
public async Task SameContext_ProducerInvokesConsumer()
{
object? received = null;
await using var ctx = CreateContext("ctx-single");
ctx.AddRoutes(r =>
{
r.From("direct-vm://local")
.Process(e => received = e.In.Body);
});
ctx.AddRoutes(r =>
{
r.From("direct://input")
.To("direct-vm://local");
});
await ctx.Start();
var producer = ctx.GetEndpoint("direct://input").CreateProducer();
await producer.Start();
await producer.Process(new Exchange(new Message { Body = "local-msg" }));
received.Should().Be("local-msg");
}
[Fact]
public async Task NoConsumer_ThrowsInvalidOperation()
{
await using var ctx = CreateContext("ctx-no-consumer");
ctx.AddRoutes(r =>
{
r.From("direct://input")
.To("direct-vm://orphan");
});
await ctx.Start();
var producer = ctx.GetEndpoint("direct://input").CreateProducer();
await producer.Start();
var act = () => producer.Process(new Exchange(new Message { Body = "x" }));
await act.Should().ThrowAsync()
.WithMessage("*No consumer registered*orphan*");
}
[Fact]
public async Task DuplicateConsumer_SecondRegistrationFails()
{
await using var ctxA = CreateContext("ctx-dup-a");
await using var ctxB = CreateContext("ctx-dup-b");
ctxA.AddRoutes(r =>
{
r.From("direct-vm://unique")
.Process(_ => { });
});
ctxB.AddRoutes(r =>
{
r.From("direct-vm://unique")
.Process(_ => { });
});
await ctxA.Start();
// ctxB.Start swallows the exception (RouteContext logs + continues)
await ctxB.Start();
// Only the first registration should be in the registry
_registry.GetProcessor("direct-vm://unique").Should().NotBeNull();
// Stop ctxA → unregisters, then ctxB can't have replaced it
await ctxA.Stop();
_registry.GetProcessor("direct-vm://unique").Should().BeNull();
}
[Fact]
public async Task Stop_UnregistersProcessor_NewConsumerCanRegister()
{
object? received = null;
await using var ctxA = CreateContext("ctx-reuse-a");
await using var ctxB = CreateContext("ctx-reuse-b");
ctxA.AddRoutes(r =>
{
r.From("direct-vm://reuse")
.Process(e => received = e.In.Body);
});
await ctxA.Start();
await ctxA.Stop();
// Now ctxB can take over the same name
ctxB.AddRoutes(r =>
{
r.From("direct-vm://reuse")
.Process(e => received = e.In.Body);
});
await ctxB.Start();
_registry.GetProcessor("direct-vm://reuse").Should().NotBeNull();
}
}
///
/// Tests for Vm (cross-context asynchronous) component.
///
public class VmComponentTests : IAsyncLifetime
{
private readonly SharedVmRegistry _registry = new();
private readonly ServiceProvider _sp;
public VmComponentTests()
{
var sc = new ServiceCollection();
sc.AddSingleton(_registry);
_sp = sc.BuildServiceProvider();
}
public Task InitializeAsync() => Task.CompletedTask;
public async Task DisposeAsync()
{
_sp.Dispose();
GC.SuppressFinalize(this);
}
private RouteContext CreateContext(string id) => new(_sp, id);
[Fact]
public void Component_HasCorrectScheme()
{
var component = new VmComponent();
component.Scheme.Should().Be("vm");
}
[Fact]
public void CreateEndpoint_ReturnsVmEndpoint()
{
var component = new VmComponent();
var uri = EndpointUriParser.Parse("vm://myqueue");
var endpoint = component.CreateEndpoint(uri);
endpoint.Should().BeOfType();
}
[Fact]
public void Options_DefaultValues()
{
var opts = new VmEndpointOptions();
opts.ResolvedConcurrentConsumers.Should().Be(1, "the default stays 1");
opts.Size.Should().Be(1000, "bounded by default, as Camel's vm: an unbounded queue is an explicit size=0");
}
[Fact]
public void Options_Validate_ThrowsOnInvalidConcurrentConsumers()
{
var opts = new VmEndpointOptions { ConcurrentConsumers = "0" };
var act = () => opts.Validate();
act.Should().Throw().WithMessage("*concurrentConsumers*");
}
[Fact]
public void Options_Validate_ThrowsOnNegativeSize()
{
var opts = new VmEndpointOptions { Size = -1 };
var act = () => opts.Validate();
act.Should().Throw();
}
[Fact]
public async Task CrossContext_AsyncDelivery()
{
var received = new ConcurrentBag();
await using var ctxA = CreateContext("vm-ctx-a");
await using var ctxB = CreateContext("vm-ctx-b");
// Context A: consumer on vm://shared-queue
ctxA.AddRoutes(r =>
{
r.From("vm://shared-queue")
.Process(e => received.Add(e.In.Body));
});
// Context B: producer sends to vm://shared-queue
ctxB.AddRoutes(r =>
{
r.From("direct://trigger")
.To("vm://shared-queue");
});
await ctxA.Start();
await ctxB.Start();
var producer = ctxB.GetEndpoint("direct://trigger").CreateProducer();
await producer.Start();
await producer.Process(new Exchange(new Message { Body = "msg1" }));
await producer.Process(new Exchange(new Message { Body = "msg2" }));
await WaitForCondition(() => received.Count >= 2, TimeSpan.FromSeconds(5));
received.Should().HaveCount(2);
received.Should().Contain("msg1");
received.Should().Contain("msg2");
}
[Fact]
public async Task SameContext_AsyncDelivery()
{
var received = new ConcurrentBag();
await using var ctx = CreateContext("vm-single");
ctx.AddRoutes(r =>
{
r.From("vm://local-queue")
.Process(e => received.Add(e.In.Body));
});
ctx.AddRoutes(r =>
{
r.From("direct://input")
.To("vm://local-queue");
});
await ctx.Start();
var producer = ctx.GetEndpoint("direct://input").CreateProducer();
await producer.Start();
await producer.Process(new Exchange(new Message { Body = "local1" }));
await producer.Process(new Exchange(new Message { Body = "local2" }));
await WaitForCondition(() => received.Count >= 2, TimeSpan.FromSeconds(5));
received.Should().HaveCount(2);
}
[Fact]
public async Task ConcurrentConsumers_ProcessInParallel()
{
var processed = new ConcurrentBag();
await using var ctxA = CreateContext("vm-parallel-a");
await using var ctxB = CreateContext("vm-parallel-b");
ctxA.AddRoutes(r =>
{
r.From("vm://parallel-queue?concurrentConsumers=3")
.Process(async (e, ct) =>
{
await Task.Delay(50, ct);
processed.Add(e.In.Body!.ToString()!);
});
});
ctxB.AddRoutes(r =>
{
r.From("direct://parallel-input")
.To("vm://parallel-queue");
});
await ctxA.Start();
await ctxB.Start();
var producer = ctxB.GetEndpoint("direct://parallel-input").CreateProducer();
await producer.Start();
for (int i = 0; i < 6; i++)
await producer.Process(new Exchange(new Message { Body = $"msg-{i}" }));
await WaitForCondition(() => processed.Count >= 6, TimeSpan.FromSeconds(5));
processed.Should().HaveCount(6);
}
[Fact]
public async Task Stop_GracefulShutdown()
{
await using var ctx = CreateContext("vm-graceful");
ctx.AddRoutes(r =>
{
r.From("vm://graceful")
.Process(_ => { });
});
await ctx.Start();
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
await ctx.Stop(cts.Token);
}
[Fact]
public async Task MultipleContextConsumers_ShareChannel()
{
// Both contexts consume from same vm channel — messages distributed between them
var receivedA = new ConcurrentBag();
var receivedB = new ConcurrentBag();
await using var ctxConsumerA = CreateContext("vm-multi-a");
await using var ctxConsumerB = CreateContext("vm-multi-b");
await using var ctxProducer = CreateContext("vm-multi-prod");
ctxConsumerA.AddRoutes(r =>
{
r.From("vm://multi-queue")
.Process(e => receivedA.Add(e.In.Body!.ToString()!));
});
ctxConsumerB.AddRoutes(r =>
{
r.From("vm://multi-queue")
.Process(e => receivedB.Add(e.In.Body!.ToString()!));
});
ctxProducer.AddRoutes(r =>
{
r.From("direct://multi-trigger")
.To("vm://multi-queue");
});
await ctxConsumerA.Start();
await ctxConsumerB.Start();
await ctxProducer.Start();
var producer = ctxProducer.GetEndpoint("direct://multi-trigger").CreateProducer();
await producer.Start();
for (int i = 0; i < 20; i++)
await producer.Process(new Exchange(new Message { Body = $"m-{i}" }));
await WaitForCondition(() => receivedA.Count + receivedB.Count >= 20, TimeSpan.FromSeconds(5));
// All messages should be processed (some by A, some by B)
(receivedA.Count + receivedB.Count).Should().Be(20);
}
private static async Task WaitForCondition(Func condition, TimeSpan timeout)
{
using var cts = new CancellationTokenSource(timeout);
while (!condition())
{
cts.Token.ThrowIfCancellationRequested();
await Task.Delay(10, cts.Token);
}
}
}
///
/// Tests for the SharedVmRegistry itself.
///
public class SharedVmRegistryTests
{
[Fact]
public void RegisterAndGetProcessor()
{
var registry = new SharedVmRegistry();
var processor = Substitute.For();
registry.TryRegisterProcessor("test", processor).Should().BeTrue();
registry.GetProcessor("test").Should().BeSameAs(processor);
}
[Fact]
public void DuplicateRegister_ReturnsFalse()
{
var registry = new SharedVmRegistry();
var p1 = Substitute.For();
var p2 = Substitute.For();
registry.TryRegisterProcessor("test", p1).Should().BeTrue();
registry.TryRegisterProcessor("test", p2).Should().BeFalse();
}
[Fact]
public void Unregister_RemovesProcessor()
{
var registry = new SharedVmRegistry();
var processor = Substitute.For();
registry.TryRegisterProcessor("test", processor);
registry.TryUnregisterProcessor("test", processor).Should().BeTrue();
registry.GetProcessor("test").Should().BeNull();
}
[Fact]
public void Unregister_WrongInstance_ReturnsFalse()
{
var registry = new SharedVmRegistry();
var p1 = Substitute.For();
var p2 = Substitute.For();
registry.TryRegisterProcessor("test", p1);
registry.TryUnregisterProcessor("test", p2).Should().BeFalse();
registry.GetProcessor("test").Should().BeSameAs(p1);
}
[Fact]
public void GetOrCreateChannel_ReturnsSameChannel()
{
var registry = new SharedVmRegistry();
var ch1 = registry.GetOrCreateChannel("q1");
var ch2 = registry.GetOrCreateChannel("q1");
ch1.Should().BeSameAs(ch2);
}
[Fact]
public void TryRemoveChannel_Removes()
{
var registry = new SharedVmRegistry();
registry.GetOrCreateChannel("q1");
registry.TryRemoveChannel("q1", out var ch).Should().BeTrue();
ch.Should().NotBeNull();
// After removal, a new call creates a new channel
var ch2 = registry.GetOrCreateChannel("q1");
ch2.Should().NotBeSameAs(ch);
}
}
Path: redb-route/tests/redb.Route.Tests/Conformance/BrokerFaultTests.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/tests/redb.Route.Tests/Conformance/BrokerFaultTests.cs
----
using System.Collections.Concurrent;
namespace redb.Route.Tests.Conformance;
///
/// without docker: the CLI calls it makes, the readiness wait by the broker's own health
/// command, and the failure texts that name the container and the command.
///
public sealed class BrokerFaultTests
{
[Fact]
public async Task A_restart_restarts_the_container_and_waits_for_the_health_command()
{
var docker = new FakeDocker { NotReadyTimes = 3 };
var fault = docker.Fault(TimeSpan.FromSeconds(10));
await fault.RestartAsync();
docker.Calls.Should().Equal(
"restart -t 10 qm", "exec qm chkmqhealthy", "exec qm chkmqhealthy", "exec qm chkmqhealthy",
"exec qm chkmqhealthy");
}
[Fact]
public async Task A_broker_that_does_not_come_back_fails_the_restart_with_the_health_output()
{
var docker = new FakeDocker { NotReadyTimes = int.MaxValue };
var fault = docker.Fault(TimeSpan.FromMilliseconds(200));
var act = () => fault.RestartAsync();
(await act.Should().ThrowAsync()).Which.Message.Should()
.Contain("qm").And.Contain("chkmqhealthy").And.Contain("not running");
}
[Fact]
public async Task A_failing_docker_command_fails_with_its_output()
{
var docker = new FakeDocker { Refuse = "pause qm" };
var fault = docker.Fault(TimeSpan.FromSeconds(1));
var act = () => fault.PauseAsync();
(await act.Should().ThrowAsync()).Which.Message.Should()
.Contain("docker pause qm").And.Contain("No such container");
}
[Fact]
public async Task Pause_and_unpause_freeze_and_release_the_container_without_a_readiness_wait()
{
var docker = new FakeDocker();
var fault = docker.Fault(TimeSpan.FromSeconds(1));
await fault.PauseAsync();
await fault.UnpauseAsync();
docker.Calls.Should().Equal("pause qm", "unpause qm");
}
[Fact]
public async Task Until_retries_an_attempt_until_it_succeeds()
{
var attempts = 0;
var done = await BrokerFault.UntilAsync(() => Task.FromResult(++attempts == 3),
TimeSpan.FromSeconds(5), TimeSpan.FromMilliseconds(10));
done.Should().BeTrue();
attempts.Should().Be(3);
}
[Fact]
public async Task A_health_command_argument_with_spaces_stays_one_argument()
{
var docker = new FakeDocker();
var fault = new BrokerFault("rmq", ["sh", "-c", "test -f cookie && check"], TimeSpan.FromSeconds(1), docker.Run,
TimeSpan.FromMilliseconds(5));
await fault.WaitReadyAsync();
docker.Arguments.Should().ContainSingle().Which.Should().Equal("exec", "rmq", "sh", "-c", "test -f cookie && check");
}
[Fact]
public void A_fault_needs_a_container_and_a_health_command()
{
FluentActions.Invoking(() => new BrokerFault("", "chkmqhealthy")).Should().Throw();
FluentActions.Invoking(() => new BrokerFault("qm")).Should().Throw();
}
private sealed class FakeDocker
{
public ConcurrentQueue CallQueue { get; } = new();
public ConcurrentQueue ArgumentQueue { get; } = new();
public string[] Calls => CallQueue.ToArray();
public string[][] Arguments => ArgumentQueue.ToArray();
public int NotReadyTimes { get; init; }
public string? Refuse { get; init; }
private int _checks;
public BrokerFault Fault(TimeSpan readyWithin)
=> new("qm", ["chkmqhealthy"], readyWithin, Run, TimeSpan.FromMilliseconds(5));
public Task Run(IReadOnlyList argumentList, CancellationToken ct)
{
ArgumentQueue.Enqueue(argumentList.ToArray());
var arguments = string.Join(' ', argumentList);
CallQueue.Enqueue(arguments);
if (arguments == Refuse)
return Task.FromResult(new DockerResult(1, "Error: No such container: qm"));
if (arguments.StartsWith("exec ", StringComparison.Ordinal) && _checks++ < NotReadyTimes)
return Task.FromResult(new DockerResult(1, "queue manager not running"));
return Task.FromResult(new DockerResult(0, ""));
}
}
}
Path: redb-route/tests/redb.Route.Tests/ControlBus/ControlBusNotifyTests.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/tests/redb.Route.Tests/ControlBus/ControlBusNotifyTests.cs
----
using System.Collections.Concurrent;
using AwesomeAssertions;
using redb.Route.Abstractions;
using redb.Route.ControlBus;
using redb.Route.Core;
namespace redb.Route.Tests.ControlBus;
///
/// Tests for the controlbus:notify event consumer (redb extension beyond Camel): route/context
/// lifecycle events surfaced as exchanges into a route, with optional event/route filters.
///
public class ControlBusNotifyTests
{
private static async Task Eventually(Func condition, int seconds = 5)
{
var deadline = DateTime.UtcNow.AddSeconds(seconds);
while (DateTime.UtcNow < deadline)
{
if (condition()) return true;
await Task.Delay(25);
}
return condition();
}
[Fact]
public async Task Notify_EmitsRouteStoppedEvent()
{
var events = new ConcurrentBag<(string ev, string? routeId)>();
await using var ctx = new RouteContext();
ctx.AddRoutes(r =>
{
r.From("direct://worker").RouteId("worker").Process(_ => { });
r.From("controlbus:notify").RouteId("notify")
.Process(e => events.Add((
e.In.GetHeader(ControlBusHeaders.Event)!,
e.In.GetHeader(ControlBusHeaders.RouteId))));
});
await ctx.Start();
await ctx.StopRoute("worker");
(await Eventually(() => events.Any(x => x.ev == "RouteStopped" && x.routeId == "worker")))
.Should().BeTrue("stopping 'worker' should surface a RouteStopped event on controlbus:notify");
}
[Fact]
public async Task Notify_EventsFilter_OnlyMatchingEvents()
{
var events = new ConcurrentBag();
await using var ctx = new RouteContext();
ctx.AddRoutes(r =>
{
r.From("direct://w").RouteId("w").Process(_ => { });
r.From("controlbus:notify?events=RouteStarted").RouteId("n")
.Process(e => events.Add(e.In.GetHeader(ControlBusHeaders.Event)!));
});
await ctx.Start();
await ctx.StopRoute("w"); // RouteStopped — must be filtered out
await ctx.StartRoute("w"); // RouteStarted — must be captured
(await Eventually(() => events.Contains("RouteStarted"))).Should().BeTrue();
events.Should().NotContain("RouteStopped");
}
[Fact]
public async Task Notify_RouteFilter_OnlyThatRoute()
{
var routeIds = new ConcurrentBag();
await using var ctx = new RouteContext();
ctx.AddRoutes(r =>
{
r.From("direct://a").RouteId("a").Process(_ => { });
r.From("direct://b").RouteId("b").Process(_ => { });
r.From("controlbus:notify?routeId=a").RouteId("n2")
.Process(e => routeIds.Add(e.In.GetHeader(ControlBusHeaders.RouteId)));
});
await ctx.Start();
await ctx.StopRoute("a");
await ctx.StopRoute("b");
(await Eventually(() => routeIds.Any(x => x == "a"))).Should().BeTrue();
routeIds.Should().NotContain("b");
}
[Fact]
public async Task Notify_IsConsumerOnly_ProducerThrows()
{
await using var ctx = new RouteContext();
var endpoint = ctx.GetEndpoint("controlbus:notify");
var act = () => endpoint.CreateProducer();
act.Should().Throw();
await Task.CompletedTask;
}
}
Path: redb-route/tests/redb.Route.Tests/ControlBus/ControlBusTests.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/tests/redb.Route.Tests/ControlBus/ControlBusTests.cs
----
using AwesomeAssertions;
using redb.Route.Abstractions;
using redb.Route.ControlBus;
using redb.Route.Core;
namespace redb.Route.Tests.ControlBus;
///
/// Tests for the Control Bus EIP (Apache Camel controlbus: parity): route actions
/// (start/stop/suspend/resume/restart/status/stats/fail), the .ControlBus(...) DSL,
/// current targeting, options validation, and producer-only enforcement.
///
public class ControlBusTests
{
private static async Task StartAndProducer(RouteContext ctx, string fromUri)
{
await ctx.Start();
var producer = ctx.GetEndpoint(fromUri).CreateProducer();
await producer.Start();
return producer;
}
[Fact]
public async Task ControlBus_OneRoute_StopsAnother()
{
await using var ctx = new RouteContext();
ctx.AddRoutes(r =>
{
r.From("direct://worker").RouteId("worker").Process(_ => { });
r.From("direct://control").RouteId("controller")
.ControlBus(ControlBusAction.Stop, "worker");
});
var control = await StartAndProducer(ctx, "direct://control");
ctx.GetRoute("worker")!.Status.Should().Be(RouteStatus.Started);
await control.Process(new Exchange(new Message("go")));
ctx.GetRoute("worker")!.Status.Should().Be(RouteStatus.Stopped);
}
[Fact]
public async Task ControlBus_Start_RevivesStoppedRoute()
{
await using var ctx = new RouteContext();
ctx.AddRoutes(r =>
{
r.From("direct://w2").RouteId("w2").Process(_ => { });
r.From("direct://ctl-start").RouteId("c2")
.ControlBus(ControlBusAction.Start, "w2");
});
await ctx.Start();
await ctx.StopRoute("w2");
ctx.GetRoute("w2")!.Status.Should().Be(RouteStatus.Stopped);
var control = ctx.GetEndpoint("direct://ctl-start").CreateProducer();
await control.Start();
await control.Process(new Exchange(new Message("go")));
ctx.GetRoute("w2")!.Status.Should().Be(RouteStatus.Started);
}
[Fact]
public async Task ControlBus_Status_ReturnsStatusOnBody()
{
await using var ctx = new RouteContext();
ctx.AddRoutes(r =>
{
r.From("direct://w3").RouteId("w3").Process(_ => { });
r.From("direct://ctl-status").RouteId("c3")
.To("controlbus:route?routeId=w3&action=status");
});
var control = await StartAndProducer(ctx, "direct://ctl-status");
var ex = new Exchange(new Message("x"));
await control.Process(ex);
ex.In.Body.Should().Be("Started");
}
[Fact]
public async Task ControlBus_Stats_ReturnsXml()
{
await using var ctx = new RouteContext();
ctx.AddRoutes(r =>
{
r.From("direct://w4").RouteId("w4").Process(_ => { });
r.From("direct://ctl-stats").RouteId("c4")
.To("controlbus:route?routeId=w4&action=stats");
});
var control = await StartAndProducer(ctx, "direct://ctl-stats");
var ex = new Exchange(new Message("x"));
await control.Process(ex);
var body = ex.In.Body!.ToString()!;
body.Should().Contain("").And.Contain("id=\"w4\"").And.Contain("status=\"Started\"");
}
[Fact]
public async Task ControlBus_Stats_CarriesTheWholeCounterSurface()
{
// The stats XML trailed IEndpointStatistics: Warnings, Rejected, Cancelled, bytes and
// LastError were readable through a captured context but invisible through the one DSL
// path a route has — exactly the columns the recent accounting work made honest.
await using var ctx = new RouteContext();
ctx.AddRoutes(r =>
{
r.From("direct://w5").RouteId("w5").Process(_ => throw new InvalidOperationException("boom & "));
r.From("direct://ctl-stats-full").RouteId("c5")
.To("controlbus:route?routeId=w5&action=stats");
});
var worker = await StartAndProducer(ctx, "direct://w5");
var act = () => worker.Process(new Exchange(new Message("x")));
await act.Should().ThrowAsync();
var control = ctx.GetEndpoint("direct://ctl-stats-full").CreateProducer();
await control.Start();
var ex = new Exchange(new Message("x"));
await control.Process(ex);
var body = ex.In.Body!.ToString()!;
body.Should().Contain("errors=\"1\"")
.And.Contain("warnings=\"0\"")
.And.Contain("rejected=\"0\"")
.And.Contain("cancelled=\"0\"")
.And.Contain("bytesIn=\"")
.And.Contain("lastError=\"boom & <bang>\"",
"the message must be XML-escaped, or a quote in an exception text corrupts the document");
}
[Fact]
public async Task ControlBus_Dsl_Current_StopsSelf_Async_NoDeadlock()
{
await using var ctx = new RouteContext();
ctx.AddRoutes(r =>
r.From("direct://selfstop").RouteId("selfstop")
.ControlBus(ControlBusAction.Suspend, "current", async: true));
var producer = await StartAndProducer(ctx, "direct://selfstop");
// Must return promptly (async dispatch), not deadlock stopping the current route.
await producer.Process(new Exchange(new Message("x"))).WaitAsync(TimeSpan.FromSeconds(5));
// Eventually the self-stop lands.
var deadline = DateTime.UtcNow.AddSeconds(5);
while (ctx.GetRoute("selfstop")!.Status != RouteStatus.Stopped && DateTime.UtcNow < deadline)
await Task.Delay(50);
ctx.GetRoute("selfstop")!.Status.Should().Be(RouteStatus.Stopped);
}
[Fact]
public async Task ControlBus_MissingAction_FailsAtEndpointCreation()
{
await using var ctx = new RouteContext();
var act = () => ctx.GetEndpoint("controlbus:route?routeId=x");
act.Should().Throw().WithMessage("*action*");
await Task.CompletedTask;
}
[Fact]
public async Task ControlBus_MissingRouteId_FailsForMutatingAction()
{
await using var ctx = new RouteContext();
var act = () => ctx.GetEndpoint("controlbus:route?action=stop");
act.Should().Throw().WithMessage("*routeId*");
await Task.CompletedTask;
}
[Fact]
public async Task ControlBus_IsProducerOnly()
{
await using var ctx = new RouteContext();
var endpoint = ctx.GetEndpoint("controlbus:route?routeId=x&action=stop");
var act = () => endpoint.CreateConsumer(new NoopProcessor());
act.Should().Throw();
await Task.CompletedTask;
}
private sealed class NoopProcessor : IProcessor
{
public Task Process(IExchange exchange, CancellationToken ct = default) => Task.CompletedTask;
}
}
Path: redb-route/tests/redb.Route.Tests/Core/BodySizeEstimateTests.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/tests/redb.Route.Tests/Core/BodySizeEstimateTests.cs
----
using AwesomeAssertions;
using redb.Route.Core;
namespace redb.Route.Tests.Core;
///
/// The byte count the endpoint statistics keep is measured, not produced: text, bytes and a seekable stream have a
/// size; any other object counts as 0, as Camel does not count bytes at all. It used to be serialized to JSON on every
/// incoming exchange, only to count the bytes of the result.
///
public class BodySizeEstimateTests
{
private sealed class Order
{
public int Reads;
public string Customer
{
get
{
Interlocked.Increment(ref Reads);
return "acme";
}
}
}
[Fact]
public void An_object_body_is_not_serialized_to_be_counted()
{
var order = new Order();
var size = EndpointBase.EstimateBodySize(order);
order.Reads.Should().Be(0, "counting bytes must not serialize the body");
size.Should().Be(0);
}
[Fact]
public void Text_bytes_and_a_seekable_stream_are_measured()
{
EndpointBase.EstimateBodySize("héllo").Should().Be(6);
EndpointBase.EstimateBodySize(new byte[7]).Should().Be(7);
EndpointBase.EstimateBodySize(new MemoryStream(new byte[9])).Should().Be(9);
}
}
Path: redb-route/tests/redb.Route.Tests/Core/BodyTextTests.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/tests/redb.Route.Tests/Core/BodyTextTests.cs
----
using System.Text.Json.Nodes;
using AwesomeAssertions;
using redb.Route.Core;
namespace redb.Route.Tests.Core;
/// The text a producer sends for a body it has no wire form for: the body's own text, never its type name.
public class BodyTextTests
{
private sealed class NoText { }
private sealed record WithText(int Id);
[Theory]
[MemberData(nameof(Texted))]
public void A_body_with_a_text_form_of_its_own_is_its_text(object body, string text)
=> BodyText.Of(body).Should().Be(text);
public static TheoryData Texted => new()
{
{ 42, "42" },
{ new JsonArray(1, 2), "[\n 1,\n 2\n]".Replace("\n", Environment.NewLine) },
{ new WithText(7), "WithText { Id = 7 }" },
{ new System.Text.StringBuilder("sb"), "sb" },
};
[Fact]
public void Bytes_and_a_stream_are_their_UTF8_text()
{
BodyText.Of(System.Text.Encoding.UTF8.GetBytes("héllo")).Should().Be("héllo");
using var stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes("from a stream"));
stream.Position = 5;
BodyText.Of(stream).Should().Be("from a stream", "a seekable stream is read from its start");
}
[Fact]
public void A_list_is_refused_naming_the_endpoint_and_the_way_out()
{
var act = () => BodyText.Of(new List { 1 }, "mqtt://t");
act.Should().Throw().WithMessage("*mqtt://t*List*Serialize the list*");
}
[Fact]
public void An_object_without_a_text_form_is_refused()
{
var act = () => BodyText.Of(new NoText());
act.Should().Throw().WithMessage("*NoText*type name*Convert it*");
}
}
Path: redb-route/tests/redb.Route.Tests/Core/BuilderOnExceptionTests.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/tests/redb.Route.Tests/Core/BuilderOnExceptionTests.cs
----
using AwesomeAssertions;
using redb.Route.Abstractions;
using redb.Route.Core;
namespace redb.Route.Tests.Core;
///
/// Tests for builder-level OnException<T>() — global exception handlers
/// defined at the RouteBuilder level and compiled into the RouteContext.
///
public class BuilderOnExceptionTests : IAsyncLifetime
{
private readonly RouteContext _context = new();
public Task InitializeAsync() => Task.CompletedTask;
public async Task DisposeAsync()
{
await _context.DisposeAsync();
GC.SuppressFinalize(this);
}
// ── Builder DSL ──
[Fact]
public void OnException_RegistersExceptionDefinition()
{
var builder = new TestBuilder(configure: b =>
{
b.OnException()
.MaximumRedeliveries(3);
});
((IRouteBuilder)builder).Configure(null!);
builder.ExceptionDefCount.Should().Be(1);
}
[Fact]
public void OnException_MultipleTypes_RegistersSeparateDefinitions()
{
var builder = new TestBuilder(configure: b =>
{
b.OnException()
.Handled();
b.OnException()
.MaximumRedeliveries(5);
});
((IRouteBuilder)builder).Configure(null!);
builder.ExceptionDefCount.Should().Be(2);
}
[Fact]
public void OnException_SupportsDslChaining()
{
// Verify all DSL methods can be chained on builder-level OnException
var builder = new TestBuilder(configure: b =>
{
b.OnException()
.MaximumRedeliveries(3)
.RedeliveryDelay(TimeSpan.FromSeconds(1))
.BackOffMultiplier(2.0)
.UseExponentialBackOff()
.Handled()
.OnWhen(e => e.In.Body is string)
.RetryAttemptedLogLevel(Microsoft.Extensions.Logging.LogLevel.Debug)
.RetriesExhaustedLogLevel(Microsoft.Extensions.Logging.LogLevel.Critical)
.OnExceptionOccurred(_ => { })
.Log("Error occurred")
.To("direct://dead-letter");
});
((IRouteBuilder)builder).Configure(null!);
builder.ExceptionDefCount.Should().Be(1);
}
// ── Engine Integration ──
[Fact]
public async Task OnException_CompilesIntoGlobalHandler()
{
Exception? capturedException = null;
_context.AddRoutes(r =>
{
r.OnException()
.Handled()
.Process(e => capturedException = e.Exception);
r.From("direct://input")
.Process(_ => throw new InvalidOperationException("boom"));
});
await _context.Start();
// Send message — exception should be caught by global handler
var endpoint = _context.GetEndpoint("direct://input");
var producer = endpoint.CreateProducer();
await producer.Start();
var exchange = new Exchange(new Message("test"));
await producer.Process(exchange);
capturedException.Should().NotBeNull();
capturedException.Should().BeOfType();
capturedException!.Message.Should().Be("boom");
}
[Fact]
public async Task OnException_WithRetry_RetriesBeforeHandling()
{
var callCount = 0;
_context.AddRoutes(r =>
{
r.OnException()
.MaximumRedeliveries(2)
.RedeliveryDelay(TimeSpan.FromMilliseconds(10))
.Handled();
r.From("direct://input")
.Process(_ =>
{
callCount++;
throw new InvalidOperationException("retry me");
});
});
await _context.Start();
var endpoint = _context.GetEndpoint("direct://input");
var producer = endpoint.CreateProducer();
await producer.Start();
var exchange = new Exchange(new Message("go"));
await producer.Process(exchange);
// Original call + 2 retries = 3 total
callCount.Should().Be(3);
}
[Fact]
public async Task OnException_DerivedType_CaughtByBaseHandler()
{
var handled = false;
_context.AddRoutes(r =>
{
// Register handler for base Exception type
r.OnException()
.Handled()
.Process(_ => handled = true);
r.From("direct://input")
.Process(_ => throw new ArgumentException("derived"));
});
await _context.Start();
var endpoint = _context.GetEndpoint("direct://input");
var producer = endpoint.CreateProducer();
await producer.Start();
await producer.Process(new Exchange(new Message("test")));
handled.Should().BeTrue();
}
[Fact]
public async Task OnException_HandledClears_ExceptionOnExchange()
{
_context.AddRoutes(r =>
{
r.OnException()
.Handled()
.Process(_ => { });
r.From("direct://input")
.Process(_ => throw new InvalidOperationException("cleared"));
});
await _context.Start();
var endpoint = _context.GetEndpoint("direct://input");
var producer = endpoint.CreateProducer();
await producer.Start();
var exchange = new Exchange(new Message("test"));
await producer.Process(exchange);
// With Handled, exception should be cleared on the exchange
exchange.Exception.Should().BeNull();
}
[Fact]
public void HasExceptionRoute_ReturnsTrue_AfterBuilderOnException()
{
_context.AddRoutes(r =>
{
r.OnException()
.Handled();
r.From("direct://input")
.To("direct://output");
});
// Start configures and compiles
_context.Start().GetAwaiter().GetResult();
_context.HasExceptionRoute().Should().BeTrue();
_context.HasExceptionRoute().Should().BeFalse();
}
[Fact]
public async Task OnException_ForwardsFullHandlerConfig_OnExceptionOccurredFires()
{
// Builder-level OnException is compiled by RouteContext into the per-route handler wrapper.
// That path used to forward only redeliveries + handled/continued, silently dropping OnWhen,
// RetryWhile, OnRedelivery, OnPrepareFailure, the log levels, LogExhausted and OnExceptionOccurred.
// This asserts one of the dropped callbacks now reaches the compiled handler.
var occurred = 0;
_context.AddRoutes(r =>
{
r.OnException()
.OnExceptionOccurred(_ => occurred++)
.Handled();
r.From("direct://input")
.Process(_ => throw new InvalidOperationException("boom"));
});
await _context.Start();
var producer = _context.GetEndpoint("direct://input").CreateProducer();
await producer.Start();
await producer.Process(new Exchange(new Message("test")));
occurred.Should().Be(1, "OnExceptionOccurred must be forwarded to the compiled builder-level handler");
}
// ── Test Helpers ──
/// Builder that exposes OnException for testing.
private sealed class TestBuilder : RouteBuilder
{
private readonly Action? _configure;
private int _exceptionDefCount;
internal TestBuilder(Action? configure = null) => _configure = configure;
protected override void Configure() => _configure?.Invoke(this);
public new IRouteDefinition OnException() where T : Exception
{
_exceptionDefCount++;
return base.OnException();
}
public IRouteDefinition CallFrom(string uri) => From(uri);
public int ExceptionDefCount => _exceptionDefCount;
}
}
Path: redb-route/tests/redb.Route.Tests/Core/BuilderScopeTests.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/tests/redb.Route.Tests/Core/BuilderScopeTests.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Processors;
using redb.Route.TestKit;
namespace redb.Route.Tests.Core;
///
/// The scope of what a declares for its routes — Intercept* , OnCompletion ,
/// OnException : the routes of that builder, never the routes of another builder of the same context
/// (Apache Camel's RouteBuilder scope). Also the detached path (.Threads() ), which reaches the handlers through
/// rather than through the route's wrapper, and the user's own
/// registrations, which a restart must not lose.
///
public class BuilderScopeTests
{
private static readonly TimeSpan Wait = TimeSpan.FromSeconds(5);
[Fact]
public async Task Intercept_OfOneBuilder_DoesNotReachTheRoutesOfAnother()
{
await using var ctx = new RouteContext();
ctx.AddRoutes(a =>
{
a.Intercept().SetHeader("seenByA", true);
a.From("direct://scope-a").To("mock://scope-a");
});
ctx.AddRoutes(b => b.From("direct://scope-b").To("mock://scope-b"));
await ctx.Start();
await ctx.SendBody("direct://scope-a", "a");
await ctx.SendBody("direct://scope-b", "b");
await ctx.Mock("mock://scope-a").ExpectHeader("seenByA", true).AssertIsSatisfiedAsync(Wait);
ctx.Mock("mock://scope-b").ReceivedExchanges.Should().ContainSingle()
.Which.In.Headers.Should().NotContainKey("seenByA", "an intercept is scoped to the builder that declares it");
}
[Fact]
public async Task OnCompletion_OfOneBuilder_DoesNotRunForTheRoutesOfAnother()
{
var completions = 0;
await using var ctx = new RouteContext();
ctx.AddRoutes(a =>
{
a.OnCompletion().ModeBeforeConsumer().Process(_ => Interlocked.Increment(ref completions));
a.From("direct://completion-a").To("mock://completion-a");
});
ctx.AddRoutes(b => b.From("direct://completion-b").To("mock://completion-b"));
await ctx.Start();
await ctx.SendBody("direct://completion-b", "b");
await ctx.SendBody("direct://completion-a", "a");
Volatile.Read(ref completions).Should().Be(1, "only the route of the declaring builder completes into it");
}
[Fact]
public async Task OnException_OfOneBuilder_DoesNotHandleTheFailuresOfAnother()
{
var hitsA = 0;
await using var ctx = new RouteContext();
ctx.AddRoutes(a =>
{
a.OnException().Handled().Process(_ => Interlocked.Increment(ref hitsA));
a.From("direct://failure-a").To("mock://failure-a");
});
ctx.AddRoutes(b => b.From("direct://failure-b").Process(_ => throw new InvalidOperationException("boom")));
await ctx.Start();
var exchange = await Send(ctx, "direct://failure-b");
Volatile.Read(ref hitsA).Should().Be(0, "an OnException is scoped to the builder that declares it");
exchange.Exception.Should().BeOfType("nothing in the failing route's scope handled it");
}
[Fact]
public async Task TwoBuilders_WithTheSameOnExceptionType_Start()
{
await using var ctx = new RouteContext();
ctx.AddRoutes(a =>
{
a.OnException().Handled();
a.From("direct://same-type-a").To("mock://same-type-a");
});
ctx.AddRoutes(b =>
{
b.OnException().Handled();
b.From("direct://same-type-b").To("mock://same-type-b");
});
var start = async () => await ctx.Start();
await start.Should().NotThrowAsync("each builder's handler belongs to its own routes, they do not collide");
}
[Fact]
public async Task Threads_RouteOnException_ReceivesTheDetachedFailure()
{
var hits = 0;
await using var ctx = new RouteContext();
ctx.AddRoutes(r => r
.From("direct://threads-route-handler")
.OnException()
.Handled()
.Process(_ => Interlocked.Increment(ref hits))
.End()
.Threads(2)
.Process((IExchange _, CancellationToken _) => throw new InvalidOperationException("boom"))
.End());
await ctx.Start();
await Send(ctx, "direct://threads-route-handler");
await WaitFor(() => Volatile.Read(ref hits) == 1);
}
[Fact]
public async Task Threads_DetachedFailure_ReachesOnlyTheHandlersOfItsOwnBuilder()
{
var hitsA = 0;
var hitsB = 0;
await using var ctx = new RouteContext();
ctx.AddRoutes(a =>
{
a.OnException().Handled().Process(_ => Interlocked.Increment(ref hitsA));
a.From("direct://threads-scope-a").To("mock://threads-scope-a");
});
ctx.AddRoutes(b =>
{
b.OnException().Handled().Process(_ => Interlocked.Increment(ref hitsB));
b.From("direct://threads-scope-b")
.Threads(2)
.Process((IExchange _, CancellationToken _) => throw new InvalidOperationException("boom"))
.End();
});
await ctx.Start();
await Send(ctx, "direct://threads-scope-b");
await WaitFor(() => Volatile.Read(ref hitsA) + Volatile.Read(ref hitsB) >= 1);
Volatile.Read(ref hitsB).Should().Be(1);
Volatile.Read(ref hitsA).Should().Be(0, "a more specific handler of another builder is out of scope");
}
[Fact]
public async Task Threads_RouteOnException_TakesPrecedenceOverTheBuilders()
{
var routeHits = 0;
var builderHits = 0;
await using var ctx = new RouteContext();
ctx.AddRoutes(r =>
{
r.OnException().Handled().Process(_ => Interlocked.Increment(ref builderHits));
r.From("direct://threads-precedence")
.OnException()
.Handled()
.Process(_ => Interlocked.Increment(ref routeHits))
.End()
.Threads(2)
.Process((IExchange _, CancellationToken _) => throw new InvalidOperationException("boom"))
.End();
});
await ctx.Start();
await Send(ctx, "direct://threads-precedence");
await WaitFor(() => Volatile.Read(ref routeHits) + Volatile.Read(ref builderHits) >= 1);
Volatile.Read(ref routeHits).Should().Be(1);
Volatile.Read(ref builderHits).Should().Be(0, "the route's own OnException wins, as it does on the inline path");
}
[Fact]
public async Task Restart_KeepsTheGlobalHandlerTheUserRegistered()
{
var hits = 0;
await using var ctx = new RouteContext();
ctx.AddGlobalExceptionHandler(
new DelegateProcessor(_ => Interlocked.Increment(ref hits)));
ctx.AddRoutes(r => r
.From("direct://restart-global")
.Threads(2)
.Process((IExchange _, CancellationToken _) => throw new InvalidOperationException("boom"))
.End());
await ctx.Start();
await Send(ctx, "direct://restart-global");
await WaitFor(() => Volatile.Read(ref hits) == 1);
await ctx.Stop();
await ctx.Start();
await Send(ctx, "direct://restart-global");
await WaitFor(() => Volatile.Read(ref hits) == 2);
}
[Fact]
public async Task Restart_KeepsTheLocalHandlerTheUserRegistered()
{
var hits = 0;
await using var ctx = new RouteContext();
ctx.AddLocalExceptionHandler("restart-local", typeof(InvalidOperationException),
new DelegateProcessor(_ => Interlocked.Increment(ref hits)));
ctx.AddRoutes(r => r
.From("direct://restart-local")
.RouteId("restart-local")
.Threads(2)
.Process((IExchange _, CancellationToken _) => throw new InvalidOperationException("boom"))
.End());
await ctx.Start();
await Send(ctx, "direct://restart-local");
await WaitFor(() => Volatile.Read(ref hits) == 1);
await ctx.Stop();
await ctx.Start();
await Send(ctx, "direct://restart-local");
await WaitFor(() => Volatile.Read(ref hits) == 2);
}
private static async Task Send(IRouteContext ctx, string uri)
{
var producer = ctx.GetEndpoint(uri).CreateProducer();
await producer.Start();
var exchange = new Exchange(new Message { Body = "x" });
try { await producer.Process(exchange); }
catch (Exception ex) { exchange.Exception ??= ex; }
return exchange;
}
private static async Task WaitFor(Func condition)
{
using var cts = new CancellationTokenSource(Wait);
while (!condition())
{
cts.Token.ThrowIfCancellationRequested();
await Task.Delay(10, cts.Token);
}
}
}
Path: redb-route/tests/redb.Route.Tests/Core/CancellationHandlerValidationTests.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/tests/redb.Route.Tests/Core/CancellationHandlerValidationTests.cs
----
using AwesomeAssertions;
using Microsoft.Extensions.Logging;
using redb.Route.Core;
namespace redb.Route.Tests.Core;
///
/// A Catch<T> / OnException<T> on a type that is an
/// can never fire — a genuine cancellation is never handled and a
/// timeout arrives as — so the route load warns about it instead of leaving
/// the dead branch to be discovered by a red test.
///
public class CancellationHandlerValidationTests
{
private static (RouteContext Context, List Warnings) New()
{
var warnings = new List();
var loggerFactory = LoggerFactory.Create(b => b.AddProvider(new CapturingLoggerProvider(warnings)));
return (new RouteContext("cancellation-handler", loggerFactory), warnings);
}
[Fact]
public async Task TryCatch_Catch_OperationCanceled_Warns()
{
var (ctx, warnings) = New();
ctx.AddRoutes(r => r
.From("direct:c").RouteId("c")
.TryCatch()
.Process(_ => { })
.Catch()
.Process(_ => { })
.EndTryCatch()
.To("direct:sink"));
await ctx.Start(); // the route still builds — the branch is dead, not illegal
warnings.Should().Contain(w => w.Contains("TaskCanceledException") && w.Contains("can never fire"));
await ctx.DisposeAsync();
}
[Fact]
public async Task TryCatch_Catch_TimeoutException_DoesNotWarn()
{
var (ctx, warnings) = New();
ctx.AddRoutes(r => r
.From("direct:t").RouteId("t")
.TryCatch()
.Process(_ => { })
.Catch()
.Process(_ => { })
.EndTryCatch()
.To("direct:sink"));
await ctx.Start();
warnings.Should().NotContain(w => w.Contains("can never fire"));
await ctx.DisposeAsync();
}
[Fact]
public async Task OnException_OperationCanceled_Warns()
{
var (ctx, warnings) = New();
ctx.AddRoutes(r =>
{
r.OnException().Handled();
r.From("direct:o").RouteId("o").Process(_ => { }).To("direct:sink");
});
await ctx.Start();
warnings.Should().Contain(w => w.Contains("OperationCanceledException") && w.Contains("can never fire"));
await ctx.DisposeAsync();
}
private sealed class CapturingLoggerProvider(List sink) : ILoggerProvider
{
public ILogger CreateLogger(string categoryName) => new CapturingLogger(sink);
public void Dispose() { }
private sealed class CapturingLogger(List sink) : ILogger
{
public IDisposable? BeginScope(TState state) where TState : notnull => null;
public bool IsEnabled(LogLevel logLevel) => true;
public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception,
Func formatter)
{
if (logLevel == LogLevel.Warning) sink.Add(formatter(state, exception));
}
}
}
}
Path: redb-route/tests/redb.Route.Tests/Core/CollectibleContextCleanupTests.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/tests/redb.Route.Tests/Core/CollectibleContextCleanupTests.cs
----
// The test emits its module with PersistedAssemblyBuilder, which .NET 9 introduced.
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Loader;
using redb.Route.Core;
using redb.Route.Serialization;
namespace redb.Route.Tests.Core;
///
/// A type of a collectible load context that went through the JSON serializer of redb.Route no longer keeps the
/// context alive: on unload the hot reload caches of the .NET libraries (System.Text.Json's above all) are emptied.
/// Without that, System.Text.Json roots the type for good (https://github.com/dotnet/runtime/issues/65323).
///
[Collection(CollectibleContextCollection.Name)]
public sealed class CollectibleContextCleanupTests
{
// A context with no assembly: clearing "for" it leaves out no library.
private static readonly AssemblyLoadContext NoAssemblies = new("no-assemblies", isCollectible: true);
[Fact]
public async Task A_module_type_serialized_as_json_lets_its_context_unload()
{
var module = SerializeFromCollectibleModule(keepCleanup: true);
await Collect(module);
module.IsAlive.Should().BeFalse("the System.Text.Json caches are emptied when the context unloads");
}
[Fact]
public async Task Without_the_cleanup_the_json_caches_keep_the_context_alive()
{
var module = SerializeFromCollectibleModule(keepCleanup: false);
await Collect(module);
module.IsAlive.Should().BeTrue("the control: System.Text.Json roots a type it serialized");
// Let the context go for the tests that follow.
CollectibleContextCleanup.ClearMetadataUpdateCaches(NoAssemblies);
}
[Fact]
public void The_handlers_of_the_loaded_libraries_are_found()
{
CollectibleContextCleanup.ClearMetadataUpdateCaches(NoAssemblies)
.Should().BeGreaterThan(0, "System.Text.Json declares a hot reload handler");
}
///
/// Loads an emitted module with one POCO into a collectible context, serializes and deserializes an instance
/// through and unloads the context. Out of line so nothing of the caller roots it.
///
[MethodImpl(MethodImplOptions.NoInlining)]
private static WeakReference SerializeFromCollectibleModule(bool keepCleanup)
{
new RouteContext().Dispose(); // the cleanup starts with the first route context
var context = new AssemblyLoadContext($"module-{Guid.NewGuid():N}", isCollectible: true);
var type = context.LoadFromStream(new MemoryStream(EmitModuleWithPoco())).GetType("Module.Order")!;
CollectibleContextCleanup.IsWatched(context).Should().BeTrue("a collectible context is watched once its assembly loads");
var order = Activator.CreateInstance(type)!;
type.GetProperty("Name")!.SetValue(order, "first");
var serializer = new JsonMessageSerializer();
var json = serializer.Serialize(order);
serializer.Deserialize(json, type).Should().NotBeNull();
if (!keepCleanup)
{
var onUnloading = typeof(CollectibleContextCleanup).GetMethod("OnUnloading", BindingFlags.NonPublic | BindingFlags.Static)!;
context.Unloading -= (Action)Delegate.CreateDelegate(typeof(Action), onUnloading);
}
context.Unload();
return new WeakReference(context);
}
/// An assembly with one public class,