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, Module.Order, with a string property Name. private static byte[] EmitModuleWithPoco() { var builder = new PersistedAssemblyBuilder(new AssemblyName("Module"), typeof(object).Assembly); var type = builder.DefineDynamicModule("Module").DefineType("Module.Order", TypeAttributes.Public | TypeAttributes.Class); var field = type.DefineField("_name", typeof(string), FieldAttributes.Private); var property = type.DefineProperty("Name", PropertyAttributes.None, typeof(string), null); const MethodAttributes accessor = MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig; var get = type.DefineMethod("get_Name", accessor, typeof(string), Type.EmptyTypes); var il = get.GetILGenerator(); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldfld, field); il.Emit(OpCodes.Ret); property.SetGetMethod(get); var set = type.DefineMethod("set_Name", accessor, null, [typeof(string)]); il = set.GetILGenerator(); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldarg_1); il.Emit(OpCodes.Stfld, field); il.Emit(OpCodes.Ret); property.SetSetMethod(set); type.DefineDefaultConstructor(MethodAttributes.Public); type.CreateType(); using var stream = new MemoryStream(); builder.Save(stream); return stream.ToArray(); } private static async Task Collect(WeakReference reference) { for (var i = 0; i < 100 && reference.IsAlive; i++) { GC.Collect(); GC.WaitForPendingFinalizers(); if (reference.IsAlive) await Task.Delay(10); } } } /// Unload tests share the process-wide caches they empty: they run one after the other. [CollectionDefinition(Name, DisableParallelization = true)] public sealed class CollectibleContextCollection { public const string Name = "CollectibleContext"; } Path: redb-route/tests/redb.Route.Tests/Core/CollectibleTypeServiceProviderTests.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/CollectibleTypeServiceProviderTests.cs ---- using System.Reflection; using System.Reflection.Emit; using AwesomeAssertions; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using redb.Route.Core; using Xunit; namespace redb.Route.Tests.Core; /// /// The provider beans and components are built with: a service type over a type of a collectible load context never /// reaches the host's container, which keeps every type it was asked for and would keep the module with it. /// public sealed class CollectibleTypeServiceProviderTests { private static readonly ModuleBuilder Module = AssemblyBuilder .DefineDynamicAssembly(new AssemblyName("Collectible" + Guid.NewGuid().ToString("N")), AssemblyBuilderAccess.RunAndCollect) .DefineDynamicModule("main"); private static readonly Type ModuleType = EmitBean("Module.Bean", type => typeof(ILogger<>).MakeGenericType(type), "Logger"); /// A settings class of the module: public, with a parameterless constructor, nothing configures it. private static readonly Type SettingsType = EmitSettings(); private static readonly Type OptionsBeanType = EmitBean("Module.OptionsBean", _ => typeof(IOptions<>).MakeGenericType(SettingsType), "Options"); private readonly ServiceProvider _host = new ServiceCollection().AddLogging().AddOptions() .AddSingleton(new Uri("http://host")).BuildServiceProvider(); [Fact] public void A_type_of_the_host_goes_to_the_host() { var services = CollectibleTypeServiceProvider.For(_host); services.GetService(typeof(Uri)).Should().BeSameAs(_host.GetService(typeof(Uri))); services.GetService(typeof(ILogger)).Should().BeSameAs( _host.GetService(typeof(ILogger))); ((IServiceProviderIsService)services).IsService(typeof(Uri)).Should().BeTrue(); } [Fact] public void A_logger_of_a_module_type_is_made_from_the_host_logger_factory() { var loggerType = typeof(ILogger<>).MakeGenericType(ModuleType); var services = CollectibleTypeServiceProvider.For(_host); services.GetService(loggerType).Should().BeAssignableTo(loggerType); ((IServiceProviderIsService)services).IsService(loggerType).Should().BeTrue(); } [Fact] public void A_list_of_a_module_type_is_empty_and_any_other_service_over_it_is_absent() { var services = CollectibleTypeServiceProvider.For(_host); ((Array)services.GetService(typeof(IEnumerable<>).MakeGenericType(ModuleType))!).Length.Should().Be(0); services.GetService(ModuleType).Should().BeNull(); services.GetService(typeof(Lazy<>).MakeGenericType(ModuleType)).Should().BeNull(); ((IServiceProviderIsService)services).IsService(ModuleType).Should().BeFalse(); ((IKeyedServiceProvider)services).GetKeyedService(ModuleType, "k").Should().BeNull(); } [Fact] public void ActivatorUtilities_builds_a_module_bean_with_its_own_logger() { var bean = ActivatorUtilities.CreateInstance(CollectibleTypeServiceProvider.For(_host), ModuleType); bean.GetType().GetField("Logger")!.GetValue(bean).Should().NotBeNull(); } [Fact] public void The_options_services_of_a_module_type_hold_its_default_instance_as_the_host_would_build_them() { var services = CollectibleTypeServiceProvider.For(_host); var isService = (IServiceProviderIsService)services; foreach (var open in new[] { typeof(IOptions<>), typeof(IOptionsSnapshot<>) }) { var options = services.GetService(open.MakeGenericType(SettingsType)); options.Should().NotBeNull(open.Name); isService.IsService(open.MakeGenericType(SettingsType)).Should().BeTrue(open.Name); // IOptionsSnapshot takes Value from IOptions typeof(IOptions<>).MakeGenericType(SettingsType).GetProperty("Value")!.GetValue(options).Should().BeOfType(SettingsType); } var monitor = services.GetService(typeof(IOptionsMonitor<>).MakeGenericType(SettingsType))!; monitor.GetType().GetProperty("CurrentValue")!.GetValue(monitor).Should().BeOfType(SettingsType); var factory = services.GetService(typeof(IOptionsFactory<>).MakeGenericType(SettingsType))!; factory.GetType().GetMethod("Create")!.Invoke(factory, [Options.DefaultName]).Should().BeOfType(SettingsType); services.GetService(typeof(IOptionsMonitorCache<>).MakeGenericType(SettingsType)).Should().NotBeNull(); } [Fact] public void ActivatorUtilities_builds_a_module_bean_that_takes_its_own_options() { var bean = ActivatorUtilities.CreateInstance(CollectibleTypeServiceProvider.For(_host), OptionsBeanType); bean.GetType().GetField("Options")!.GetValue(bean).Should().NotBeNull(); } [Fact] public void A_wrapped_provider_is_not_wrapped_twice() { var once = CollectibleTypeServiceProvider.For(_host); CollectibleTypeServiceProvider.For(once).Should().BeSameAs(once); } [Fact] public void Arrays_and_generics_over_a_module_type_involve_it() { CollectibleTypeServiceProvider.InvolvesCollectible(ModuleType.MakeArrayType()).Should().BeTrue(); CollectibleTypeServiceProvider.InvolvesCollectible(typeof(Dictionary<,>).MakeGenericType(typeof(string), ModuleType)) .Should().BeTrue(); CollectibleTypeServiceProvider.InvolvesCollectible(typeof(List)).Should().BeFalse(); CollectibleTypeServiceProvider.InvolvesCollectible(typeof(List<>)).Should().BeFalse(); } private static Type EmitSettings() { var type = Module.DefineType("Module.Settings", TypeAttributes.Public | TypeAttributes.Sealed); type.DefineDefaultConstructor(MethodAttributes.Public); return type.CreateType(); } /// /// A public class of the collectible assembly whose constructor takes one service (built from the type itself) and /// keeps it in the public field . /// private static Type EmitBean(string name, Func parameter, string fieldName) { var type = Module.DefineType(name, TypeAttributes.Public | TypeAttributes.Sealed); var field = type.DefineField(fieldName, typeof(object), FieldAttributes.Public); var constructor = type.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, [parameter(type)]); var il = constructor.GetILGenerator(); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Call, typeof(object).GetConstructor(Type.EmptyTypes)!); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldarg_1); il.Emit(OpCodes.Stfld, field); il.Emit(OpCodes.Ret); return type.CreateType(); } } Path: redb-route/tests/redb.Route.Tests/Core/ConcurrencyOptionTests.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/ConcurrencyOptionTests.cs ---- using redb.Route.Components; using redb.Route.Core; namespace redb.Route.Tests.Core; /// /// The one resolver behind every consumer-concurrency option that accepts auto. /// Red-before context: these options used to /// be int-typed, so concurrentConsumers=auto — and any typo — silently bound to the /// default of 1; the garbage cases below THREW nowhere before the string conversion. /// public sealed class ConcurrencyOptionTests { [Fact] public void Auto_IsAtLeastTwo_AndCpuBound() { ConcurrencyOption.Auto.Should().Be(Math.Max(Environment.ProcessorCount, 2), "the NServiceBus formula: max(CPU, 2)"); } [Theory] [InlineData(null, 1)] [InlineData("", 1)] [InlineData(" ", 1)] [InlineData("1", 1)] [InlineData("7", 7)] [InlineData(" 3 ", 3)] public void Resolve_NumbersAndDefault(string? raw, int expected) => ConcurrencyOption.Resolve(raw, "concurrentConsumers").Should().Be(expected); [Theory] [InlineData("auto")] [InlineData("AUTO")] [InlineData("Auto")] [InlineData(" auto ")] public void Resolve_Auto_IsCaseInsensitive(string raw) => ConcurrencyOption.Resolve(raw, "concurrentConsumers").Should().Be(ConcurrencyOption.Auto); [Theory] [InlineData("0")] [InlineData("-1")] [InlineData("trash")] [InlineData("2x")] [InlineData("1.5")] public void Resolve_Garbage_FailsLoud_NamingTheOption(string raw) { var act = () => ConcurrencyOption.Resolve(raw, "concurrentConsumers"); act.Should().Throw() .WithMessage("*concurrentConsumers*", "the error must name the option") .WithMessage("*auto*", "and hint at the valid values"); } [Fact] public void Resolve_CustomDefault_IsHonored() => ConcurrencyOption.Resolve(null, "x", defaultValue: 5).Should().Be(5); [Fact] public void Seda_AutoBinds_AndGarbageFailsLoud() { // The end-to-end proof through a real component: "auto" resolves, garbage throws at // endpoint creation. On the old int options both silently became 1. var context = new RouteContext(); var auto = context.GetEndpoint("seda:v5-auto?concurrentConsumers=auto"); var opts = (SedaEndpointOptions)typeof(EndpointBase) .GetProperty("Options", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)! .GetValue(auto)!; opts.ResolvedConcurrentConsumers.Should().Be(ConcurrencyOption.Auto); var act = () => context.GetEndpoint("seda:v5-bad?concurrentConsumers=trash"); act.Should().Throw().WithMessage("*concurrentConsumers*"); } } Path: redb-route/tests/redb.Route.Tests/Core/ConnectionEventHookTests.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/ConnectionEventHookTests.cs ---- using System.Collections.Concurrent; using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.ControlBus; using redb.Route.Core; namespace redb.Route.Tests.Core; /// /// The connection event hook: what a reports reaches /// and the controlbus:notify routes, in order, with the /// endpoint and the consumer's route; a failing or slow listener holds up nothing; and a route can react with the /// existing controlbus:route actions. /// public sealed class ConnectionEventHookTests { [Fact] public async Task A_listener_gets_loss_failed_attempt_and_recovery_in_order_with_endpoint_and_route() { await using var context = new RouteContext(); var listener = new RecordingListener(); context.AddLifecycleListener(listener); var endpoint = await StartSource(context); var worker = endpoint.Worker!; worker.Lost(new IOException("connect to amqp://user:s3cret@host broken")); worker.Failed(new IOException("refused")); worker.Restored(); (await Eventually(() => listener.Events.Count == 3)).Should().BeTrue(); var events = listener.Events.ToArray(); events.Select(e => e.Kind).Should().Equal( ConnectionEventKind.Lost, ConnectionEventKind.AttemptFailed, ConnectionEventKind.Restored); events.Should().AllSatisfy(e => { e.RouteId.Should().Be("orders-in", "the route whose consumer reads from the endpoint"); e.Endpoint.Should().StartWith("sup:"); e.Connection.Should().Be("sup worker"); }); events[0].ErrorMessage.Should().NotContain("s3cret"); events[1].Attempt.Should().Be(1); events[1].State.Should().Be(ConnectionState.Disconnected); events[2].Reconnects.Should().Be(1); } [Fact] public async Task The_event_reader_ends_when_the_context_is_disposed() { var context = new RouteContext(); var listener = new RecordingListener(); context.AddLifecycleListener(listener); var endpoint = await StartSource(context); endpoint.Worker!.Lost(new IOException("broken")); (await Eventually(() => listener.Events.Count == 1)).Should().BeTrue(); var reader = context.ConnectionEventReader; reader.Should().NotBeNull(); await context.DisposeAsync(); (await Task.WhenAny(reader!, Task.Delay(TimeSpan.FromSeconds(5)))).Should().BeSameAs(reader, "nothing of the dispatcher runs after the context is gone"); } [Fact] public async Task A_producer_connection_has_no_route() { await using var context = new RouteContext(); var listener = new RecordingListener(); context.AddLifecycleListener(listener); context.AddComponent(new SupervisedComponent()); var endpoint = (SupervisedEndpoint)context.GetEndpoint("sup://producer-side"); endpoint.Supervise("sup producer", null).Lost(new IOException("broken")); (await Eventually(() => listener.Events.Count == 1)).Should().BeTrue(); listener.Events.Single().RouteId.Should().BeNull(); } [Fact] public async Task A_throwing_or_blocked_listener_holds_up_nothing_and_full_queues_drop_the_oldest() { await using var context = new RouteContext(); var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var throwing = new RecordingListener { Throw = true }; var blocked = new RecordingListener { Gate = gate.Task }; context.AddLifecycleListener(throwing); context.AddLifecycleListener(blocked); var endpoint = await StartSource(context); var worker = endpoint.Worker!; var reports = Task.Run(() => { for (var i = 0; i < 1500; i++) { worker.Lost(new IOException("broken")); worker.Restored(); } }); (await Task.WhenAny(reports, Task.Delay(TimeSpan.FromSeconds(10)))).Should().BeSameAs(reports, "the supervisor never waits for listeners"); context.DroppedConnectionEvents.Should().BeGreaterThan(0, "3000 events do not fit the queue of a blocked listener"); gate.SetResult(); (await Eventually(() => blocked.Events.Count >= ConnectionEventDispatcher.Capacity)).Should().BeTrue(); throwing.Calls.Should().BeGreaterThan(0, "the throwing listener was called and its errors only logged"); } [Fact] public async Task A_notify_route_gets_the_connection_events_as_messages() { var received = new ConcurrentQueue(); await using var context = new RouteContext(); context.AddComponent(new SupervisedComponent()); context.AddRoutes(r => { r.From("sup://broker").RouteId("orders-in").Process(_ => { }); r.From("controlbus:notify?events=ConnectionLost,ConnectionRestored").RouteId("watch") .Process(e => received.Enqueue(e.In)); }); await context.Start(); var worker = ((SupervisedEndpoint)context.GetEndpoint("sup://broker")).Worker!; worker.Lost(new IOException("broken")); worker.Failed(new IOException("refused")); worker.Restored(); (await Eventually(() => received.Count == 2)).Should().BeTrue("ReconnectFailed is filtered out"); var lost = received.Single(m => m.GetHeader(ControlBusHeaders.Event) == "ConnectionLost"); lost.GetHeader(ControlBusHeaders.RouteId).Should().Be("orders-in"); lost.GetHeader(ControlBusHeaders.Connection).Should().Be("sup worker"); lost.GetHeader(ControlBusHeaders.ConnectionState).Should().Be("Recovering"); lost.GetHeader(ControlBusHeaders.Error).Should().Be("broken"); received.Should().ContainSingle(m => m.GetHeader(ControlBusHeaders.Event) == "ConnectionRestored"); } [Fact] public async Task A_route_fails_the_consumer_route_on_a_failed_reconnect_with_controlbus_route() { await using var context = new RouteContext(); context.AddComponent(new SupervisedComponent()); context.AddRoutes(r => { r.From("sup://broker").RouteId("orders-in").Process(_ => { }); r.From("controlbus:notify?events=ReconnectFailed&routeId=orders-in").RouteId("give-up") .To("controlbus:route?routeId=orders-in&action=fail"); }); await context.Start(); var worker = ((SupervisedEndpoint)context.GetEndpoint("sup://broker")).Worker!; worker.Lost(new IOException("broken")); worker.Failed(new IOException("refused")); (await Eventually(() => context.Routes.Single(x => x.RouteId == "orders-in").Status == RouteStatus.Errored)) .Should().BeTrue("the reaction route failed the consumer route"); } private static async Task StartSource(RouteContext context) { context.AddComponent(new SupervisedComponent()); context.AddRoutes(r => r.From("sup://broker").RouteId("orders-in").Process(_ => { })); await context.Start(); return (SupervisedEndpoint)context.GetEndpoint("sup://broker"); } private static async Task Eventually(Func condition, int seconds = 10) { var deadline = DateTime.UtcNow.AddSeconds(seconds); while (DateTime.UtcNow < deadline) { if (condition()) return true; await Task.Delay(25); } return condition(); } private sealed class RecordingListener : IRouteLifecycleListener { public ConcurrentQueue Events { get; } = new(); public bool Throw { get; init; } public Task? Gate { get; init; } public int Calls; public async Task OnConnectionEvent(ConnectionEvent connectionEvent, CancellationToken ct) { Interlocked.Increment(ref Calls); if (Gate is { } gate) await gate; if (Throw) throw new InvalidOperationException("listener bug"); Events.Enqueue(connectionEvent); } } private sealed class SupervisedComponent : ComponentBase { public override string Scheme => "sup"; public override IEndpoint CreateEndpoint(EndpointUri uri) => new SupervisedEndpoint(uri, this); } private sealed class SupervisedOptions : EndpointOptions { public override void Validate() { } } private sealed class SupervisedEndpoint(EndpointUri uri, IComponent component) : EndpointBase(uri, component, new SupervisedOptions()) { public ConnectionSupervisor? Worker { get; set; } public override IProducer CreateProducer() => throw new NotSupportedException(); public override IConsumer CreateConsumer(IProcessor processor) => new SupervisedConsumer(this); } /// A consumer that supervises one connection while it runs, as a broker consumer does. private sealed class SupervisedConsumer(SupervisedEndpoint endpoint) : IConsumer { public IEndpoint Endpoint => endpoint; public Task Start(CancellationToken ct = default) { endpoint.Worker = endpoint.Supervise("sup worker", null); return Task.CompletedTask; } public Task Stop(CancellationToken ct = default) { if (endpoint.Worker is { } worker) endpoint.Unsupervise(worker); return Task.CompletedTask; } } } Path: redb-route/tests/redb.Route.Tests/Core/ConnectionFactorySecretsTests.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/ConnectionFactorySecretsTests.cs ---- using System.Text.RegularExpressions; using AwesomeAssertions; namespace redb.Route.Tests.Core; /// /// A connection factory holds the credentials a route must not write into its URI, and [Sensitive] is the one /// declaration that tells every renderer to mask them. No test project references every connector, so the guard reads /// the factories' sources: a public property whose name says it is a secret carries the attribute. /// public class ConnectionFactorySecretsTests { private static readonly Regex SecretProperty = new( @"^\s*public\s+(?:required\s+)?[\w<>?.\[\]]+\s+(\w*(?:Password|Passphrase|Secret|SecretKey|Token|ApiKey|AccessKey|ConnectionString))\s*\{", RegexOptions.Multiline); private static string SourceRoot() { for (var dir = new DirectoryInfo(AppContext.BaseDirectory); dir is not null; dir = dir.Parent) if (File.Exists(Path.Combine(dir.FullName, "redb.Route.slnx"))) return Path.Combine(dir.FullName, "src"); throw new InvalidOperationException("redb.Route.slnx not found above the test output directory."); } [Fact] public void Every_secret_of_a_connection_factory_is_marked_sensitive() { var unmarked = new List(); foreach (var file in Directory.EnumerateFiles(SourceRoot(), "*ConnectionFactory.cs", SearchOption.AllDirectories) .Where(f => !f.Contains($"{Path.DirectorySeparatorChar}obj{Path.DirectorySeparatorChar}"))) { var lines = File.ReadAllLines(file); for (var i = 0; i < lines.Length; i++) { var match = SecretProperty.Match(lines[i]); if (!match.Success) continue; var previous = lines.Take(i).LastOrDefault(l => !string.IsNullOrWhiteSpace(l) && !l.TrimStart().StartsWith("///")) ?? ""; if (!lines[i].Contains("Sensitive]") && !previous.Contains("Sensitive]")) unmarked.Add($"{Path.GetFileName(file)}: {match.Groups[1].Value}"); } } unmarked.Should().BeEmpty("a credential on a connection factory is masked by declaration, not by luck"); } } Path: redb-route/tests/redb.Route.Tests/Core/ConnectionParameterTests.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/ConnectionParameterTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Tests.Core; /// /// A named connection factory is the whole connection, as in Camel ("all connection options set on URI are not /// used"). An option a factory sets is declared so ([ConnectionParameter]), the option naming the factory is /// declared too ([ConnectionFactoryReference]), and the core refuses the first beside the second for every /// connector, when the endpoint's options are bound — naming the parameters, never their values. /// public class ConnectionParameterTests { public sealed class Probe : EndpointOptions { [ConnectionFactoryReference] public string? ConnectionFactory { get; set; } [ConnectionParameter] public string? Host { get; set; } [ConnectionParameter, Sensitive] public string? Password { get; set; } public string? Exchange { get; set; } public override void Validate() { } } public sealed class Misdeclared : EndpointOptions { [ConnectionParameter] public string? Host { get; set; } public override void Validate() { } } private static void Bind(EndpointOptions options, string query) => options.BindFromUri(EndpointUriParser.Parse("probe://x?" + query).RawParameters); [Fact] public void A_connection_parameter_beside_the_factory_is_refused_by_name_only() { var act = () => Bind(new Probe(), "connectionFactory=prod&HOST=broker-2&password=s3cret"); act.Should().Throw() .WithMessage("*'prod'*HOST*password*") .Which.Message.Should().NotContain("s3cret").And.NotContain("broker-2"); } [Fact] public void Endpoint_options_beside_the_factory_are_accepted() => Bind(new Probe(), "connectionFactory=prod&exchange=orders"); [Fact] public void Connection_parameters_without_a_factory_are_accepted() => Bind(new Probe(), "host=broker-2&password=x"); [Fact] public void The_parameters_are_found_as_written() => EndpointOptions.WrittenBesideConnectionFactory(typeof(Probe), EndpointUriParser.Parse("probe://x?connectionFactory=prod&HOST=h&exchange=e")) .Should().Equal("HOST"); [Fact] public void Connection_parameters_without_a_declared_factory_option_are_a_declaration_error() { var act = () => Bind(new Misdeclared(), "host=h"); act.Should().Throw().WithMessage("*ConnectionFactoryReference*"); } } Path: redb-route/tests/redb.Route.Tests/Core/ConnectionSupervisorTests.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/ConnectionSupervisorTests.cs ---- using AwesomeAssertions; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Time.Testing; using redb.Route.Abstractions; using redb.Route.Configuration; using redb.Route.Core; namespace redb.Route.Tests.Core; /// /// : the state of one supervised connection, the pauses between reconnect attempts, the /// bound of one connect, the log lines and the health it gives its endpoint. Time is a . /// public sealed class ConnectionSupervisorTests { private static readonly DateTimeOffset Start = new(2026, 12, 5, 10, 0, 0, TimeSpan.Zero); private readonly FakeTimeProvider _time = new(Start); private readonly CapturingLogger _log = new(); private ConnectionSupervisor Create(ReconnectOptions? options = null) => new("wmq:ORDERS consumer worker 1", options ?? new ReconnectOptions(), _log, _time); [Fact] public void Pauses_start_at_one_second_double_after_each_failure_and_stop_at_thirty() { var supervisor = Create(); supervisor.Lost(new IOException("broken")).Should().BeTrue(); supervisor.DueIn.Should().Be(TimeSpan.FromSeconds(1)); var seen = new List(); for (var i = 0; i < 7; i++) { supervisor.Failed(new IOException("still down")); seen.Add(supervisor.DueIn); } seen.Select(d => d.TotalSeconds).Should().Equal(2, 4, 8, 16, 30, 30, 30); } [Fact] public void DueIn_counts_down_with_the_clock() { var supervisor = Create(); supervisor.Lost(new IOException("broken")); _time.Advance(TimeSpan.FromMilliseconds(400)); supervisor.DueIn.Should().Be(TimeSpan.FromMilliseconds(600)); _time.Advance(TimeSpan.FromSeconds(5)); supervisor.DueIn.Should().Be(TimeSpan.Zero); } [Fact] public void Restored_resets_the_schedule_for_the_next_loss() { var supervisor = Create(); supervisor.Lost(new IOException("first")); supervisor.Failed(new IOException("down")); supervisor.Failed(new IOException("down")); supervisor.Restored(); supervisor.Lost(new IOException("second")).Should().BeTrue(); supervisor.DueIn.Should().Be(TimeSpan.FromSeconds(1)); supervisor.Failed(new IOException("down")); supervisor.DueIn.Should().Be(TimeSpan.FromSeconds(2)); } [Fact] public void A_loss_is_Warning_until_an_attempt_fails_then_Critical_then_nothing_once_restored() { var supervisor = Create(); supervisor.State.Should().Be(ConnectionState.Connected); supervisor.Condition.Should().BeNull(); supervisor.Lost(new IOException("MQRC_CONNECTION_BROKEN")); supervisor.State.Should().Be(ConnectionState.Recovering); supervisor.Condition!.Value.Status.Should().Be(EndpointHealthStatus.Warning); supervisor.Condition!.Value.Reason.Should().Contain("wmq:ORDERS consumer worker 1").And.Contain("MQRC_CONNECTION_BROKEN"); supervisor.Failed(new IOException("connect refused")); supervisor.State.Should().Be(ConnectionState.Disconnected); supervisor.Condition!.Value.Status.Should().Be(EndpointHealthStatus.Critical); supervisor.Condition!.Value.Reason.Should().Contain("connect refused").And.Contain("next attempt in 2 s"); supervisor.Restored(); supervisor.State.Should().Be(ConnectionState.Connected); supervisor.Condition.Should().BeNull(); supervisor.LastFailure.Should().BeNull(); supervisor.Reconnects.Should().Be(1); } [Fact] public void With_a_warning_period_a_loss_stays_Warning_until_the_period_has_passed() { var supervisor = Create(new ReconnectOptions { WarningPeriod = TimeSpan.FromSeconds(30) }); supervisor.Lost(new IOException("blip")); supervisor.Failed(new IOException("still down")); supervisor.State.Should().Be(ConnectionState.Recovering, "a failed attempt inside the warning period is not Critical yet"); _time.Advance(TimeSpan.FromSeconds(30)); supervisor.State.Should().Be(ConnectionState.Disconnected, "the loss outlived the warning period"); supervisor.Condition!.Value.Status.Should().Be(EndpointHealthStatus.Critical); } [Fact] public void One_warning_per_loss_and_one_information_per_recovery_however_many_reports() { var supervisor = Create(); supervisor.Lost(new IOException("broken")).Should().BeTrue(); supervisor.Lost(new IOException("broken again")).Should().BeFalse("the loss is already known"); for (var i = 0; i < 5; i++) supervisor.Failed(new IOException("down")); supervisor.Restored(); supervisor.Restored(); _log.Entries.Count(e => e.Level == LogLevel.Warning).Should().Be(1); _log.Entries.Count(e => e.Level == LogLevel.Information).Should().Be(1); _log.Entries.Single(e => e.Level == LogLevel.Information).Text.Should().Contain("reconnected after"); _log.Entries.Count(e => e.Level >= LogLevel.Error).Should().Be(0); supervisor.Reconnects.Should().Be(1); } [Fact] public void A_repeated_loss_report_replaces_the_last_failure() { var supervisor = Create(); supervisor.Lost(new IOException("first")); supervisor.Lost(new IOException("second")); supervisor.LastFailure.Should().Be("second"); } [Fact] public void Failed_and_Restored_are_ignored_while_connected() { var supervisor = Create(); supervisor.Failed(new IOException("stray")); supervisor.Restored(); supervisor.State.Should().Be(ConnectionState.Connected); supervisor.Reconnects.Should().Be(0); _log.Entries.Should().BeEmpty(); } [Fact] public async Task A_connect_that_does_not_finish_in_time_fails_and_its_late_result_is_closed() { var supervisor = Create(new ReconnectOptions { AttemptTimeout = TimeSpan.FromSeconds(30) }); var connect = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var closed = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var attempt = supervisor.AttemptAsync(_ => connect.Task, closed.SetResult, CancellationToken.None); _time.Advance(TimeSpan.FromSeconds(30)); var failure = await FluentActions.Awaiting(() => attempt).Should().ThrowAsync(); failure.Which.Message.Should().Contain("Reconnect.AttemptTimeout"); connect.SetResult("late connection"); (await closed.Task.WaitAsync(TimeSpan.FromSeconds(5))).Should().Be("late connection"); } [Fact] public async Task A_connect_in_time_returns_its_result() { var supervisor = Create(); var result = await supervisor.AttemptAsync(_ => Task.FromResult(42), _ => throw new InvalidOperationException(), CancellationToken.None); result.Should().Be(42); } [Fact] public async Task A_cancelled_attempt_throws_cancellation() { var supervisor = Create(); using var cts = new CancellationTokenSource(); var never = new TaskCompletionSource(); var attempt = supervisor.AttemptAsync(_ => never.Task, _ => { }, cts.Token); cts.Cancel(); await FluentActions.Awaiting(() => attempt).Should().ThrowAsync(); } [Fact] public async Task The_reconnect_loop_waits_each_pause_retries_and_reports_the_recovery() { var supervisor = Create(); supervisor.Lost(new IOException("broken")); var calls = 0; var loop = supervisor.ReconnectAsync(_ => { calls++; return calls < 3 ? Task.FromException(new IOException($"refused {calls}")) : Task.CompletedTask; }, CancellationToken.None); await AdvanceUntil(() => calls == 1, TimeSpan.FromSeconds(1)); supervisor.State.Should().Be(ConnectionState.Disconnected); supervisor.DueIn.Should().Be(TimeSpan.FromSeconds(2)); await AdvanceUntil(() => calls == 2, TimeSpan.FromSeconds(2)); await AdvanceUntil(() => calls == 3, TimeSpan.FromSeconds(4)); (await loop.WaitAsync(TimeSpan.FromSeconds(5))).Should().BeTrue(); supervisor.State.Should().Be(ConnectionState.Connected); supervisor.Reconnects.Should().Be(1); } [Fact] public async Task The_reconnect_loop_ends_with_false_when_its_owner_stops() { var supervisor = Create(); supervisor.Lost(new IOException("broken")); using var cts = new CancellationTokenSource(); var loop = supervisor.ReconnectAsync(_ => Task.FromException(new IOException("down")), cts.Token); cts.Cancel(); (await loop.WaitAsync(TimeSpan.FromSeconds(5))).Should().BeFalse(); supervisor.State.Should().NotBe(ConnectionState.Connected); } [Fact] public void Every_change_goes_to_the_event_sink_in_order() { var supervisor = Create(); var sink = new ListSink(); supervisor.EventSink = sink; supervisor.Lost(new IOException("broken")); _time.Advance(TimeSpan.FromSeconds(1)); supervisor.Failed(new IOException("refused")); _time.Advance(TimeSpan.FromSeconds(2)); supervisor.Restored(); sink.Changes.Select(c => c.Kind).Should().Equal( ConnectionEventKind.Lost, ConnectionEventKind.AttemptFailed, ConnectionEventKind.Restored); var failed = sink.Changes[1]; failed.Attempt.Should().Be(1); failed.NextDelay.Should().Be(TimeSpan.FromSeconds(2)); failed.Outage.Should().Be(TimeSpan.FromSeconds(1)); failed.State.Should().Be(ConnectionState.Disconnected); failed.Connection.Should().Be("wmq:ORDERS consumer worker 1"); var restored = sink.Changes[2]; restored.Outage.Should().Be(TimeSpan.FromSeconds(3)); restored.Reconnects.Should().Be(1); restored.Error.Should().BeNull(); } [Fact] public void Durations_in_the_health_reason_use_the_invariant_culture() { var saved = System.Globalization.CultureInfo.CurrentCulture; System.Globalization.CultureInfo.CurrentCulture = new System.Globalization.CultureInfo("ru-RU"); try { var supervisor = Create(); supervisor.Lost(new IOException("broken")); supervisor.Failed(new IOException("refused")); _time.Advance(TimeSpan.FromMilliseconds(500)); supervisor.Condition!.Value.Reason.Should().Contain("next attempt in 1.5 s"); } finally { System.Globalization.CultureInfo.CurrentCulture = saved; } } [Fact] public async Task Events_of_one_connection_reach_the_sink_in_the_order_of_the_changes_under_concurrent_reports() { var supervisor = Create(); var sink = new ListSink(); supervisor.EventSink = sink; using var start = new ManualResetEventSlim(); var reporters = Enumerable.Range(0, 4).Select(t => Task.Run(() => { start.Wait(); for (var i = 0; i < 2000; i++) { switch ((i + t) % 3) { case 0: supervisor.Lost(new IOException("broken")); break; case 1: supervisor.Failed(new IOException("refused")); break; default: supervisor.Restored(); break; } } })).ToArray(); start.Set(); await Task.WhenAll(reporters); // A valid sequence per outage: Lost, then AttemptFailed with attempts 1, 2, 3 ..., then Restored. var expectedAttempt = 0; var connected = true; long reconnects = 0; foreach (var change in sink.Changes) { switch (change.Kind) { case ConnectionEventKind.Lost: connected.Should().BeTrue("a loss follows a connected state"); connected = false; expectedAttempt = 0; break; case ConnectionEventKind.AttemptFailed: connected.Should().BeFalse("a failed attempt belongs to an outage"); change.Attempt.Should().Be(++expectedAttempt); break; default: connected.Should().BeFalse("a recovery ends an outage"); connected = true; change.Reconnects.Should().Be(++reconnects); break; } } sink.Changes.Should().NotBeEmpty(); } [Theory] [InlineData(0, 2, 30)] [InlineData(1, 0.5, 30)] [InlineData(5, 2, 1)] public void Invalid_options_are_refused(double delaySeconds, double multiplier, double maxSeconds) { var options = new ReconnectOptions { Delay = TimeSpan.FromSeconds(delaySeconds), Multiplier = multiplier, MaxDelay = TimeSpan.FromSeconds(maxSeconds), }; FluentActions.Invoking(() => Create(options)).Should().Throw() .WithMessage("Reconnect.*"); } [Fact] public void A_non_positive_attempt_timeout_is_refused() { FluentActions.Invoking(() => Create(new ReconnectOptions { AttemptTimeout = TimeSpan.Zero })) .Should().Throw().WithMessage("Reconnect.AttemptTimeout*"); } private async Task AdvanceUntil(Func condition, TimeSpan step) { // The loop runs on the thread pool: let it reach its delay before the clock moves, then wait for the attempt. for (var i = 0; i < 200 && !condition(); i++) { await Task.Delay(10); if (i % 5 == 4) _time.Advance(step); } condition().Should().BeTrue(); } private sealed class ListSink : IConnectionEventSink { public List Changes { get; } = []; public void Post(ConnectionEvent change) { lock (Changes) Changes.Add(change); } } internal sealed class CapturingLogger : ILogger { public List<(LogLevel Level, string Text)> Entries { get; } = []; 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) { lock (Entries) Entries.Add((logLevel, formatter(state, exception))); } } } Path: redb-route/tests/redb.Route.Tests/Core/ConsumerStartRetryTests.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/ConsumerStartRetryTests.cs ---- using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Logging; using NSubstitute; using redb.Route.Abstractions; using redb.Route.Configuration; using redb.Route.Core; using redb.Route.Definitions; using redb.Route.Extensions; using redb.Route.Processors; namespace redb.Route.Tests.Core; /// /// A consumer that fails to start with its context (a broker not up yet) is started again in the background /// (): the route stays Errored while it waits and becomes Started /// once the consumer starts. The start-up log names the Errored routes instead of reporting everything operational. /// public sealed class ConsumerStartRetryTests { private static readonly TimeSpan Wait = TimeSpan.FromSeconds(10); private sealed class CapturingLoggerProvider : ILoggerProvider { public List<(LogLevel Level, string Text)> Entries { get; } = []; public ILogger CreateLogger(string categoryName) => new Logger(this); public void Dispose() { } private sealed class Logger(CapturingLoggerProvider 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) { lock (owner.Entries) owner.Entries.Add((logLevel, formatter(state, exception))); } } } private sealed class Recorder : IRouteLifecycleListener { public List Events { get; } = []; public Task OnRouteStarted(string routeId, CancellationToken ct) { lock (Events) Events.Add($"RouteStarted:{routeId}"); return Task.CompletedTask; } public Task OnRouteErrored(string routeId, Exception ex, CancellationToken ct) { lock (Events) Events.Add($"RouteErrored:{routeId}"); return Task.CompletedTask; } } /// A consumer whose first starts throw, then starts succeed. private static IConsumer Consumer(int failures) { var calls = 0; var consumer = Substitute.For(); consumer.Start(Arg.Any()).Returns(_ => { return Interlocked.Increment(ref calls) <= failures ? Task.FromException(new InvalidOperationException("broker unreachable")) : Task.CompletedTask; }); consumer.Stop(Arg.Any()).Returns(Task.CompletedTask); return consumer; } private static RouteContext Context(ConsumerStartRetryOptions retry, ILoggerFactory? loggerFactory = null) => new(loggerFactory: loggerFactory, options: new RouteEngineOptions { ShutdownTimeout = TimeSpan.FromMilliseconds(500), ConsumerStartRetry = retry, }); private static ConsumerStartRetryOptions Fast(int maxAttempts = 0, bool enabled = true) => new() { Enabled = enabled, Delay = TimeSpan.FromMilliseconds(20), Multiplier = 1.0, MaxDelay = TimeSpan.FromMilliseconds(20), MaxAttempts = maxAttempts, }; private static void AddRoute(RouteContext context, string id, IConsumer consumer, bool autoStart = true) { context.AddConsumer(consumer); context.AddRoute(new CompiledRoute(id, $"direct://{id}", new RouteDefinition(), new PipelineProcessor(), consumer, Substitute.For()) { AutoStart = autoStart }); } private static async Task Until(Func condition) { var deadline = DateTime.UtcNow + Wait; while (!condition()) { if (DateTime.UtcNow > deadline) throw new TimeoutException("the condition did not come true in time"); await Task.Delay(10); } } private static int StartCalls(IConsumer consumer) => consumer.ReceivedCalls().Count(c => c.GetMethodInfo().Name == nameof(IConsumer.Start)); [Fact] public async Task A_consumer_that_failed_to_start_is_started_again_and_the_route_becomes_Started() { await using var context = Context(Fast()); var recorder = new Recorder(); context.AddLifecycleListener(recorder); var consumer = Consumer(failures: 3); AddRoute(context, "late-broker", consumer); await context.Start(); context.GetRoute("late-broker")!.Status.Should().Be(RouteStatus.Errored); await Until(() => context.GetRoute("late-broker")!.Status == RouteStatus.Started); StartCalls(consumer).Should().Be(4, "one start with the context and three retries, the last one succeeding"); lock (recorder.Events) recorder.Events.Should().Equal("RouteErrored:late-broker", "RouteStarted:late-broker"); } [Fact] public async Task The_retries_stop_after_MaxAttempts_and_the_route_stays_Errored() { await using var context = Context(Fast(maxAttempts: 2)); var consumer = Consumer(failures: int.MaxValue); AddRoute(context, "never-up", consumer); await context.Start(); await Until(() => StartCalls(consumer) == 3); await Task.Delay(200); StartCalls(consumer).Should().Be(3, "one start with the context and two retries"); context.GetRoute("never-up")!.Status.Should().Be(RouteStatus.Errored); } [Fact] public async Task With_retry_off_the_consumer_is_not_started_again() { await using var context = Context(Fast(enabled: false)); var consumer = Consumer(failures: 1); AddRoute(context, "no-retry", consumer); await context.Start(); await Task.Delay(200); StartCalls(consumer).Should().Be(1); context.GetRoute("no-retry")!.Status.Should().Be(RouteStatus.Errored); } [Fact] public async Task Stopping_the_context_ends_the_retries() { var context = Context(Fast()); var consumer = Consumer(failures: int.MaxValue); AddRoute(context, "stopped-context", consumer); await context.Start(); await Until(() => StartCalls(consumer) >= 2); await context.Stop(); var afterStop = StartCalls(consumer); await Task.Delay(200); StartCalls(consumer).Should().Be(afterStop); await context.DisposeAsync(); } [Fact] public async Task A_route_stopped_by_hand_is_not_started_again() { var retry = Fast(); retry.Delay = retry.MaxDelay = TimeSpan.FromMilliseconds(300); await using var context = Context(retry); var consumer = Consumer(failures: 1); AddRoute(context, "by-hand", consumer); await context.Start(); await context.StopRoute("by-hand"); await Task.Delay(600); StartCalls(consumer).Should().Be(1); context.GetRoute("by-hand")!.Status.Should().Be(RouteStatus.Stopped); } [Fact] public async Task A_route_failed_by_the_control_bus_is_not_started_again() { // controlbus action=fail stops the route and marks it Errored: an Errored the retry did not leave behind. var retry = Fast(); retry.Delay = retry.MaxDelay = TimeSpan.FromMilliseconds(300); await using var context = Context(retry); var consumer = Consumer(failures: 1); AddRoute(context, "failed-by-hand", consumer); await context.Start(); await context.StopRoute("failed-by-hand"); context.GetRoute("failed-by-hand")!.Status = RouteStatus.Errored; await Task.Delay(600); StartCalls(consumer).Should().Be(1); context.GetRoute("failed-by-hand")!.Status.Should().Be(RouteStatus.Errored); } [Fact] public async Task A_route_started_by_hand_meanwhile_is_left_to_it() { var retry = Fast(); retry.Delay = retry.MaxDelay = TimeSpan.FromMilliseconds(300); await using var context = Context(retry); var consumer = Consumer(failures: 1); AddRoute(context, "started-by-hand", consumer); await context.Start(); await context.StartRoute("started-by-hand"); await Task.Delay(600); StartCalls(consumer).Should().Be(2, "the start with the context and the start by hand, no retry"); context.GetRoute("started-by-hand")!.Status.Should().Be(RouteStatus.Started); } private sealed class RefusingPolicy : IRoutePolicy { public int Starts; public Task OnStart(IRouteContext context, CompiledRoute route, CancellationToken ct) { Interlocked.Increment(ref Starts); throw new InvalidOperationException("policy refuses"); } } [Fact] public async Task A_policy_that_refuses_on_retry_leaves_no_consumer_running() { await using var context = Context(Fast()); var consumer = Consumer(failures: 1); AddRoute(context, "refused", consumer); var policy = new RefusingPolicy(); context.GetRoute("refused")!.Policy = policy; await context.Start(); await Until(() => Volatile.Read(ref policy.Starts) == 1); await Task.Delay(200); StartCalls(consumer).Should().Be(1, "the policy is asked before the consumer, as StartRoute does"); context.GetRoute("refused")!.Status.Should().Be(RouteStatus.Errored); policy.Starts.Should().Be(1, "a refusing policy ends the retry"); } [Fact] public async Task A_route_with_AutoStart_off_is_not_retried() { await using var context = Context(Fast()); var consumer = Consumer(failures: int.MaxValue); AddRoute(context, "manual", consumer, autoStart: false); await context.Start(); await Task.Delay(200); StartCalls(consumer).Should().Be(0); context.GetRoute("manual")!.Status.Should().Be(RouteStatus.Stopped); } [Fact] public async Task The_start_log_names_the_Errored_routes_instead_of_all_endpoints_operational() { var provider = new CapturingLoggerProvider(); using var factory = LoggerFactory.Create(b => b.AddProvider(provider).SetMinimumLevel(LogLevel.Trace)); var retry = Fast(); retry.Delay = retry.MaxDelay = TimeSpan.FromSeconds(30); await using var context = Context(retry, factory); AddRoute(context, "good", Consumer(failures: 0)); AddRoute(context, "bad", Consumer(failures: int.MaxValue)); await context.Start(); List<(LogLevel Level, string Text)> entries; lock (provider.Entries) entries = [.. provider.Entries]; entries.Should().NotContain(e => e.Text.Contains("endpoints operational")); entries.Should().Contain(e => e.Level == LogLevel.Warning && e.Text.Contains("1 of 2 route(s) Errored: bad") && e.Text.Contains("started again in the background")); } [Fact] public async Task The_start_log_reports_all_operational_when_every_route_started() { var provider = new CapturingLoggerProvider(); using var factory = LoggerFactory.Create(b => b.AddProvider(provider).SetMinimumLevel(LogLevel.Trace)); await using var context = Context(Fast(), factory); AddRoute(context, "good", Consumer(failures: 0)); await context.Start(); lock (provider.Entries) provider.Entries.Should().Contain(e => e.Level == LogLevel.Information && e.Text.Contains("endpoints operational")); } [Theory] [InlineData(0, 2.0, 60_000, 0)] [InlineData(2_000, 0.5, 60_000, 0)] [InlineData(2_000, 2.0, 1_000, 0)] [InlineData(2_000, 2.0, 60_000, -1)] public void Invalid_settings_are_refused_when_the_context_is_created( int delayMs, double multiplier, int maxDelayMs, int maxAttempts) { var retry = new ConsumerStartRetryOptions { Delay = TimeSpan.FromMilliseconds(delayMs), Multiplier = multiplier, MaxDelay = TimeSpan.FromMilliseconds(maxDelayMs), MaxAttempts = maxAttempts, }; var act = () => Context(retry); act.Should().Throw(); } [Fact] public void The_defaults_retry_without_a_limit_from_two_seconds_up_to_a_minute() { var retry = new RouteEngineOptions().ConsumerStartRetry; retry.Enabled.Should().BeTrue(); retry.Delay.Should().Be(TimeSpan.FromSeconds(2)); retry.Multiplier.Should().Be(2.0); retry.MaxDelay.Should().Be(TimeSpan.FromMinutes(1)); retry.MaxAttempts.Should().Be(0); retry.UnhealthyOnRestarting.Should().BeTrue("Camel 4.7 and later report a restarting route DOWN"); retry.UnhealthyOnExhausted.Should().BeTrue("Camel 4.7 and later report an exhausted route DOWN"); } private static async Task Health(RouteContext context) => (await new RouteHealthCheck(context).CheckHealthAsync(new HealthCheckContext())).Status; [Theory] [InlineData(true, HealthStatus.Unhealthy)] [InlineData(false, HealthStatus.Degraded)] public async Task UnhealthyOnRestarting_decides_the_health_of_a_route_that_waits_for_a_retry( bool unhealthyOnRestarting, HealthStatus expected) { // A long first pause: the route waits for its first retry while the check is read. var retry = Fast(); retry.Delay = retry.MaxDelay = TimeSpan.FromMinutes(1); retry.UnhealthyOnRestarting = unhealthyOnRestarting; retry.UnhealthyOnExhausted = !unhealthyOnRestarting; await using var context = Context(retry); AddRoute(context, "waiting", Consumer(failures: 1)); await context.Start(); context.GetRoute("waiting")!.Status.Should().Be(RouteStatus.Errored); context.IsErroredRouteUnhealthy(context.GetRoute("waiting")!).Should().Be(unhealthyOnRestarting); (await Health(context)).Should().Be(expected); } [Theory] [InlineData(true, HealthStatus.Unhealthy)] [InlineData(false, HealthStatus.Degraded)] public async Task UnhealthyOnExhausted_decides_the_health_of_a_route_whose_retries_ran_out( bool unhealthyOnExhausted, HealthStatus expected) { var retry = Fast(maxAttempts: 1); retry.UnhealthyOnExhausted = unhealthyOnExhausted; retry.UnhealthyOnRestarting = !unhealthyOnExhausted; await using var context = Context(retry); var consumer = Consumer(failures: int.MaxValue); AddRoute(context, "never-up", consumer); await context.Start(); await Until(() => StartCalls(consumer) == 2); await Until(() => context.IsErroredRouteUnhealthy(context.GetRoute("never-up")!) == unhealthyOnExhausted); context.GetRoute("never-up")!.Status.Should().Be(RouteStatus.Errored); (await Health(context)).Should().Be(expected); } } Path: redb-route/tests/redb.Route.Tests/Core/ConsumerTemplateTests.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/ConsumerTemplateTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Tests.Core; /// /// Tests for : lifecycle, SEDA polling (optimized path), /// generic consumer-based polling, typed body, timeout, and no-wait semantics. /// public class ConsumerTemplateTests : IDisposable { private readonly RouteContext _ctx = new("ct-test"); private readonly ConsumerTemplate _consumer; private readonly ProducerTemplate _producer; public ConsumerTemplateTests() { _consumer = new ConsumerTemplate(_ctx); _producer = new ProducerTemplate(_ctx); } public void Dispose() { if (_producer.IsStarted) _producer.Stop(); if (_consumer.IsStarted) _consumer.Stop(); _producer.Dispose(); _consumer.Dispose(); _ctx.Dispose(); } private void StartBoth() { _producer.Start(); _consumer.Start(); } /// Helper: send a body to a SEDA endpoint. private async Task SendToSeda(string uri, object body) { await _producer.SendAsync(uri, body); } // ── Lifecycle ── [Fact] public void IsStarted_FalseByDefault() { _consumer.IsStarted.Should().BeFalse(); } [Fact] public void Start_SetsIsStarted() { _consumer.Start(); _consumer.IsStarted.Should().BeTrue(); } [Fact] public void Start_WhenAlreadyStarted_Throws() { _consumer.Start(); var act = () => _consumer.Start(); act.Should().Throw().WithMessage("*already started*"); } [Fact] public void Stop_ClearsIsStarted() { _consumer.Start(); _consumer.Stop(); _consumer.IsStarted.Should().BeFalse(); } [Fact] public void Stop_WhenNotStarted_Throws() { var act = () => _consumer.Stop(); act.Should().Throw().WithMessage("*not started*"); } [Fact] public async Task Receive_WhenNotStarted_Throws() { var act = () => _consumer.Receive("seda:test"); await act.Should().ThrowAsync().WithMessage("*not started*"); } [Fact] public void Context_ReturnsRouteContext() { _consumer.Context.Should().BeSameAs(_ctx); } [Fact] public void Constructor_NullContext_Throws() { var act = () => new ConsumerTemplate(null!); act.Should().Throw(); } [Fact] public async Task Dispose_PreventsSubsequentCalls() { _consumer.Start(); _consumer.Dispose(); var act = () => _consumer.Receive("seda:test"); await act.Should().ThrowAsync(); } // ── SEDA: Receive (blocking) ── [Fact] public async Task DoneUoW_On_A_Seda_Exchange_Is_Accepted_Once() { // Callers write one loop for any endpoint: Receive, handle, DoneUoW. A SEDA exchange has no // unit of work to commit, but completing it is still accepted — once. StartBoth(); await SendToSeda("seda:uow", "hello"); var exchange = await _consumer.Receive("seda:uow"); await _consumer.DoneUoW(exchange); var again = () => _consumer.DoneUoW(exchange); await again.Should().ThrowAsync(); } [Fact] public async Task Receive_Seda_ReturnsExchange() { StartBoth(); await SendToSeda("seda:queue1", "hello"); var result = await _consumer.Receive("seda:queue1"); result.In.Body.Should().Be("hello"); } [Fact] public async Task Receive_Seda_FIFO_Order() { StartBoth(); for (var i = 0; i < 5; i++) await SendToSeda("seda:ordered", i); for (var i = 0; i < 5; i++) { var result = await _consumer.Receive("seda:ordered"); result.In.Body.Should().Be(i); } } [Fact] public async Task Receive_Seda_Endpoint_Overload() { StartBoth(); var endpoint = _ctx.GetEndpoint("seda:ep-overload"); await _producer.SendAsync(endpoint, "via-endpoint"); var result = await _consumer.Receive(endpoint); result.In.Body.Should().Be("via-endpoint"); } // ── SEDA: Receive with timeout ── [Fact] public async Task Receive_Seda_WithTimeout_ReturnsExchange() { StartBoth(); await SendToSeda("seda:timeout1", "with-timeout"); var result = await _consumer.Receive("seda:timeout1", TimeSpan.FromSeconds(5)); result.Should().NotBeNull(); result!.In.Body.Should().Be("with-timeout"); } [Fact] public async Task Receive_Seda_Timeout_ReturnsNull() { _consumer.Start(); // No messages in queue — should timeout var result = await _consumer.Receive("seda:empty", TimeSpan.FromMilliseconds(100)); result.Should().BeNull(); } [Fact] public async Task Receive_Seda_Timeout_Endpoint_Overload() { _consumer.Start(); var endpoint = _ctx.GetEndpoint("seda:ep-timeout"); var result = await _consumer.Receive(endpoint, TimeSpan.FromMilliseconds(100)); result.Should().BeNull(); } // ── SEDA: ReceiveNoWait ── [Fact] public async Task ReceiveNoWait_Seda_WithMessage_Returns() { StartBoth(); await SendToSeda("seda:nowait1", "instant"); var result = await _consumer.ReceiveNoWait("seda:nowait1"); result.Should().NotBeNull(); result!.In.Body.Should().Be("instant"); } [Fact] public async Task ReceiveNoWait_Seda_Empty_ReturnsNull() { _consumer.Start(); var result = await _consumer.ReceiveNoWait("seda:nowait-empty"); result.Should().BeNull(); } [Fact] public async Task ReceiveNoWait_Seda_Endpoint_Overload() { _consumer.Start(); var endpoint = _ctx.GetEndpoint("seda:ep-nowait"); var result = await _consumer.ReceiveNoWait(endpoint); result.Should().BeNull(); } // ── Typed body ── [Fact] public async Task ReceiveBody_ReturnsBody() { StartBoth(); await SendToSeda("seda:body1", 42); var body = await _consumer.ReceiveBody("seda:body1"); body.Should().Be(42); } [Fact] public async Task ReceiveBody_Typed_ReturnsTyped() { StartBoth(); await SendToSeda("seda:typed", "typed-value"); var body = await _consumer.ReceiveBody("seda:typed"); body.Should().Be("typed-value"); } [Fact] public async Task ReceiveBody_Typed_Converts() { StartBoth(); await SendToSeda("seda:convert", 42); var body = await _consumer.ReceiveBody("seda:convert"); body.Should().Be("42"); } [Fact] public async Task ReceiveBody_Typed_WithTimeout_ReturnsDefault() { _consumer.Start(); var body = await _consumer.ReceiveBody("seda:nobody", TimeSpan.FromMilliseconds(100)); body.Should().BeNull(); } [Fact] public async Task ReceiveBody_Typed_WithTimeout_ReturnsValue() { StartBoth(); await SendToSeda("seda:bodytimeout", "got-it"); var body = await _consumer.ReceiveBody("seda:bodytimeout", TimeSpan.FromSeconds(5)); body.Should().Be("got-it"); } // ── Cancellation ── [Fact] public async Task Receive_Seda_Cancellation_Throws() { _consumer.Start(); using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(50)); var act = () => _consumer.Receive("seda:cancel", cts.Token); await act.Should().ThrowAsync(); } // ── Integration: ProducerTemplate → ConsumerTemplate via SEDA ── [Fact] public async Task ProducerToConsumer_Seda_Roundtrip() { StartBoth(); await _producer.SendAsync("seda:roundtrip", "ping"); var result = await _consumer.Receive("seda:roundtrip", TimeSpan.FromSeconds(5)); result.Should().NotBeNull(); result!.In.Body.Should().Be("ping"); } [Fact] public async Task ProducerToConsumer_Seda_MultipleMessages() { StartBoth(); for (var i = 0; i < 10; i++) await _producer.SendAsync("seda:multi", $"msg-{i}"); for (var i = 0; i < 10; i++) { var body = await _consumer.ReceiveBody("seda:multi"); body.Should().Be($"msg-{i}"); } } // ── Generic consumer path (Direct endpoint via bridge) ── [Fact] public async Task Receive_Direct_ViaGenericBridge() { StartBoth(); var endpoint = _ctx.GetEndpoint("direct:poll-test"); // Send a message on another thread after a small delay _ = Task.Run(async () => { await Task.Delay(100); _producer.Send(endpoint, "from-direct"); }); var result = await _consumer.Receive(endpoint, TimeSpan.FromSeconds(5)); result.Should().NotBeNull(); result!.In.Body.Should().Be("from-direct"); } [Fact] public async Task ReceiveNoWait_Direct_ReturnsNull_WhenEmpty() { _consumer.Start(); // Direct with no messages — generic path, zero timeout → null var result = await _consumer.ReceiveNoWait("direct:no-msg"); result.Should().BeNull(); } } Path: redb-route/tests/redb.Route.Tests/Core/ContextLifecycleTests.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/ContextLifecycleTests.cs ---- using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Tests.Core; /// /// Tests for context-level lifecycle events: OnContextStarting, OnContextStarted, /// OnContextStopping, OnContextStopped. /// public sealed class ContextLifecycleTests { private sealed class ContextListener : IRouteLifecycleListener { public List Events { get; } = []; public Task OnContextStarting(IRouteContext context, CancellationToken ct) { Events.Add("ContextStarting"); return Task.CompletedTask; } public Task OnContextStarted(IRouteContext context, CancellationToken ct) { Events.Add("ContextStarted"); return Task.CompletedTask; } public Task OnContextStopping(IRouteContext context, CancellationToken ct) { Events.Add("ContextStopping"); return Task.CompletedTask; } public Task OnContextStopped(IRouteContext context, CancellationToken ct) { Events.Add("ContextStopped"); return Task.CompletedTask; } public Task OnRouteStarted(string routeId, CancellationToken ct) { Events.Add($"RouteStarted:{routeId}"); return Task.CompletedTask; } public Task OnRouteStopped(string routeId, CancellationToken ct) { Events.Add($"RouteStopped:{routeId}"); return Task.CompletedTask; } public Task OnRouteSuspending(string routeId, CancellationToken ct) { Events.Add($"RouteSuspending:{routeId}"); return Task.CompletedTask; } public Task OnRouteErrored(string routeId, Exception ex, CancellationToken ct) { Events.Add($"RouteErrored:{routeId}"); return Task.CompletedTask; } public Task OnExchangeTimedOut(string routeId, string exchangeId, TimeSpan elapsed, CancellationToken ct) => Task.CompletedTask; } private static RouteContext CreateContext() => new( options: new Configuration.RouteEngineOptions { EnableTelemetry = false, EnableMetrics = false }); [Fact] public async Task ContextStarting_FiresBeforeRouteStarted() { var listener = new ContextListener(); var ctx = CreateContext(); ctx.AddLifecycleListener(listener); ctx.AddRoutes(r => { r.From("direct://ctx-start") .RouteId("cs-route") .Process(e => { }); }); await ctx.Start(); await ctx.Stop(); var startingIdx = listener.Events.IndexOf("ContextStarting"); var routeStartedIdx = listener.Events.IndexOf("RouteStarted:cs-route"); startingIdx.Should().BeGreaterThanOrEqualTo(0); routeStartedIdx.Should().BeGreaterThanOrEqualTo(0); startingIdx.Should().BeLessThan(routeStartedIdx, "ContextStarting should fire before any route starts"); } [Fact] public async Task ContextStarted_FiresAfterRouteStarted() { var listener = new ContextListener(); var ctx = CreateContext(); ctx.AddLifecycleListener(listener); ctx.AddRoutes(r => { r.From("direct://ctx-started") .RouteId("cs2-route") .Process(e => { }); }); await ctx.Start(); await ctx.Stop(); var routeStartedIdx = listener.Events.IndexOf("RouteStarted:cs2-route"); var startedIdx = listener.Events.IndexOf("ContextStarted"); routeStartedIdx.Should().BeGreaterThanOrEqualTo(0); startedIdx.Should().BeGreaterThanOrEqualTo(0); startedIdx.Should().BeGreaterThan(routeStartedIdx, "ContextStarted should fire after routes start"); } [Fact] public async Task ContextStopping_FiresBeforeRouteStopped() { var listener = new ContextListener(); var ctx = CreateContext(); ctx.AddLifecycleListener(listener); ctx.AddRoutes(r => { r.From("direct://ctx-stop") .RouteId("cstop-route") .Process(e => { }); }); await ctx.Start(); await ctx.Stop(); var stoppingIdx = listener.Events.IndexOf("ContextStopping"); var routeSuspendingIdx = listener.Events.IndexOf("RouteSuspending:cstop-route"); stoppingIdx.Should().BeGreaterThanOrEqualTo(0); routeSuspendingIdx.Should().BeGreaterThanOrEqualTo(0); stoppingIdx.Should().BeLessThan(routeSuspendingIdx, "ContextStopping should fire before routes start suspending"); } [Fact] public async Task ContextStopped_FiresAfterRouteStopped() { var listener = new ContextListener(); var ctx = CreateContext(); ctx.AddLifecycleListener(listener); ctx.AddRoutes(r => { r.From("direct://ctx-stopped") .RouteId("cstop2-route") .Process(e => { }); }); await ctx.Start(); await ctx.Stop(); var routeStoppedIdx = listener.Events.IndexOf("RouteStopped:cstop2-route"); var stoppedIdx = listener.Events.IndexOf("ContextStopped"); routeStoppedIdx.Should().BeGreaterThanOrEqualTo(0); stoppedIdx.Should().BeGreaterThanOrEqualTo(0); stoppedIdx.Should().BeGreaterThan(routeStoppedIdx, "ContextStopped should fire after all routes stopped"); } [Fact] public async Task FullContextLifecycle_CorrectEventOrder() { var listener = new ContextListener(); var ctx = CreateContext(); ctx.AddLifecycleListener(listener); ctx.AddRoutes(r => { r.From("direct://full-ctx") .RouteId("full-route") .Process(e => { }); }); await ctx.Start(); await ctx.Stop(); listener.Events.Should().ContainInOrder( "ContextStarting", "RouteStarted:full-route", "ContextStarted", "ContextStopping", "RouteSuspending:full-route", "RouteStopped:full-route", "ContextStopped"); } [Fact] public async Task MultipleListeners_AllReceiveContextEvents() { var listener1 = new ContextListener(); var listener2 = new ContextListener(); var ctx = CreateContext(); ctx.AddLifecycleListener(listener1); ctx.AddLifecycleListener(listener2); ctx.AddRoutes(r => { r.From("direct://multi-ctx") .RouteId("multi-ctx-route") .Process(e => { }); }); await ctx.Start(); await ctx.Stop(); foreach (var listener in new[] { listener1, listener2 }) { listener.Events.Should().Contain("ContextStarting"); listener.Events.Should().Contain("ContextStarted"); listener.Events.Should().Contain("ContextStopping"); listener.Events.Should().Contain("ContextStopped"); } } [Fact] public async Task ContextEvents_FireEvenWithNoRoutes() { var listener = new ContextListener(); var ctx = CreateContext(); ctx.AddLifecycleListener(listener); // No routes added await ctx.Start(); await ctx.Stop(); listener.Events.Should().Contain("ContextStarting"); listener.Events.Should().Contain("ContextStarted"); listener.Events.Should().Contain("ContextStopping"); listener.Events.Should().Contain("ContextStopped"); } } Path: redb-route/tests/redb.Route.Tests/Core/CorrelatedCopyTests.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/CorrelatedCopyTests.cs ---- using System.Collections.Concurrent; using System.Diagnostics; using AwesomeAssertions; using Microsoft.Extensions.DependencyInjection; using redb.Route.Abstractions; using redb.Route.Components; using redb.Route.Core; using redb.Route.Tests.Telemetry; namespace redb.Route.Tests.Core; /// /// The id of an exchange that crosses to another unit of work, by Apache Camel's table: seda, vm, multicast, recipient /// list, scatter-gather, enrich and on-completion send a correlated copy (a new id, CamelCorrelationId = the /// immediate parent's id, as ExchangeHelper.createCorrelatedCopy); wire tap and poll enrich a copy with a new /// id and no correlation id; direct-vm, threads and loop keep the exchange's id. The original keeps its own id and /// its own correlation id after a fan-out merges back. /// public sealed class CorrelatedCopyTests { private sealed record Seen(string Id, string? Correlation, string? Route); /// A context that can reach vm and direct-vm endpoints (they share a process-wide registry from DI). private static RouteContext NewContext() { var services = new ServiceCollection(); services.AddSingleton(new SharedVmRegistry()); return new RouteContext(services.BuildServiceProvider(), "corr-" + Guid.NewGuid().ToString("N")); } private static Seen Record(IExchange ex) => new(ex.ExchangeId, ex.GetProperty(ExchangePropertyKeys.CorrelationId), ex.RouteId); private static async Task WaitUntil(Func condition, string what) { var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(10); while (DateTime.UtcNow < deadline) { if (condition()) return; await Task.Delay(20); } throw new TimeoutException("Timed out waiting for " + what); } /// /// Runs with a direct:in route that records the original first, sends one message /// and returns what the original and the direct:capture route saw. /// private static async Task<(Seen Origin, Seen[] Captured, IExchange After)> Run( Func define, int expected, string routeIdPrefix = "corr") { await using var ctx = NewContext(); Seen? origin = null; IExchange? after = null; var captured = new ConcurrentQueue(); ctx.AddRoutes(r => { define(r.From("direct:in").RouteId(routeIdPrefix + "-in").Process(ex => origin = Record(ex))) .Process(ex => after = ex); r.From("direct:capture").RouteId(routeIdPrefix + "-capture").Process(ex => captured.Enqueue(Record(ex))); }); await ctx.Start(); using var producer = new ProducerTemplate(ctx); producer.Start(); await producer.SendAsync("direct:in", "payload"); await WaitUntil(() => captured.Count >= expected, $"{expected} captured exchanges"); return (origin!, captured.ToArray(), after!); } // ── The copy itself ── [Fact] public void A_correlated_copy_has_a_new_id_and_the_parent_s_id_as_its_correlation_id() { var original = new Exchange(new Message("x")); var copy = original.CorrelatedCopy(); var linked = original.CorrelatedCopyLinked(); copy.ExchangeId.Should().NotBe(original.ExchangeId); linked.ExchangeId.Should().NotBe(original.ExchangeId).And.NotBe(copy.ExchangeId); copy.GetProperty(ExchangePropertyKeys.CorrelationId).Should().Be(original.ExchangeId); linked.GetProperty(ExchangePropertyKeys.CorrelationId).Should().Be(original.ExchangeId); original.Properties.Should().NotContainKey(ExchangePropertyKeys.CorrelationId); original.Clone().ExchangeId.Should().Be(original.ExchangeId, "Clone stays the identity copy"); } [Fact] public void After_two_hops_the_correlation_id_is_the_immediate_parent_s_as_in_camel() { var root = new Exchange(new Message("x")); var first = root.CorrelatedCopy(); var second = first.CorrelatedCopy(); second.GetProperty(ExchangePropertyKeys.CorrelationId).Should().Be(first.ExchangeId); first.GetProperty(ExchangePropertyKeys.CorrelationId).Should().Be(root.ExchangeId, "the root stays reachable by walking the chain"); } // ── Hops that send a correlated copy ── [Theory] [InlineData("seda:corr-q")] [InlineData("vm:corr-q")] public async Task A_seda_or_vm_hop_sends_a_correlated_copy(string queue) { await using var ctx = NewContext(); Seen? origin = null; var captured = new ConcurrentQueue(); ctx.AddRoutes(r => { r.From("direct:in").RouteId("in").Process(ex => origin = Record(ex)).To(queue); r.From(queue).RouteId("worker").Process(ex => captured.Enqueue(Record(ex))); }); await ctx.Start(); using var producer = new ProducerTemplate(ctx); producer.Start(); await producer.SendAsync("direct:in", "payload"); await WaitUntil(() => !captured.IsEmpty, "the queued copy"); var copy = captured.Single(); copy.Id.Should().NotBe(origin!.Id); copy.Correlation.Should().Be(origin.Id); } [Theory] [InlineData(false)] [InlineData(true)] public async Task Multicast_branches_are_correlated_copies_and_the_original_keeps_its_own_id(bool parallel) { var (origin, captured, after) = await Run( r => { var multicast = r.Multicast().AggregationStrategy((a, b) => b); if (parallel) multicast.ParallelProcessing(); return multicast.To("direct:capture").To("direct:capture").End(); }, expected: 2); captured.Select(c => c.Id).Should().OnlyHaveUniqueItems().And.NotContain(origin.Id); captured.Should().OnlyContain(c => c.Correlation == origin.Id); after.ExchangeId.Should().Be(origin.Id); after.Properties.Should().NotContainKey(ExchangePropertyKeys.CorrelationId, "the merge does not hand the branch's correlation id to the original"); } [Theory] [InlineData(false)] [InlineData(true)] public async Task Recipient_list_copies_are_correlated(bool parallel) { var (origin, captured, _) = await Run( r => r.RecipientList(_ => ["direct:capture", "direct:capture"], parallelProcessing: parallel), expected: 2); captured.Select(c => c.Id).Should().OnlyHaveUniqueItems().And.NotContain(origin.Id); captured.Should().OnlyContain(c => c.Correlation == origin.Id); } [Theory] [InlineData(false)] [InlineData(true)] public async Task Scatter_gather_copies_are_correlated_and_the_original_keeps_its_own_correlation_id(bool parallel) { var (origin, captured, after) = await Run( r => r.Process(ex => ex.Properties[ExchangePropertyKeys.CorrelationId] = "upstream") .ScatterGather(sg => sg.Recipients("direct:capture", "direct:capture") .AggregationStrategy((a, b) => b).ParallelProcessing(parallel)), expected: 2); captured.Should().OnlyContain(c => c.Correlation == origin.Id && c.Id != origin.Id); after.GetProperty(ExchangePropertyKeys.CorrelationId).Should().Be("upstream"); } [Fact] public async Task An_enrich_resource_exchange_is_correlated() { var (origin, captured, after) = await Run(r => r.Enrich("direct:capture"), expected: 1); captured.Single().Id.Should().NotBe(origin.Id); captured.Single().Correlation.Should().Be(origin.Id); after.ExchangeId.Should().Be(origin.Id); } [Fact] public async Task An_on_completion_copy_is_correlated() { var (origin, captured, _) = await Run( r => { r.OnCompletion().To("direct:capture").EndOnCompletion(); return r; }, expected: 1); captured.Single().Id.Should().NotBe(origin.Id); captured.Single().Correlation.Should().Be(origin.Id); } [Fact] public async Task A_split_part_is_correlated_and_the_merge_leaves_the_original_s_correlation_alone() { var (origin, captured, after) = await Run( r => r.Split(_ => new object?[] { "a", "b" }).AggregationStrategy((a, b) => b).To("direct:capture").End(), expected: 2); captured.Should().OnlyContain(c => c.Correlation == origin.Id && c.Id != origin.Id); after.Properties.Should().NotContainKey(ExchangePropertyKeys.CorrelationId); } // ── Hops that send a copy with a new id and no correlation id ── [Fact] public async Task A_wire_tap_copy_has_a_new_id_and_no_correlation_id() { var (origin, captured, _) = await Run( r => r.Process(ex => ex.Properties[ExchangePropertyKeys.CorrelationId] = "upstream").WireTap("direct:capture"), expected: 1); captured.Single().Id.Should().NotBe(origin.Id); captured.Single().Correlation.Should().BeNull("Camel's wire tap removes the correlation id from its copy"); } [Fact] public async Task A_poll_enrich_exchange_has_a_new_id_and_no_correlation_id() { var (origin, captured, _) = await Run(r => r.PollEnrich("direct:capture"), expected: 1); captured.Single().Id.Should().NotBe(origin.Id); captured.Single().Correlation.Should().BeNull(); } // ── Hops that keep the id ── [Fact] public async Task A_direct_vm_hop_keeps_the_exchange_id_as_camel_s_direct() { var queue = "direct-vm:corr-dvm-" + Guid.NewGuid().ToString("N")[..8]; await using var ctx = NewContext(); Seen? origin = null; Seen? seen = null; ctx.AddRoutes(r => { r.From("direct:in").RouteId("in").Process(ex => origin = Record(ex)).To(queue); r.From(queue).RouteId("dvm").Process(ex => seen = Record(ex)); }); await ctx.Start(); using var producer = new ProducerTemplate(ctx); producer.Start(); await producer.SendAsync("direct:in", "payload"); seen!.Id.Should().Be(origin!.Id); } [Fact] public async Task A_loop_with_copy_keeps_the_exchange_id_as_camel_s_createCopy() { var (origin, captured, _) = await Run(r => r.Loop(2, copy: true).To("direct:capture").End(), expected: 2); captured.Should().OnlyContain(c => c.Id == origin.Id); } [Fact] public async Task A_threads_hand_off_keeps_the_exchange_id_as_camel_s_threads() { var (origin, captured, _) = await Run(r => r.Threads(2).To("direct:capture").End(), expected: 1); captured.Single().Id.Should().Be(origin.Id); } // ── What operators see ── [Fact] public async Task A_seda_hop_is_its_own_inflight_entry_in_its_own_route() { await using var ctx = NewContext(); using var held = new SemaphoreSlim(0); using var release = new SemaphoreSlim(0); ctx.AddRoutes(r => { r.From("direct:in").RouteId("origin-route").To("seda:corr-inflight") .Process(async (_, ct) => { held.Release(); await release.WaitAsync(ct); }); r.From("seda:corr-inflight").RouteId("seda-route") .Process(async (_, ct) => { held.Release(); await release.WaitAsync(ct); }); }); await ctx.Start(); using var producer = new ProducerTemplate(ctx); producer.Start(); var send = producer.SendAsync("direct:in", "payload"); (await held.WaitAsync(TimeSpan.FromSeconds(10))).Should().BeTrue(); (await held.WaitAsync(TimeSpan.FromSeconds(10))).Should().BeTrue(); try { var inflight = ctx.InflightRepository.Browse(); inflight.Select(e => e.RouteId).Should().BeEquivalentTo("origin-route", "seda-route"); inflight.Select(e => e.ExchangeId).Should().OnlyHaveUniqueItems(); } finally { release.Release(2); await send; } } [Fact] public async Task Across_a_seda_hop_the_span_parentage_is_unchanged_and_the_span_carries_the_correlation_id() { var prefix = "corr-trace-" + Guid.NewGuid().ToString("N")[..8]; using var probe = RouteTelemetryProbe.ForRouteIdPrefix(prefix); await using var ctx = NewContext(); Seen? origin = null; var done = new TaskCompletionSource(); ctx.AddRoutes(r => { r.From("direct:in").RouteId(prefix + "-in").Process(ex => origin = Record(ex)).To($"seda:{prefix}"); r.From($"seda:{prefix}").RouteId(prefix + "-worker").Process(_ => done.TrySetResult()); }); await ctx.Start(); using var producer = new ProducerTemplate(ctx); producer.Start(); using (var root = new Activity("corr-test-root").Start()) { await producer.SendAsync("direct:in", "payload"); await done.Task.WaitAsync(TimeSpan.FromSeconds(10)); } await WaitUntil(() => probe.Activities.Any(a => RouteTelemetryProbe.Tag(a, RouteTelemetryProbe.RouteIdTag) == prefix + "-worker"), "the worker's span"); var originSpans = probe.Activities.Where(a => RouteTelemetryProbe.Tag(a, RouteTelemetryProbe.RouteIdTag) == prefix + "-in").ToList(); var workerSpans = probe.Activities.Where(a => RouteTelemetryProbe.Tag(a, RouteTelemetryProbe.RouteIdTag) == prefix + "-worker").ToList(); originSpans.Should().NotBeEmpty(); // As before the correlated copy (checked on develop 2026-11-19): the seda worker carries no trace context over // the queue, so its route span is the root of a trace of its own. The copy's new id does not change that; the // correlation id tag is what joins it to the sender now. var workerRoute = workerSpans.Single(s => s.OperationName.StartsWith("route:", StringComparison.Ordinal)); workerRoute.ParentSpanId.Should().Be(default(ActivitySpanId)); workerRoute.TraceId.Should().NotBe(originSpans[0].TraceId); workerSpans.Should().Contain(s => RouteTelemetryProbe.Tag(s, "redb.correlation.id") == origin!.Id); } } Path: redb-route/tests/redb.Route.Tests/Core/DeadLetterErrorHandlerTests.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/DeadLetterErrorHandlerTests.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.ErrorHandling; using redb.Route.TestKit; namespace redb.Route.Tests.Core; /// /// The context's dead letter channel — Apache Camel's context-level errorHandler(deadLetterChannel(...)): every /// route sends to it a failure no OnException took, stamped with the CamelDeadLetter* headers, and the /// failure is handled; a failure an OnException took never reaches it; a lost dead letter lets the failure go on. /// public class DeadLetterErrorHandlerTests { private static readonly TimeSpan Wait = TimeSpan.FromSeconds(2); [Fact] public async Task AFailureNoOnExceptionTook_GoesToTheDeadLetterRoute_AndIsHandled() { await using var ctx = new RouteContext(); ctx.ErrorHandler = new DeadLetterErrorHandler(ctx, "mock://dlc-errors"); ctx.AddRoutes(r => r.From("direct://dlc-orders").Process(_ => throw new InvalidOperationException("boom"))); await ctx.Start(); var exchange = await Send(ctx, "direct://dlc-orders"); exchange.ExceptionHandled.Should().BeTrue("a dead letter channel takes the failure, as in Camel"); var dead = ctx.Mock("mock://dlc-errors"); await dead.ExpectBodies("x").AssertIsSatisfiedAsync(Wait); var headers = dead.ReceivedExchanges.Single().In.Headers; headers["CamelDeadLetterReason"].Should().Be("boom"); headers["CamelDeadLetterExceptionType"].Should().Be(typeof(InvalidOperationException).FullName); } [Fact] public async Task AFailureAnOnExceptionTook_NeverReachesIt() { await using var ctx = new RouteContext(); ctx.ErrorHandler = new DeadLetterErrorHandler(ctx, "mock://dlc-taken-errors"); ctx.AddRoutes(r => r .From("direct://dlc-taken") .OnException().Handled().End() .Process(_ => throw new InvalidOperationException("boom"))); await ctx.Start(); await Send(ctx, "direct://dlc-taken"); ctx.Mock("mock://dlc-taken-errors").ReceivedExchanges.Should().BeEmpty(); } [Fact] public async Task ALostDeadLetter_LetsTheFailureGoOn() { await using var ctx = new RouteContext(); ctx.ErrorHandler = new DeadLetterErrorHandler(ctx, "direct://dlc-nobody-listens"); ctx.AddRoutes(r => r.From("direct://dlc-lost").Process(_ => throw new InvalidOperationException("boom"))); await ctx.Start(); var exchange = await Send(ctx, "direct://dlc-lost"); exchange.ExceptionHandled.Should().BeFalse("the dead letter was not delivered, so the failure is not swallowed"); exchange.Exception.Should().BeOfType(); } 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; } } Path: redb-route/tests/redb.Route.Tests/Core/DefaultHeaderFilterStrategyTests.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/DefaultHeaderFilterStrategyTests.cs ---- using redb.Route.Core; namespace redb.Route.Tests.Core; /// /// : Apache Camel's DefaultHeaderFilterStrategy semantics. A list of /// names, a pattern and prefixes per direction; true drops a header; FilterOnMatch=false turns the /// configuration into a whitelist; null values, case and the two directions kept apart. /// public class DefaultHeaderFilterStrategyTests { private static readonly Exchange Exchange = new(new Message()); private static bool Out(DefaultHeaderFilterStrategy s, string name, object? value = null) => s.FilterOutgoing(name, value ?? "v", Exchange); private static bool In(DefaultHeaderFilterStrategy s, string name, object? value = null) => s.FilterIncoming(name, value ?? "v", Exchange); [Fact] public void Empty_DropsNothing() { var s = new DefaultHeaderFilterStrategy(); Out(s, "X-Corr").Should().BeFalse(); In(s, "X-Corr").Should().BeFalse(); } [Fact] public void Blacklist_DropsWhatMatches_ByName_Pattern_Prefix() { var s = new DefaultHeaderFilterStrategy { OutFilter = ["Authorization"], OutFilterPattern = "X-Secret-.*", OutFilterStartsWith = ["redb"], }; Out(s, "Authorization").Should().BeTrue(); Out(s, "X-Secret-Key").Should().BeTrue(); Out(s, "redbHttp.Method").Should().BeTrue(); Out(s, "X-Corr").Should().BeFalse(); } [Fact] public void Whitelist_KeepsOnlyWhatMatches() { var s = new DefaultHeaderFilterStrategy { OutFilter = ["Correlation-ID"], FilterOnMatch = false }; Out(s, "Correlation-ID").Should().BeFalse("listed: kept"); Out(s, "Authorization").Should().BeTrue("not listed: dropped"); Out(s, "X-Corr").Should().BeTrue(); } [Fact] public void Whitelist_WithNothingConfigured_DropsEverything() { var s = new DefaultHeaderFilterStrategy { FilterOnMatch = false }; Out(s, "X-Corr").Should().BeTrue(); In(s, "X-Corr").Should().BeTrue(); } [Fact] public void TheDirections_AreSeparate() { var s = new DefaultHeaderFilterStrategy { OutFilter = ["X-Out"], InFilter = ["X-In"] }; Out(s, "X-Out").Should().BeTrue(); Out(s, "X-In").Should().BeFalse("the incoming list does not filter outgoing headers"); In(s, "X-In").Should().BeTrue(); In(s, "X-Out").Should().BeFalse(); } [Fact] public void ThePattern_MatchesTheWholeName() { var s = new DefaultHeaderFilterStrategy { OutFilterPattern = "X-[A-Z]+" }; Out(s, "X-ABC").Should().BeTrue(); Out(s, "X-ABC-more").Should().BeFalse("a pattern is matched against the whole name, as in Camel"); Out(s, "prefix-X-ABC").Should().BeFalse(); } [Fact] public void ANullValue_IsDropped_UnlessAllowed() { var s = new DefaultHeaderFilterStrategy(); s.FilterOutgoing("X-Null", null, Exchange).Should().BeTrue(); s.AllowNullValues = true; s.FilterOutgoing("X-Null", null, Exchange).Should().BeFalse(); } [Fact] public void Names_IgnoreCase_ByDefault_AsInCamel() { var s = new DefaultHeaderFilterStrategy { OutFilter = ["Authorization"] }; Out(s, "authorization").Should().BeTrue(); Out(s, "AUTHORIZATION").Should().BeTrue(); s.CaseInsensitive = false; Out(s, "authorization").Should().BeFalse("exact when case-insensitivity is off"); } [Fact] public void LowerCase_DoesNotApplyToThePattern() { var s = new DefaultHeaderFilterStrategy { OutFilterPattern = "x-[a-z]+", LowerCase = true }; Out(s, "X-Trace").Should().BeFalse("the pattern is matched against the name as it is, as in Camel"); Out(s, "x-trace").Should().BeTrue(); } [Fact] public void LowerCase_AlsoMatchesTheLowerCasedName() { var s = new DefaultHeaderFilterStrategy { OutFilterStartsWith = ["x-"], LowerCase = true }; Out(s, "X-Trace").Should().BeTrue("'x-trace' starts with 'x-'"); } [Fact] public void ThePattern_FollowsTheProperty() { var s = new DefaultHeaderFilterStrategy { OutFilterPattern = "A" }; Out(s, "A").Should().BeTrue(); s.OutFilterPattern = "B"; Out(s, "A").Should().BeFalse("a changed pattern is compiled again"); Out(s, "B").Should().BeTrue(); } [Fact] public void Resolve_FindsTheRegisteredStrategy_AndRefusesAMissingOne() { var ctx = new RouteContext(); var strategy = new DefaultHeaderFilterStrategy(); ctx.AddToRegistry("onlyCorrelation", strategy); HeaderFilterStrategies.Resolve(ctx, "#onlyCorrelation", "http://x").Should().BeSameAs(strategy); HeaderFilterStrategies.Resolve(ctx, "onlyCorrelation", "http://x").Should().BeSameAs(strategy); HeaderFilterStrategies.Resolve(ctx, null, "http://x").Should().BeNull("no option: the transport's default"); var missing = () => HeaderFilterStrategies.Resolve(ctx, "#nope", "http://x"); missing.Should().Throw().WithMessage("*http://x*'#nope'*"); ctx.AddToRegistry("notAStrategy", "text"); var wrongType = () => HeaderFilterStrategies.Resolve(ctx, "#notAStrategy", "http://x"); wrongType.Should().Throw(); } } Path: redb-route/tests/redb.Route.Tests/Core/DefaultInflightRepositoryTests.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/DefaultInflightRepositoryTests.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using AwesomeAssertions; namespace redb.Route.Tests.Core; public class DefaultInflightRepositoryTests { private readonly DefaultInflightRepository _repo = new(); private static InflightExchange MakeEntry(string exchangeId = "ex-1", string routeId = "route-1") => new(exchangeId, routeId, DateTime.UtcNow, Environment.CurrentManagedThreadId, "kafka:orders"); [Fact] public void Register_AddsEntry() { _repo.Register(MakeEntry()); _repo.Count.Should().Be(1); } [Fact] public void Unregister_RemovesEntry() { _repo.Register(MakeEntry("ex-1")); _repo.Unregister("ex-1"); _repo.Count.Should().Be(0); } [Fact] public void Unregister_UnknownId_DoesNotThrow() { var act = () => _repo.Unregister("nonexistent"); act.Should().NotThrow(); } [Fact] public void Browse_ReturnsAllEntries() { _repo.Register(MakeEntry("ex-1", "route-1")); _repo.Register(MakeEntry("ex-2", "route-2")); _repo.Register(MakeEntry("ex-3", "route-1")); _repo.Browse().Should().HaveCount(3); } [Fact] public void Browse_ByRouteId_ReturnsFilteredEntries() { _repo.Register(MakeEntry("ex-1", "route-1")); _repo.Register(MakeEntry("ex-2", "route-2")); _repo.Register(MakeEntry("ex-3", "route-1")); _repo.Browse("route-1").Should().HaveCount(2); _repo.Browse("route-2").Should().HaveCount(1); _repo.Browse("route-3").Should().BeEmpty(); } [Fact] public void CountByRoute_ReturnsCorrectCount() { _repo.Register(MakeEntry("ex-1", "route-1")); _repo.Register(MakeEntry("ex-2", "route-1")); _repo.Register(MakeEntry("ex-3", "route-2")); _repo.CountByRoute("route-1").Should().Be(2); _repo.CountByRoute("route-2").Should().Be(1); _repo.CountByRoute("route-3").Should().Be(0); } [Fact] public void CountByRoute_AfterUnregister_Decrements() { _repo.Register(MakeEntry("ex-1", "route-1")); _repo.Register(MakeEntry("ex-2", "route-1")); _repo.Unregister("ex-1"); _repo.CountByRoute("route-1").Should().Be(1); } [Fact] public void CountByRoute_NeverGoesNegative() { _repo.Register(MakeEntry("ex-1", "route-1")); _repo.Unregister("ex-1"); _repo.Unregister("ex-1"); // double unregister _repo.CountByRoute("route-1").Should().Be(0); } [Fact] public void DuplicateRegister_IsIgnored() { _repo.Register(MakeEntry("ex-1", "route-1")); _repo.Register(MakeEntry("ex-1", "route-1")); // same id _repo.Count.Should().Be(1); _repo.CountByRoute("route-1").Should().Be(1); } [Fact] public async Task ConcurrentRegisterUnregister_IsThreadSafe() { const int count = 1000; var registerTasks = Enumerable.Range(0, count) .Select(i => Task.Run(() => _repo.Register(MakeEntry($"ex-{i}", "route-1")))); await Task.WhenAll(registerTasks); _repo.Count.Should().Be(count); _repo.CountByRoute("route-1").Should().Be(count); var unregisterTasks = Enumerable.Range(0, count) .Select(i => Task.Run(() => _repo.Unregister($"ex-{i}"))); await Task.WhenAll(unregisterTasks); _repo.Count.Should().Be(0); _repo.CountByRoute("route-1").Should().Be(0); } [Fact] public void Browse_ReturnsSnapshot_NotLiveReference() { _repo.Register(MakeEntry("ex-1")); var snapshot = _repo.Browse(); _repo.Register(MakeEntry("ex-2")); snapshot.Should().HaveCount(1); // snapshot unchanged _repo.Browse().Should().HaveCount(2); // new browse reflects change } } Path: redb-route/tests/redb.Route.Tests/Core/DefaultRouteIdTests.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/DefaultRouteIdTests.cs ---- using AwesomeAssertions; using redb.Route.Core; namespace redb.Route.Tests.Core; /// /// The id of a route that declared none. It used to be the sanitized endpoint URI, so every /// {RouteId} log line, metric tag and dashboard label carried a ://; now it is the /// scheme, the path and a deterministic UUID of the endpoint: readable, the same on every start and /// every node, and free of both URI separators and secrets. /// public class DefaultRouteIdTests { private static async Task IdOf(string fromUri) { await using var context = new RouteContext(); context.AddRoutes(r => r.From(fromUri).Process(_ => { })); await context.Start(); return context.Routes.Single().RouteId; } [Fact] public async Task The_scheme_and_path_lead_and_a_uuid_closes() { var id = await IdOf("direct://orders"); id.Should().StartWith("direct-orders-"); Guid.TryParse(id["direct-orders-".Length..], out _).Should().BeTrue("the tail is a UUID"); } [Fact] public async Task The_id_holds_nothing_a_dashboard_chokes_on() { var id = await IdOf("seda://orders/eu-west?size=10"); id.Should().StartWith("seda-orders-eu-west-"); id.Should().NotContainAny("/", ":", "?", "&", "=", " "); } [Fact] public async Task A_secret_in_the_uri_never_reaches_the_id() { var id = await IdOf("direct://svc?password=topsecret"); id.Should().Be("direct-svc-" + RouteIdFactory.Uuid5( RouteIdFactory.UrlNamespace, "direct://svc?password=topsecret")); id.Should().NotContain("topsecret", "the query is hashed, not printed"); id.Should().NotContain("****", "there is no masked leftover to print either"); } [Fact] public async Task The_same_endpoint_keeps_its_id_across_restarts() { var first = await IdOf("direct://stable"); var second = await IdOf("direct://stable"); // Metrics, checkpoints and control-bus commands address a route by this id: a restart, // another node or another process must produce the very same one. second.Should().Be(first); } [Fact] public void Endpoints_that_differ_only_in_a_parameter_get_different_ids() { var withOneSecret = RouteIdFactory.ForEndpoint(EndpointUriParser.Parse("sql://db?password=one")); var withAnother = RouteIdFactory.ForEndpoint(EndpointUriParser.Parse("sql://db?password=two")); // Sanitizing masked both to "sql://db?password=****" and the second route was refused as a // duplicate id although the URIs differ; the UUID sees the values the label never shows. withOneSecret.Should().NotBe(withAnother); } [Fact] public void Credentials_in_the_authority_are_dropped_from_the_readable_part() { var id = RouteIdFactory.ForEndpoint(EndpointUriParser.Parse("amqp://user:pw@localhost:5672/orders")); id.Should().StartWith("amqp-localhost-5672-orders-"); id.Should().NotContain("pw").And.NotContain("user"); } [Fact] public async Task A_long_path_is_cut_short_and_the_uuid_still_tells_routes_apart() { var shared = new string('a', 60); var first = await IdOf($"direct://{shared}-one"); var second = await IdOf($"direct://{shared}-two"); first.Length.Should().BeLessThan(90, "the readable part is capped, the UUID is not"); first.Should().NotBe(second); } [Fact] public async Task A_declared_route_id_is_left_alone() { await using var context = new RouteContext(); context.AddRoutes(r => r.From("direct://named").RouteId("orders-in").Process(_ => { })); await context.Start(); context.Routes.Single().RouteId.Should().Be("orders-in"); } [Fact] public void The_uuid_is_the_one_any_uuid_library_computes() { // RFC 4122 version 5 over the DNS namespace, the vector published with Python's uuid module: // proof that the id can be reproduced outside this code. RouteIdFactory.Uuid5(new Guid("6ba7b810-9dad-11d1-80b4-00c04fd430c8"), "python.org") .Should().Be(new Guid("886313e1-3b8a-5372-9b90-0c9aee199e5d")); } } Path: redb-route/tests/redb.Route.Tests/Core/DetachedErrorScopeTests.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/DetachedErrorScopeTests.cs ---- using redb.Route.Abstractions; using redb.Route.Aggregation; using redb.Route.Core; using redb.Route.Extensions; namespace redb.Route.Tests.Core; /// /// The bodies an EIP runs on a timer, after the exchange that fed it has left — a debounce flush, an aggregation group /// completed by its timeout, a resequencer batch released by its timer — run outside the route's error wrappers, as a /// detached .Threads() body does. They are wrapped by the route's error scope, so a failure there reaches the /// route's OnException (and the context's handlers), as Apache Camel's error handler covers an aggregation /// completed by timeout. A completion on the arriving exchange stays inside the wrappers and is handled once. /// public class DetachedErrorScopeTests { private static readonly TimeSpan Wait = TimeSpan.FromSeconds(5); [Fact] public async Task Debounce_FlushFailure_ReachesTheRoutesOnException() { var hits = 0; await using var ctx = new RouteContext(); ctx.AddRoutes(r => r .From("direct://detached-debounce") .OnException().Handled().Process(_ => Interlocked.Increment(ref hits)).End() .Debounce(_ => "k", TimeSpan.FromMilliseconds(20)) .Process(_ => throw new InvalidOperationException("boom")) .End()); await ctx.Start(); await Send(ctx, "direct://detached-debounce"); await WaitFor(() => Volatile.Read(ref hits) == 1); } [Fact] public async Task Aggregate_TimeoutCompletionFailure_ReachesTheRoutesOnException() { var hits = 0; await using var ctx = new RouteContext(); ctx.AddRoutes(r => r .From("direct://detached-aggregate") .OnException().Handled().Process(_ => Interlocked.Increment(ref hits)).End() .Aggregate("header.group", AggregationStrategies.UseLatest(), completionTimeout: TimeSpan.FromMilliseconds(50)) .Process(_ => throw new InvalidOperationException("boom")) .End()); await ctx.Start(); await Send(ctx, "direct://detached-aggregate", ("group", "g1")); await WaitFor(() => Volatile.Read(ref hits) == 1); } [Fact] public async Task Aggregate_CompletionOnTheArrivingExchange_IsHandledOnce() { var hits = 0; await using var ctx = new RouteContext(); ctx.AddRoutes(r => r .From("direct://detached-aggregate-inline") .OnException().Handled().Process(_ => Interlocked.Increment(ref hits)).End() .Aggregate("header.group", AggregationStrategies.UseLatest(), completionSize: 1) .Process(_ => throw new InvalidOperationException("boom")) .End()); await ctx.Start(); await Send(ctx, "direct://detached-aggregate-inline", ("group", "g1")); await Task.Delay(200); Volatile.Read(ref hits).Should().Be(1, "completed on the caller, inside the route's wrappers — not again detached"); } [Fact] public async Task Resequence_TimerReleaseFailure_ReachesTheRoutesOnException() { var hits = 0; await using var ctx = new RouteContext(); ctx.AddRoutes(r => r .From("direct://detached-resequence") .OnException().Handled().Process(_ => Interlocked.Increment(ref hits)).End() .Resequence(_ => 1, batchSize: 10, timeout: TimeSpan.FromMilliseconds(50)) .Process(_ => throw new InvalidOperationException("boom")) .End()); await ctx.Start(); await Send(ctx, "direct://detached-resequence"); await WaitFor(() => Volatile.Read(ref hits) == 1); } private static async Task Send(IRouteContext ctx, string uri, params (string Name, object? Value)[] headers) { var producer = ctx.GetEndpoint(uri).CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message { Body = "x" }); foreach (var (name, value) in headers) exchange.In.Headers[name] = value; try { await producer.Process(exchange); } catch (Exception ex) { exchange.Exception ??= ex; } } 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/DrainableConsumerTrackingTests.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/DrainableConsumerTrackingTests.cs ---- using System.Diagnostics; using redb.Route.Abstractions; using redb.Route.Components; using redb.Route.Processors; using redb.Route.Telemetry; using redb.Route.Tests.Telemetry; namespace redb.Route.Tests.Core; /// /// DrainableConsumer.ProcessWithTracking is the one place a polling consumer hands an exchange to the route. A /// failure that escapes the pipeline — a cancellation the consumer did not ask for, e.g. an HttpClient timeout through /// an error handler that rethrows it — lands on the exchange, so a consumer deciding on the outcome (delete after read, /// move on failure) sees a failed route instead of a clean one; the receive span, when given, is marked by the same /// rule as every transport; and only the consumer's own stop is passed on. /// public class DrainableConsumerTrackingTests { private sealed class Probe(IProcessor processor, IEndpoint endpoint) : global::redb.Route.Core.DrainableConsumer(processor) { protected override IEndpoint ConsumerEndpoint => endpoint; protected override string ConsumerName => "probe"; protected override Task RunAsync(CancellationToken pollCt, CancellationToken processingCt) => Task.CompletedTask; public Task Track(IExchange exchange, CancellationToken ct) => ProcessWithTracking(exchange, ct); public Task Track(IExchange exchange, TransportSpan span, CancellationToken ct) => ProcessWithTracking(exchange, span, ct); } private sealed class StubEndpoint(string uri) : IEndpoint { public EndpointUri Uri { get; } = global::redb.Route.Core.EndpointUriParser.Parse(uri); public IComponent Component { get; } = new TimerComponent(); public IProducer CreateProducer() => throw new NotSupportedException(); public IConsumer CreateConsumer(IProcessor processor) => throw new NotSupportedException(); public Task Start(CancellationToken ct = default) => Task.CompletedTask; public Task Stop(CancellationToken ct = default) => Task.CompletedTask; } private static (Probe Consumer, string Endpoint) Consumer(Func route) { var endpoint = $"probe://tracking-{Guid.NewGuid():N}"; return (new Probe(new DelegateProcessor(route), new StubEndpoint(endpoint)), endpoint); } private static TransportSpan Span(string endpoint) => RouteTelemetryExtensions.StartConsumerSpan(null, "probe receive", ActivityKind.Consumer, "messaging.system", "probe", endpoint, null, static (_, _) => null); [Fact] public async Task A_cancellation_escaping_the_route_lands_on_the_exchange() { var (consumer, _) = Consumer((_, _) => throw new TaskCanceledException("a call inside the route timed out")); var exchange = new global::redb.Route.Core.Exchange(new global::redb.Route.Core.Message("x")); await consumer.Track(exchange, CancellationToken.None); exchange.Exception.Should().BeOfType("the consumer decides on the outcome after this"); } [Fact] public async Task A_failure_escaping_the_route_marks_the_span() { var (consumer, endpoint) = Consumer((_, _) => throw new TaskCanceledException("timed out")); using var probe = RouteTelemetryProbe.ForEndpointContaining(endpoint); using (var span = Span(endpoint)) await consumer.Track(new global::redb.Route.Core.Exchange(new global::redb.Route.Core.Message("x")), span, CancellationToken.None); probe.Activities.Single().Status.Should().Be(ActivityStatusCode.Error); } [Fact] public async Task A_failure_the_route_left_on_the_exchange_marks_the_span() { var (consumer, endpoint) = Consumer((e, _) => { e.Exception = new InvalidOperationException("route failed"); return Task.CompletedTask; }); using var probe = RouteTelemetryProbe.ForEndpointContaining(endpoint); using (var span = Span(endpoint)) await consumer.Track(new global::redb.Route.Core.Exchange(new global::redb.Route.Core.Message("x")), span, CancellationToken.None); probe.Activities.Single().Status.Should().Be(ActivityStatusCode.Error); } [Fact] public async Task A_handled_failure_and_a_clean_route_leave_the_span_unmarked() { var (consumer, endpoint) = Consumer((e, _) => { e.Exception = new InvalidOperationException("handled"); e.ExceptionHandled = true; return Task.CompletedTask; }); using var probe = RouteTelemetryProbe.ForEndpointContaining(endpoint); using (var span = Span(endpoint)) await consumer.Track(new global::redb.Route.Core.Exchange(new global::redb.Route.Core.Message("x")), span, CancellationToken.None); probe.Activities.Single().Status.Should().Be(ActivityStatusCode.Unset); } [Fact] public async Task The_consumers_own_stop_is_passed_on_and_is_not_a_failure() { using var stop = new CancellationTokenSource(); var (consumer, endpoint) = Consumer(async (_, ct) => { await stop.CancelAsync(); ct.ThrowIfCancellationRequested(); }); using var probe = RouteTelemetryProbe.ForEndpointContaining(endpoint); using (var span = Span(endpoint)) { var act = () => consumer.Track(new global::redb.Route.Core.Exchange(new global::redb.Route.Core.Message("x")), span, stop.Token); await act.Should().ThrowAsync(); } probe.Activities.Single().Status.Should().Be(ActivityStatusCode.Unset); } } Path: redb-route/tests/redb.Route.Tests/Core/DynamicValueTests.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/DynamicValueTests.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using AwesomeAssertions; namespace redb.Route.Tests.Core; public class DynamicValueTests { [Fact] public void FromStatic_ResolvesConstant() { var dv = DynamicValue.FromStatic("hello"); dv.IsDynamic.Should().BeFalse(); dv.Resolve(new Exchange()).Should().Be("hello"); } [Fact] public void FromExpression_ResolvesPerMessage() { var dv = DynamicValue.FromExpression(ex => ex.In.GetHeader("region")); var exchange = new Exchange(new Message()); exchange.In.Headers["region"] = "us-east"; dv.IsDynamic.Should().BeTrue(); dv.Resolve(exchange).Should().Be("us-east"); } [Fact] public void ImplicitConversion_CreatesStatic() { DynamicValue dv = 42; dv.IsDynamic.Should().BeFalse(); dv.Resolve(new Exchange()).Should().Be(42); } [Fact] public void FromExpression_NullResolver_Throws() { var act = () => DynamicValue.FromExpression((Func)null!); act.Should().Throw(); } [Fact] public void ToString_Static_ReturnsValue() { var dv = DynamicValue.FromStatic("test"); dv.ToString().Should().Be("test"); } [Fact] public void ToString_Dynamic_ReturnsPlaceholder() { var dv = DynamicValue.FromExpression(_ => "x"); dv.ToString().Should().Be("${expression}"); } [Fact] public void FromStatic_NullValue_ReturnsNull() { var dv = DynamicValue.FromStatic(null!); dv.Resolve(new Exchange()).Should().BeNull(); } [Fact] public void DynamicInt_ResolvesCorrectly() { var dv = DynamicValue.FromExpression(ex => ex.In.GetHeader("ttl")); var exchange = new Exchange(new Message()); exchange.In.Headers["ttl"] = 60; dv.Resolve(exchange).Should().Be(60); } } Path: redb-route/tests/redb.Route.Tests/Core/EndpointOptionsBindingTests.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/EndpointOptionsBindingTests.cs ---- using redb.Route.Core; using AwesomeAssertions; namespace redb.Route.Tests.Core; // Test options class for binding tests public class TestEndpointOptions : EndpointOptions { public string? Host { get; set; } public int Port { get; set; } = 5672; public bool Durable { get; set; } = true; public DynamicValue? Key { get; set; } public DynamicValue? Ttl { get; set; } public override void Validate() { if (string.IsNullOrEmpty(Host)) throw new InvalidOperationException("Host is required"); } } [LenientProperties] public class LenientTestEndpointOptions : TestEndpointOptions; public class EndpointOptionsBindingTests { [Fact] public void BindFromUri_MapsStringProperty() { var opts = new TestEndpointOptions(); opts.BindFromUri(new Dictionary { ["host"] = "rabbit1" }); opts.Host.Should().Be("rabbit1"); } [Fact] public void BindFromUri_MapsIntProperty() { var opts = new TestEndpointOptions(); opts.BindFromUri(new Dictionary { ["port"] = "9999" }); opts.Port.Should().Be(9999); } [Fact] public void BindFromUri_MapsBoolProperty() { var opts = new TestEndpointOptions(); opts.BindFromUri(new Dictionary { ["durable"] = "false" }); opts.Durable.Should().BeFalse(); } [Fact] public void BindFromUri_IsCaseInsensitive() { var opts = new TestEndpointOptions(); opts.BindFromUri(new Dictionary { ["HOST"] = "server" }); opts.Host.Should().Be("server"); } [Fact] public void BindFromUri_UnmappedParams_GoToUnmapped() { var opts = new LenientTestEndpointOptions(); // strict types refuse unknown names opts.BindFromUri(new Dictionary { ["host"] = "server", ["unknownParam"] = "value" }); opts.Host.Should().Be("server"); opts.UnmappedParameters.Should().ContainKey("unknownParam"); opts.UnmappedParameters["unknownParam"].Should().Be("value"); } [Fact] public void BindFromUri_StaticDynamicValue_Wraps() { var opts = new TestEndpointOptions(); opts.BindFromUri(new Dictionary { ["key"] = "static-key" }); opts.Key.Should().NotBeNull(); opts.Key!.Value.IsDynamic.Should().BeFalse(); opts.Key!.Value.Resolve(new Exchange()).Should().Be("static-key"); } [Fact] public void BindFromUri_EmptyParams_NoOp() { var opts = new TestEndpointOptions(); opts.BindFromUri(new Dictionary()); opts.Host.Should().BeNull(); // default opts.Port.Should().Be(5672); // default } [Fact] public void Validate_MissingRequired_Throws() { var opts = new TestEndpointOptions(); var act = () => opts.Validate(); act.Should().Throw().WithMessage("*Host*"); } [Fact] public void Validate_WithHost_Passes() { var opts = new TestEndpointOptions(); opts.Host = "localhost"; var act = () => opts.Validate(); act.Should().NotThrow(); } } Path: redb-route/tests/redb.Route.Tests/Core/EndpointOptionsInvalidValueTests.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/EndpointOptionsInvalidValueTests.cs ---- using AwesomeAssertions; using redb.Route.Core; namespace redb.Route.Tests.Core; /// /// A known option whose value does not convert to the option's type is an error at binding, for /// every connector: the name is right, the value is wrong — the most common typo — and the option /// must not quietly keep its default. Unknown names are a different question (the connector's /// strictness) and stay among the unmapped parameters. /// public class EndpointOptionsInvalidValueTests { public enum Delivery { Push, Poll } [Flags] public enum Rights { None = 0, Read = 1, Write = 2 } public sealed class Probe : EndpointOptions { public int Port { get; set; } = 5672; public bool Durable { get; set; } = true; public long? MaxBytes { get; set; } public double Ratio { get; set; } public TimeSpan Timeout { get; set; } = TimeSpan.FromSeconds(30); public Delivery Mode { get; set; } public Rights Access { get; set; } public DynamicValue? Ttl { get; set; } [Sensitive] public int? Pin { get; set; } public override void Validate() { } } /// A connector that adds its own hint to the core refusal. public sealed class HintedProbe : EndpointOptions { public Delivery Mode { get; set; } protected override string? OptionValueHint(string optionName) => optionName == nameof(Mode) ? "Push delivers as it arrives, Poll on a schedule." : null; public override void Validate() { } } private static Action Bind(EndpointOptions options, string key, string value) => () => options.BindFromUri(new Dictionary { [key] = value }); [Theory] [InlineData("port", "abc", "*'port=abc'*port*whole number*")] [InlineData("port", "99999999999", "*'port=99999999999'*")] [InlineData("durable", "yes", "*'durable=yes'*true or false*")] [InlineData("maxBytes", "", "*'maxBytes='*whole number*")] [InlineData("ratio", "1,5", "*'ratio=1,5'*number*")] [InlineData("timeout", "30s", "*'timeout=30s'*time span*")] [InlineData("mode", "pul", "*'mode=pul'*mode=push*mode=poll*")] [InlineData("ttl", "soon", "*'ttl=soon'*whole number*")] public void An_unconvertible_value_of_a_known_option_is_refused_with_what_it_takes(string key, string value, string message) { var act = Bind(new Probe(), key, value); act.Should().Throw().WithMessage(message); } [Fact] public void A_number_that_names_no_enum_member_is_refused() { var act = Bind(new Probe(), "mode", "7"); act.Should().Throw().WithMessage("*'mode=7'*mode=push*"); } [Fact] public void Flags_combinations_still_bind() { var probe = new Probe(); Bind(probe, "access", "Read, Write")(); probe.Access.Should().Be(Rights.Read | Rights.Write); } [Fact] public void An_expression_in_a_plain_option_is_refused_and_told_where_expressions_go() { var act = Bind(new Probe(), "port", "${header.port}"); act.Should().Throw().WithMessage("*does not accept ${...} expressions*"); } [Fact] public void An_expression_in_a_dynamic_option_still_binds() { var probe = new Probe(); Bind(probe, "ttl", "${header.ttl}")(); probe.Ttl!.Value.IsDynamic.Should().BeTrue(); } [Fact] public void The_value_of_a_sensitive_option_never_reaches_the_message() { var act = Bind(new Probe(), "pin", "12x4"); act.Should().Throw().Which.Message.Should().NotContain("12x4").And.Contain("pin"); } [Fact] public void A_connector_adds_its_own_hint() { var act = Bind(new HintedProbe(), "mode", "pul"); act.Should().Throw().WithMessage("*mode=push*Poll on a schedule*"); } // ── Unknown names: strict unless the options type declares itself lenient ── [LenientProperties] public sealed class LenientProbe : EndpointOptions { public int Port { get; set; } public override void Validate() { } } public sealed class RenamedProbe : EndpointOptions { public bool Durable { get; set; } protected override string? UnknownParameterHint(string name) => name == "streamAutoAck" ? "'streamAutoAck' is gone, use 'durable'." : null; public override void Validate() { } } [Fact] public void An_unknown_name_is_refused_with_the_nearest_option() { var act = Bind(new Probe(), "prot", "abc"); act.Should().Throw().WithMessage("'prot' is not an option of the Probe endpoint. Did you mean 'port'?*"); } [Fact] public void Every_unknown_name_is_named_by_name_only() { var act = () => new Probe().BindFromUri(new Dictionary { ["prot"] = "s3cret", ["zzz"] = "s3cret" }); act.Should().Throw() .WithMessage("*'prot'*'zzz' is not an option of the Probe endpoint.*") .Which.Message.Should().NotContain("s3cret", "the value may be a secret"); } [Fact] public void A_connector_explains_a_name_it_used_to_take() { var act = Bind(new RenamedProbe(), "streamAutoAck", "false"); act.Should().Throw().WithMessage("*'streamAutoAck' is gone, use 'durable'.*"); } [Fact] public void A_lenient_options_type_keeps_unknown_names_for_the_connector() { var probe = new LenientProbe(); Bind(probe, "param.id", "7")(); probe.UnmappedParameters.Should().ContainKey("param.id"); EndpointOptions.IsLenient(typeof(LenientProbe)).Should().BeTrue(); EndpointOptions.IsLenient(typeof(Probe)).Should().BeFalse(); } [Fact] public void A_lenient_options_type_still_refuses_a_bad_value_of_a_known_option() { var act = Bind(new LenientProbe(), "port", "abc"); act.Should().Throw().WithMessage("*'port=abc'*"); } } Path: redb-route/tests/redb.Route.Tests/Core/EndpointRoleTests.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/EndpointRoleTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Tests.Core; /// /// An option that only one side of an endpoint reads is declared so on its property ([EndpointRole], Camel's /// @UriParam(label = "producer"/"consumer")): the engine refuses it on the other side by the declaration, and /// tooling reads the same declaration by reflection. /// public class EndpointRoleTests { public sealed class Probe : EndpointOptions { [EndpointRole(EndpointRole.Producer)] public string? Password { get; set; } [EndpointRole(EndpointRole.Consumer)] public string? InboundRealm { get; set; } public int Timeout { get; set; } public override void Validate() { } } private static EndpointUri Uri(string query) => EndpointUriParser.Parse("probe://x?" + query); [Fact] public void The_role_of_an_option_is_read_from_its_declaration() { EndpointOptions.RoleOf(typeof(Probe).GetProperty(nameof(Probe.Password))!).Should().Be(EndpointRole.Producer); EndpointOptions.RoleOf(typeof(Probe).GetProperty(nameof(Probe.InboundRealm))!).Should().Be(EndpointRole.Consumer); EndpointOptions.RoleOf(typeof(Probe).GetProperty(nameof(Probe.Timeout))!).Should().BeNull("an option both sides read has no role"); } [Fact] public void A_consumer_finds_the_producer_options_its_uri_wrote_as_written() { var written = EndpointOptions.WrittenForOtherRole(typeof(Probe), Uri("PASSWORD=x&timeout=5&inboundRealm=r"), EndpointRole.Consumer); written.Should().Equal("PASSWORD"); } [Fact] public void A_producer_finds_the_consumer_options_its_uri_wrote() { var written = EndpointOptions.WrittenForOtherRole(typeof(Probe), Uri("password=x&inboundRealm=r"), EndpointRole.Producer); written.Should().Equal("inboundRealm"); } } Path: redb-route/tests/redb.Route.Tests/Core/EndpointSidesTests.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/EndpointSidesTests.cs ---- using redb.Route.Abstractions; using redb.Route.Components; using redb.Route.Components.Bean; using redb.Route.Core; using redb.Route.Validation; using redb.Route.Xslt; namespace redb.Route.Tests.Core; /// /// A component declares the only side it has with [EndpointRole] on its class (Apache Camel's /// producerOnly / consumerOnly); the context refuses the missing side in one message. /// public sealed class EndpointSidesTests { [Fact] public void The_core_components_declare_their_only_side() { EndpointSides.Of(new LogComponent()).Should().Be(EndpointRole.Producer); EndpointSides.Of(new BeanComponent()).Should().Be(EndpointRole.Producer); EndpointSides.Of(new XsltComponent()).Should().Be(EndpointRole.Producer); EndpointSides.Of(new ValidatorComponent()).Should().Be(EndpointRole.Producer); EndpointSides.Of(new TimerComponent()).Should().Be(EndpointRole.Consumer); EndpointSides.Of(new DirectComponent()).Should().BeNull("direct has both sides"); EndpointSides.Of(new SedaComponent()).Should().BeNull(); } [Fact] public void The_message_names_the_scheme_its_missing_side_and_the_hint() { EndpointSides.MissingSide("smtp", EndpointRole.Producer, "Use imap: or pop3: to receive mail.") .Should().Be("smtp has no consumer side: a route cannot start from it (smtp is producer-only). " + "Use imap: or pop3: to receive mail."); EndpointSides.MissingSide("timer", EndpointRole.Consumer, null) .Should().Be("timer has no producer side: a route cannot send to it (timer is consumer-only)."); } [Fact] public async Task A_route_from_a_producer_only_scheme_is_refused_at_start() { await using var ctx = new RouteContext(); ctx.AddRoutes(r => r.From("log:x").To("mock:out")); var act = () => ctx.Start(); (await act.Should().ThrowAsync()).Which.Message.Should() .StartWith("log has no consumer side: a route cannot start from it (log is producer-only)."); } [Fact] public async Task A_static_target_on_a_consumer_only_scheme_fails_the_route_build() { await using var ctx = new RouteContext(); ctx.AddRoutes(r => r.From("direct:in") .Choice() .When(_ => false, branch => branch.To("timer:t")) .EndChoice()); var act = () => ctx.Start(); (await act.Should().ThrowAsync()).Which.Message.Should() .StartWith("timer has no producer side: a route cannot send to it (timer is consumer-only)."); } [Fact] public async Task A_dynamic_target_on_a_consumer_only_scheme_is_refused_on_the_exchange() { await using var ctx = new RouteContext(); ctx.AddRoutes(r => r.From("direct:in").ToD("timer:t")); await ctx.Start(); var template = new ProducerTemplate(ctx); template.Start(); var exchange = new Exchange(new Message("m")); Exception? thrown = null; try { await template.SendAsync("direct:in", exchange); } catch (Exception ex) { thrown = ex; } (thrown ?? exchange.Exception).Should().BeOfType().Which.Message.Should() .StartWith("timer has no producer side: a route cannot send to it (timer is consumer-only)."); } [Fact] public async Task A_producer_template_send_to_a_consumer_only_scheme_is_refused() { await using var ctx = new RouteContext(); await ctx.Start(); var template = new ProducerTemplate(ctx); template.Start(); var act = () => template.SendAsync("timer:t", "m"); (await act.Should().ThrowAsync()).Which.Message.Should() .StartWith("timer has no producer side"); } [Fact] public async Task A_consumer_template_receive_from_a_producer_only_scheme_is_refused() { await using var ctx = new RouteContext(); await ctx.Start(); var template = new ConsumerTemplate(ctx); template.Start(); var act = () => template.Receive("log:x", TimeSpan.FromMilliseconds(100)); (await act.Should().ThrowAsync()).Which.Message.Should() .StartWith("log has no consumer side"); } [Fact] public void A_component_with_both_sides_is_not_refused() { var endpoint = new DirectComponent().CreateEndpoint(EndpointUriParser.Parse("direct:a")); var act = () => { EndpointSides.Refuse(endpoint, EndpointRole.Consumer); EndpointSides.Refuse(endpoint, EndpointRole.Producer); }; act.Should().NotThrow(); } } Path: redb-route/tests/redb.Route.Tests/Core/EndpointSupervisionTests.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/EndpointSupervisionTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Configuration; using redb.Route.Core; namespace redb.Route.Tests.Core; /// /// How connection supervisors feed an endpoint (): health as the worst of the /// supervisors and the transport's own condition, errors and reconnects counted; and how /// reconnects a lost connection on the next send. /// public sealed class EndpointSupervisionTests : IAsyncLifetime { private RouteContext? _context; public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { if (_context is not null) await _context.DisposeAsync(); } private SupervisedEndpoint Endpoint(ReconnectOptions? reconnect = null) { _context = new RouteContext(options: new RouteEngineOptions { Reconnect = reconnect ?? new ReconnectOptions() }); _context.AddComponent(new SupervisedComponent()); return (SupervisedEndpoint)_context.GetEndpoint("sup://broker"); } [Fact] public void A_lost_connection_turns_the_endpoint_Warning_then_Critical_and_Healthy_again_once_restored() { var endpoint = Endpoint(); var worker = endpoint.Supervise("sup:broker worker 1", null); endpoint.HealthStatus.Should().Be(EndpointHealthStatus.Healthy); worker.Lost(new IOException("connection broken")); endpoint.HealthStatus.Should().Be(EndpointHealthStatus.Warning); endpoint.HealthReason.Should().Contain("sup:broker worker 1"); worker.Failed(new IOException("connect refused")); endpoint.HealthStatus.Should().Be(EndpointHealthStatus.Critical); worker.Restored(); endpoint.HealthStatus.Should().Be(EndpointHealthStatus.Healthy); endpoint.Reconnects.Should().Be(1); } [Fact] public void The_worst_of_the_supervisors_and_the_transport_condition_wins() { var endpoint = Endpoint(); var first = endpoint.Supervise("worker 1", null); var second = endpoint.Supervise("worker 2", null); first.Lost(new IOException("blip")); second.Lost(new IOException("down")); second.Failed(new IOException("refused")); endpoint.HealthStatus.Should().Be(EndpointHealthStatus.Critical); endpoint.HealthReason.Should().Contain("worker 2"); second.Restored(); endpoint.HealthStatus.Should().Be(EndpointHealthStatus.Warning); endpoint.HealthReason.Should().Contain("worker 1"); endpoint.Condition = (EndpointHealthStatus.Critical, "transport says no"); endpoint.HealthStatus.Should().Be(EndpointHealthStatus.Critical); endpoint.HealthReason.Should().Be("transport says no"); } [Fact] public void A_loss_does_not_raise_the_error_rate_but_a_failed_message_still_does() { var endpoint = Endpoint(); var worker = endpoint.Supervise("worker 1", null); endpoint.RecordMessageIn(); worker.Lost(new IOException("broken")); worker.Failed(new IOException("refused")); worker.Restored(); endpoint.HealthStatus.Should().Be(EndpointHealthStatus.Healthy, "the connection is back and no message failed"); endpoint.RecordError(new InvalidOperationException("the route failed on a message")); endpoint.Errors.Should().Be(1); endpoint.HealthStatus.Should().Be(EndpointHealthStatus.Critical, "1 failed message of 1 is a high error rate"); } [Fact] public void A_removed_supervisor_no_longer_counts() { var endpoint = Endpoint(); var worker = endpoint.Supervise("worker 1", null); worker.Lost(new IOException("down")); worker.Failed(new IOException("refused")); endpoint.Unsupervise(worker); endpoint.HealthReason.Should().NotContain("worker 1"); } [Fact] public void A_loss_shows_masked_in_the_health_reason_not_in_errors_and_reset_clears_reconnects() { var endpoint = Endpoint(); var worker = endpoint.Supervise("worker 1", null); worker.Lost(new IOException("connect to amqp://user:s3cret@host failed")); endpoint.Errors.Should().Be(0, "a supervised loss is not a failed message"); endpoint.HealthReason.Should().Contain("connect to").And.NotContain("s3cret"); worker.LastFailure.Should().NotContain("s3cret"); worker.Restored(); endpoint.Reconnects.Should().Be(1); endpoint.ResetStatistics(); endpoint.Reconnects.Should().Be(0); } [Fact] public void The_context_reconnect_options_reach_the_supervisor() { var endpoint = Endpoint(new ReconnectOptions { Delay = TimeSpan.FromSeconds(5), MaxDelay = TimeSpan.FromMinutes(1) }); var worker = endpoint.Supervise("worker 1", null); worker.Lost(new IOException("down")); worker.DueIn.Should().BeGreaterThan(TimeSpan.FromSeconds(4)); } [Fact] public void Invalid_context_reconnect_options_stop_the_context_from_being_built() { FluentActions.Invoking(() => new RouteContext(options: new RouteEngineOptions { Reconnect = new ReconnectOptions { WarningPeriod = TimeSpan.FromSeconds(-1) }, })) .Should().Throw().WithMessage("Reconnect.WarningPeriod*"); } // ── ConnectableProducer ── [Fact] public async Task A_producer_that_never_loses_its_connection_sends_as_before() { var endpoint = Endpoint(); var producer = new FlakyProducer(endpoint); await producer.Start(); await producer.Process(null!); await producer.Process(null!); producer.Connects.Should().Be(1); endpoint.HealthStatus.Should().Be(EndpointHealthStatus.Healthy); } [Fact] public async Task While_the_next_attempt_is_not_due_a_send_fails_at_once_saying_when_it_is() { var endpoint = Endpoint(new ReconnectOptions { Delay = TimeSpan.FromMinutes(5), MaxDelay = TimeSpan.FromMinutes(5) }); var producer = new FlakyProducer(endpoint); await producer.Start(); producer.Lose(new IOException("MQRC_CONNECTION_BROKEN")); producer.Lose(new IOException("MQRC_CONNECTION_BROKEN")); producer.Losses.Should().Be(1, "what waits on the connection is failed once per loss"); var failure = await FluentActions.Awaiting(() => producer.Process(null!)).Should() .ThrowAsync(); failure.Which.Message.Should().Contain("next reconnect attempt is due in").And.Contain("MQRC_CONNECTION_BROKEN"); producer.Connects.Should().Be(1); endpoint.HealthStatus.Should().Be(EndpointHealthStatus.Warning); } [Fact] public async Task Once_due_a_send_reconnects_a_failed_attempt_goes_Critical_and_the_next_one_restores() { var endpoint = Endpoint(new ReconnectOptions { Delay = TimeSpan.FromMilliseconds(1), MaxDelay = TimeSpan.FromMilliseconds(1), }); var producer = new FlakyProducer(endpoint); await producer.Start(); producer.Lose(new IOException("broken")); producer.FailConnect = new IOException("refused"); await Task.Delay(20); await FluentActions.Awaiting(() => producer.Process(null!)).Should().ThrowAsync().WithMessage("refused"); endpoint.HealthStatus.Should().Be(EndpointHealthStatus.Critical); producer.FailConnect = null; await Task.Delay(20); await producer.Process(null!); producer.Connects.Should().Be(3); producer.Disconnects.Should().Be(3, "each attempt closes what is left first, a failed one also closes after itself"); endpoint.HealthStatus.Should().NotBe(EndpointHealthStatus.Critical); endpoint.Reconnects.Should().Be(1); } [Fact] public async Task Concurrent_sends_share_one_reconnect_attempt() { var endpoint = Endpoint(new ReconnectOptions { Delay = TimeSpan.FromMilliseconds(1), MaxDelay = TimeSpan.FromMilliseconds(1), }); var producer = new FlakyProducer(endpoint); await producer.Start(); producer.Lose(new IOException("broken")); await Task.Delay(20); var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); producer.Gate = gate.Task; var sends = Enumerable.Range(0, 5).Select(_ => Task.Run(() => producer.Process(null!))).ToArray(); await Task.Delay(50); gate.SetResult(); await Task.WhenAll(sends); producer.Connects.Should().Be(2, "one cold start and one reconnect for all five sends"); } [Fact] public async Task A_stop_during_a_reconnect_waits_for_it_and_closes_what_it_opened() { var endpoint = Endpoint(new ReconnectOptions { Delay = TimeSpan.FromMilliseconds(1), MaxDelay = TimeSpan.FromMilliseconds(1), }); var producer = new FlakyProducer(endpoint); await producer.Start(); producer.Lose(new IOException("broken")); await Task.Delay(20); var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); producer.Gate = gate.Task; var send = Task.Run(() => producer.Process(null!)); (await Until(() => producer.Connects == 2)).Should().BeTrue("the send is inside its reconnect"); var stop = producer.Stop(); await Task.Delay(100); stop.IsCompleted.Should().BeFalse("the stop waits for the reconnect in flight"); gate.SetResult(); await stop.WaitAsync(TimeSpan.FromSeconds(5)); await send.WaitAsync(TimeSpan.FromSeconds(5)); producer.Open.Should().Be(0, "the connection the reconnect opened is closed by the stop"); await FluentActions.Awaiting(() => producer.Process(null!)).Should().ThrowAsync(); } [Fact] public async Task A_send_that_waited_behind_a_stop_does_not_reconnect() { var endpoint = Endpoint(new ReconnectOptions { Delay = TimeSpan.FromMilliseconds(1), MaxDelay = TimeSpan.FromMilliseconds(1), }); var producer = new FlakyProducer(endpoint); await producer.Start(); producer.Lose(new IOException("broken")); await Task.Delay(20); var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); producer.Gate = gate.Task; var first = Task.Run(() => producer.Process(null!)); (await Until(() => producer.Connects == 2)).Should().BeTrue(); var second = Task.Run(() => producer.Process(null!)); // waits for the reconnect lock await Task.Delay(50); var stop = producer.Stop(); gate.SetResult(); await stop.WaitAsync(TimeSpan.FromSeconds(5)); await first.WaitAsync(TimeSpan.FromSeconds(5)); await FluentActions.Awaiting(() => second.WaitAsync(TimeSpan.FromSeconds(5))).Should() .ThrowAsync().WithMessage("*not been started*"); producer.Connects.Should().Be(2, "no reconnect started behind the stop"); producer.Open.Should().Be(0); } private static async Task Until(Func done) { for (var i = 0; i < 200 && !done(); i++) await Task.Delay(25); return done(); } [Fact] public async Task A_stopped_producer_leaves_the_endpoint_health() { var endpoint = Endpoint(new ReconnectOptions { Delay = TimeSpan.FromMinutes(5), MaxDelay = TimeSpan.FromMinutes(5) }); var producer = new FlakyProducer(endpoint); await producer.Start(); producer.Lose(new IOException("broken")); endpoint.HealthStatus.Should().Be(EndpointHealthStatus.Warning); await producer.Stop(); endpoint.HealthReason.Should().NotContain("sup:flaky"); } private sealed class FlakyProducer(IEndpoint endpoint) : ConnectableProducer { public int Connects; public int Disconnects; public int Losses; public Exception? FailConnect; public Task? Gate; public int Open; // connections opened and not closed yet protected override IEndpoint ProducerEndpoint => endpoint; protected override string ProducerName => "sup:flaky"; protected override async Task ConnectAsync(CancellationToken ct) { Interlocked.Increment(ref Connects); if (Gate is { } gate) await gate; if (FailConnect is { } failure) throw failure; Interlocked.Exchange(ref Open, 1); } protected override Task DisconnectAsync(CancellationToken ct) { Interlocked.Increment(ref Disconnects); Interlocked.Exchange(ref Open, 0); return Task.CompletedTask; } protected override void OnConnectionLost(Exception cause) => Interlocked.Increment(ref Losses); public void Lose(Exception cause) => MarkConnectionLost(cause); public override async Task Process(IExchange exchange, CancellationToken ct = default) { EnsureStarted(); await EnsureConnectedAsync(ct); } } private sealed class SupervisedComponent : ComponentBase { public override string Scheme => "sup"; public override IEndpoint CreateEndpoint(EndpointUri uri) => new SupervisedEndpoint(uri, this); } private sealed class SupervisedOptions : EndpointOptions { public override void Validate() { } } private sealed class SupervisedEndpoint(EndpointUri uri, IComponent component) : EndpointBase(uri, component, new SupervisedOptions()) { public (EndpointHealthStatus Status, string Reason)? Condition { get; set; } protected override (EndpointHealthStatus Status, string Reason)? TransportCondition => Condition; public override IProducer CreateProducer() => throw new NotSupportedException(); public override IConsumer CreateConsumer(IProcessor processor) => throw new NotSupportedException(); } } Path: redb-route/tests/redb.Route.Tests/Core/ExceptionPolicyTests.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/ExceptionPolicyTests.cs ---- using System.Data.Common; using System.Net.Sockets; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Tests.Core; /// /// Which OnException takes a failure — Apache Camel's exception policy (DefaultExceptionPolicyStrategy): /// the failure is walked from its innermost cause up to the thrown exception; a handler of exactly that type wins at /// once; otherwise the handler whose type is the nearest ancestor does, wherever it is declared — on the route, on its /// builder, in a route configuration; the route's own handler wins a tie; a later handler of the same type replaces the /// earlier one; a handler whose OnWhen is false is passed over. /// public class ExceptionPolicyTests { [Fact] public async Task TheNearestType_Wins_WhateverTheDeclarationOrder() { var taken = new List(); await using var ctx = new RouteContext(); ctx.AddRoutes(r => { // The wide one first: it used to sit innermost and take everything. r.OnException().Handled().Process(_ => Take(taken, "exception")); r.OnException().Handled().Process(_ => Take(taken, "io")); r.OnException().Handled().Process(_ => Take(taken, "file")); r.From("direct://policy-nearest").Process(Throw); }); await ctx.Start(); await Send(ctx, "direct://policy-nearest", new FileNotFoundException("f")); await Send(ctx, "direct://policy-nearest", new EndOfStreamException("e")); await Send(ctx, "direct://policy-nearest", new InvalidOperationException("o")); taken.Should().Equal("file", "io", "exception"); } [Fact] public async Task ABuildersNearerHandler_WinsOverTheRoutesWiderOne() { var taken = new List(); await using var ctx = new RouteContext(); ctx.AddRoutes(r => { r.OnException().Handled().Process(_ => Take(taken, "builder")); r.From("direct://policy-scopes") .OnException().Handled().Process(_ => Take(taken, "route")).End() .Process(Throw); }); await ctx.Start(); await Send(ctx, "direct://policy-scopes", new IOException("io")); await Send(ctx, "direct://policy-scopes", new InvalidOperationException("op")); taken.Should().Equal("builder", "route"); } [Fact] public async Task TheRoutesOwnHandler_WinsATieWithItsBuilders() { var taken = new List(); await using var ctx = new RouteContext(); ctx.AddRoutes(r => { r.OnException().Handled().Process(_ => Take(taken, "builder")); r.From("direct://policy-tie") .OnException().Handled().Process(_ => Take(taken, "route")).End() .Process(Throw); }); await ctx.Start(); await Send(ctx, "direct://policy-tie", new IOException("io")); taken.Should().Equal("route"); } [Fact] public async Task ACause_IsMatched() { var taken = new List(); await using var ctx = new RouteContext(); ctx.AddRoutes(r => { r.OnException().Handled().Process(e => Take(taken, e.Exception!.GetType().Name)); r.From("direct://policy-cause").Process(Throw); }); await ctx.Start(); var exchange = await Send(ctx, "direct://policy-cause", new InvalidOperationException("wrapper", new IOException("the cause"))); taken.Should().ContainSingle().Which.Should().Be("InvalidOperationException", "the handler gets the exception that was thrown, as in Camel"); exchange.Exception.Should().BeNull(); } [Fact] public async Task TheInnermostCause_IsLookedAtFirst() { var taken = new List(); await using var ctx = new RouteContext(); ctx.AddRoutes(r => { r.OnException().Handled().Process(_ => Take(taken, "wrapper")); r.OnException().Handled().Process(_ => Take(taken, "cause")); r.From("direct://policy-innermost").Process(Throw); }); await ctx.Start(); await Send(ctx, "direct://policy-innermost", new InvalidOperationException("wrapper", new IOException("cause"))); taken.Should().Equal("cause"); } [Fact] public async Task ACauseFurtherFromItsHandler_LosesToTheThrownExceptionsNearerOne() { // As in Camel's source: the smallest distance over the whole chain wins, the cause only breaks a tie. // The thrown exception is one step from Exception, its cause two steps from DbException. var taken = new List(); await using var ctx = new RouteContext(); ctx.AddRoutes(r => { r.OnException().Handled().Process(_ => Take(taken, "db")); r.OnException().Handled().Process(_ => Take(taken, "any")); r.From("direct://policy-chain-gap").Process(Throw); }); await ctx.Start(); await Send(ctx, "direct://policy-chain-gap", new UniqueViolationException(new DriverException())); taken.Should().Equal("any"); } [Fact] public async Task AHandlerForTheThrownType_TakesAFailureWhoseCauseIsFurtherAway() { var taken = new List(); await using var ctx = new RouteContext(); ctx.AddRoutes(r => { r.OnException().Handled().Process(_ => Take(taken, "db")); r.OnException().Handled().Process(_ => Take(taken, "unique")); r.OnException().Handled().Process(_ => Take(taken, "any")); r.From("direct://policy-chain-remedy").Process(Throw); }); await ctx.Start(); await Send(ctx, "direct://policy-chain-remedy", new UniqueViolationException(new DriverException())); taken.Should().Equal("unique"); } [Fact] public async Task AWrapperWithItsOwnHandler_IsNotTakenByACatchAllThatMatchesItsCause() { // The common shape, a catch-all beside a specific handler: the cause matches only the catch-all, the // thrown exception matches its own handler exactly, and the exact match wins. var taken = new List(); await using var ctx = new RouteContext(); ctx.AddRoutes(r => { r.OnException().Handled().Process(_ => Take(taken, "invalid")); r.OnException().Handled().Process(_ => Take(taken, "any")); r.From("direct://policy-chain-wrapper").Process(Throw); }); await ctx.Start(); await Send(ctx, "direct://policy-chain-wrapper", new InvalidOperationException("wrapper", new SocketException((int)SocketError.ConnectionRefused))); taken.Should().Equal("invalid"); } [Fact] public async Task AHandlerWhoseOnWhenIsFalse_IsPassedOver() { var taken = new List(); await using var ctx = new RouteContext(); ctx.AddRoutes(r => { r.OnException().OnWhen(e => e.In.Headers.ContainsKey("urgent")) .Handled().Process(_ => Take(taken, "urgent")); r.OnException().Handled().Process(_ => Take(taken, "any")); r.From("direct://policy-when").Process(Throw); }); await ctx.Start(); await Send(ctx, "direct://policy-when", new IOException("io")); await Send(ctx, "direct://policy-when", new IOException("io"), ("urgent", true)); taken.Should().Equal("any", "urgent"); } [Fact] public async Task ALaterHandlerOfTheSameType_ReplacesTheEarlier() { var taken = new List(); await using var ctx = new RouteContext(); ctx.AddRoutes(r => { r.OnException().Handled().Process(_ => Take(taken, "first")); r.OnException().Handled().Process(_ => Take(taken, "second")); r.From("direct://policy-replace").Process(Throw); }); await ctx.Start(); await Send(ctx, "direct://policy-replace", new IOException("io")); taken.Should().Equal("second"); } [Fact] public async Task ARedelivery_MayEndInAnotherHandler() { // One scope, one redelivery loop: the handler is chosen again for the failure of every attempt. var taken = new List(); var attempts = 0; await using var ctx = new RouteContext(); ctx.AddRoutes(r => { r.OnException().MaximumRedeliveries(1).RedeliveryDelay(TimeSpan.FromMilliseconds(1)) .Handled().Process(_ => Take(taken, "io")); r.OnException().Handled().Process(_ => Take(taken, "invalid")); r.From("direct://policy-redelivery").Process(_ => { if (Interlocked.Increment(ref attempts) == 1) throw new IOException("first attempt"); throw new InvalidOperationException("second attempt"); }); }); await ctx.Start(); await Send(ctx, "direct://policy-redelivery", "x"); attempts.Should().Be(2); taken.Should().Equal("invalid"); } /// A storage exception thrown with a driver exception inside, deriving directly from Exception. private sealed class UniqueViolationException(Exception inner) : Exception("unique violation", inner); /// A driver exception two steps from DbException, as a PostgreSQL driver's is. private sealed class DriverException() : ProviderException("duplicate key"); private class ProviderException(string message) : DbException(message); private static void Take(List taken, string who) { lock (taken) taken.Add(who); } private static void Throw(IExchange exchange) => throw (Exception)exchange.In.Body!; private static async Task Send(IRouteContext ctx, string uri, object body, params (string Name, object? Value)[] headers) { var producer = ctx.GetEndpoint(uri).CreateProducer(); await producer.Start(); var message = new Message { Body = body }; foreach (var (name, value) in headers) message.Headers[name] = value; var exchange = new Exchange(message); try { await producer.Process(exchange); } catch (Exception ex) { exchange.Exception ??= ex; } return exchange; } } Path: redb-route/tests/redb.Route.Tests/Core/ExchangeBodyDisposeTests.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/ExchangeBodyDisposeTests.cs ---- using redb.Route.Core; using AwesomeAssertions; namespace redb.Route.Tests.Core; public class ExchangeBodyDisposeTests { [Fact] public async Task DisposeAsync_StreamBody_DisposesStream() { var stream = new MemoryStream(new byte[] { 1, 2, 3 }); var exchange = new Exchange(new Message(stream)); await exchange.DisposeAsync().ConfigureAwait(false); stream.CanRead.Should().BeFalse(); } [Fact] public async Task DisposeAsync_StringBody_NoError() { var exchange = new Exchange(new Message("hello")); var act = async () => await exchange.DisposeAsync().ConfigureAwait(false); await act.Should().NotThrowAsync().ConfigureAwait(false); } [Fact] public async Task DisposeAsync_NullBody_NoError() { var exchange = new Exchange(new Message()); var act = async () => await exchange.DisposeAsync().ConfigureAwait(false); await act.Should().NotThrowAsync().ConfigureAwait(false); } [Fact] public async Task DisposeAsync_OutBodyStream_BothDisposed() { var inStream = new MemoryStream(new byte[] { 1, 2, 3 }); var outStream = new MemoryStream(new byte[] { 4, 5, 6 }); var exchange = new Exchange(new Message(inStream)) { Out = new Message(outStream) }; await exchange.DisposeAsync().ConfigureAwait(false); inStream.CanRead.Should().BeFalse(); outStream.CanRead.Should().BeFalse(); } [Fact] public async Task DisposeAsync_CustomDisposableBody_CallsDispose() { var disposable = new TrackingDisposable(); var exchange = new Exchange(new Message(disposable)); await exchange.DisposeAsync().ConfigureAwait(false); disposable.Disposed.Should().BeTrue(); } [Fact] public async Task DisposeAsync_CustomAsyncDisposableBody_CallsDisposeAsync() { var disposable = new TrackingAsyncDisposable(); var exchange = new Exchange(new Message(disposable)); await exchange.DisposeAsync().ConfigureAwait(false); disposable.Disposed.Should().BeTrue(); } private sealed class TrackingDisposable : IDisposable { public bool Disposed { get; private set; } public void Dispose() => Disposed = true; } private sealed class TrackingAsyncDisposable : IAsyncDisposable { public bool Disposed { get; private set; } public ValueTask DisposeAsync() { Disposed = true; return ValueTask.CompletedTask; } } } Path: redb-route/tests/redb.Route.Tests/Core/ExchangeBodyOwnershipTests.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/ExchangeBodyOwnershipTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Components; using redb.Route.Core; namespace redb.Route.Tests.Core; /// /// A body that needs disposing (a stream, a ) is disposed by the unit of work that owns it, once, /// when that owner is done — as in Camel, where the original exchange's unit of work cleans up and a copy does not. A copy /// shares the body of its origin by reference, and it used to dispose it: a fan-out step (RecipientList, Splitter, /// Scatter-Gather, a copying Loop) closed the body the route went on with, the aggregated result included, and /// .Threads() lost its body to the caller disposing the original while the worker still read it. /// public class ExchangeBodyOwnershipTests { /// A stream that counts its disposals and refuses to be read after the first. private sealed class TrackedStream() : MemoryStream("payload"u8.ToArray()) { public int Disposals; protected override void Dispose(bool disposing) { if (disposing) Interlocked.Increment(ref Disposals); base.Dispose(disposing); } } // ── The rule, on the exchange ── [Fact] public async Task A_copy_does_not_dispose_the_body_it_shares_with_its_origin() { var body = new TrackedStream(); var root = new Exchange(new Message(body)); var copy = root.Clone(); await copy.DisposeAsync(); body.Disposals.Should().Be(0, "the origin still carries it"); await root.DisposeAsync(); body.Disposals.Should().Be(1); } [Fact] public async Task A_body_a_copy_made_and_handed_to_its_origin_lives_as_long_as_the_origin() { var root = new Exchange(new Message("in")); var copy = root.Clone(); var result = new TrackedStream(); copy.In.Body = result; root.In.Body = copy.In.Body; // what an aggregation does await copy.DisposeAsync(); result.Disposals.Should().Be(0); await root.DisposeAsync(); result.Disposals.Should().Be(1); } [Fact] public async Task A_body_the_origin_lent_and_then_replaced_is_still_disposed_by_the_origin() { var original = new TrackedStream(); var root = new Exchange(new Message(original)); var copy = root.Clone(); root.In.Body = "aggregated"; await copy.DisposeAsync(); original.Disposals.Should().Be(0, "it is the origin's to dispose"); await root.DisposeAsync(); original.Disposals.Should().Be(1, "replacing it must not leak it"); } [Fact] public async Task A_body_a_copy_made_and_kept_is_disposed_by_the_copy() { var root = new Exchange(new Message("in")); var part = new TrackedStream(); var child = root.CreateChild(new Message(part)); await child.DisposeAsync(); part.Disposals.Should().Be(1); await root.DisposeAsync(); part.Disposals.Should().Be(1); } [Fact] public async Task Disposing_an_exchange_twice_disposes_its_body_once() { var body = new TrackedStream(); var root = new Exchange(new Message(body)); await root.DisposeAsync(); await root.DisposeAsync(); body.Disposals.Should().Be(1); } [Fact] public async Task A_body_shared_by_In_and_Out_is_disposed_once() { var body = new TrackedStream(); var root = new Exchange(new Message(body)) { Out = new Message(body) }; await root.DisposeAsync(); body.Disposals.Should().Be(1); } // ── The EIPs the review named ── private static async Task Routes(Action build) { var context = new RouteContext($"body-ownership-{Guid.NewGuid():N}"); context.AddComponent(new DirectComponent()); context.AddRoutes(build); await context.Start(); return context; } [Fact] public async Task RecipientList_keeps_open_the_aggregated_body_the_route_goes_on_with() { TrackedStream? produced = null; var disposalsAfterStep = -1; await using var context = await Routes(r => { r.From("direct://rl-in") .RecipientList(_ => ["direct://rl-producer"], aggregationStrategy: static (_, latest) => latest) .Process(e => disposalsAfterStep = ((TrackedStream)e.In.Body!).Disposals); r.From("direct://rl-producer").Process(e => e.In.Body = produced = new TrackedStream()); }); var template = new ProducerTemplate(context); template.Start(); await template.SendAsync("direct://rl-in", "in"); template.Dispose(); disposalsAfterStep.Should().Be(0, "the route goes on with the aggregated body"); produced!.Disposals.Should().Be(1, "and it is disposed once, when the exchange is done"); } [Fact] public async Task A_copying_Loop_keeps_open_the_body_merged_back() { var disposalsAfterLoop = -1; TrackedStream? last = null; await using var context = await Routes(r => r.From("direct://loop-in") .Loop(2, copy: true) .Process(e => e.In.Body = last = new TrackedStream()) .EndLoop() .Process(e => disposalsAfterLoop = ((TrackedStream)e.In.Body!).Disposals)); var template = new ProducerTemplate(context); template.Start(); await template.SendAsync("direct://loop-in", "in"); template.Dispose(); disposalsAfterLoop.Should().Be(0); last!.Disposals.Should().Be(1); } [Fact] public async Task Threads_keeps_the_body_open_for_the_worker_after_the_caller_is_done() { var body = new TrackedStream(); var read = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); await using var context = await Routes(r => r.From("direct://threads-in") .Threads(1) .Process(async (e, _) => { await Task.Delay(200); read.TrySetResult(((TrackedStream)e.In.Body!).Disposals); })); var template = new ProducerTemplate(context); template.Start(); await template.SendAsync("direct://threads-in", body); // the caller disposes its exchange right after template.Dispose(); (await read.Task.WaitAsync(TimeSpan.FromSeconds(10))).Should().Be(0, "the worker still reads the body"); await context.Stop(); body.Disposals.Should().Be(1, "the worker's exchange disposes it once"); } } Path: redb-route/tests/redb.Route.Tests/Core/ExchangeCompletionTests.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/ExchangeCompletionTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Tests.Core; /// /// Completions registered with — Apache Camel's addOnCompletion with a /// Synchronization — run once when the exchange's unit of work ends: OnComplete on success, OnFailure /// otherwise, reaching the consumer's verdict. The outermost route owns the unit of work and ends it before returning; /// an exchange no route owns ends it when it is released. Copies do not inherit completions. /// public sealed class ExchangeCompletionTests { private sealed class Recording : IExchangeCompletion { private readonly List _log; private readonly string _name; public Recording(List log, string name = "c") { _log = log; _name = name; } public Task OnComplete(IExchange exchange, CancellationToken ct) { lock (_log) _log.Add($"{_name}:complete"); return Task.CompletedTask; } public Task OnFailure(IExchange exchange, CancellationToken ct) { lock (_log) _log.Add($"{_name}:failure"); return Task.CompletedTask; } } private sealed class Throwing : IExchangeCompletion { public Task OnComplete(IExchange exchange, CancellationToken ct) => throw new InvalidOperationException("completion fails"); public Task OnFailure(IExchange exchange, CancellationToken ct) => throw new InvalidOperationException("completion fails"); } private static async Task Start(RouteContext context, string uri) { await context.Start(); var producer = context.GetEndpoint(uri).CreateProducer(); await producer.Start(); return producer; } [Fact] public async Task A_route_ends_the_unit_of_work_before_it_returns_success() { var log = new List(); await using var context = new RouteContext(); context.AddRoutes(r => r .From("direct://c-success") .Process(ex => ExchangeResources.OnCompletion(ex, new Recording(log))) .Process(_ => { lock (log) log.Add("route"); })); var producer = await Start(context, "direct://c-success"); await producer.Process(new Exchange(new Message("x"))); log.Should().Equal("route", "c:complete"); } [Fact] public async Task An_escaping_exception_is_a_failure() { var log = new List(); await using var context = new RouteContext(); context.AddRoutes(r => r .From("direct://c-thrown") .Process(ex => ExchangeResources.OnCompletion(ex, new Recording(log))) .Process(_ => throw new InvalidOperationException("boom"))); var producer = await Start(context, "direct://c-thrown"); var send = () => producer.Process(new Exchange(new Message("x"))); await send.Should().ThrowAsync(); log.Should().Equal("c:failure"); } [Fact] public async Task A_failure_left_unhandled_on_the_exchange_is_a_failure() { var log = new List(); await using var context = new RouteContext(); context.AddRoutes(r => r .From("direct://c-unhandled") .OnException() .Log("seen, not handled") .End() .Process(ex => ExchangeResources.OnCompletion(ex, new Recording(log))) .Process(_ => throw new InvalidOperationException("boom"))); var producer = await Start(context, "direct://c-unhandled"); var exchange = new Exchange(new Message("x")); await producer.Process(exchange); exchange.EndedInFailure().Should().BeTrue("OnException without Handled leaves the failure on the exchange"); log.Should().Equal("c:failure"); } [Fact] public async Task A_handled_failure_is_a_success() { var log = new List(); await using var context = new RouteContext(); context.AddRoutes(r => r .From("direct://c-handled") .OnException() .Handled() .End() .Process(ex => ExchangeResources.OnCompletion(ex, new Recording(log))) .Process(_ => throw new InvalidOperationException("boom"))); var producer = await Start(context, "direct://c-handled"); await producer.Process(new Exchange(new Message("x"))); log.Should().Equal("c:complete"); } [Fact] public async Task A_rollback_only_exchange_is_a_failure() { var log = new List(); await using var context = new RouteContext(); context.AddRoutes(r => r .From("direct://c-rollback") .Process(ex => ExchangeResources.OnCompletion(ex, new Recording(log))) .RollbackAll()); var producer = await Start(context, "direct://c-rollback"); await producer.Process(new Exchange(new Message("x"))); log.Should().Equal("c:failure"); } [Fact] public async Task A_release_in_the_middle_of_the_route_does_not_end_its_unit_of_work() { var log = new List(); await using var context = new RouteContext(); context.AddRoutes(r => r .From("direct://c-midrelease") .Process(ex => ExchangeResources.OnCompletion(ex, new Recording(log))) .Process(async (ex, _) => await ex.ReleaseScopes()) .Process(_ => throw new InvalidOperationException("after the release"))); var producer = await Start(context, "direct://c-midrelease"); var send = () => producer.Process(new Exchange(new Message("x"))); await send.Should().ThrowAsync(); log.Should().Equal("c:failure"); } [Fact] public async Task Completions_run_in_registration_order_and_a_failing_one_does_not_stop_the_others() { var log = new List(); await using var context = new RouteContext(); context.AddRoutes(r => r .From("direct://c-order") .Process(ex => { ExchangeResources.OnCompletion(ex, new Recording(log, "first")); ExchangeResources.OnCompletion(ex, new Throwing()); ExchangeResources.OnCompletion(ex, new Recording(log, "second")); })); var producer = await Start(context, "direct://c-order"); await producer.Process(new Exchange(new Message("x"))); log.Should().Equal("first:complete", "second:complete"); } [Fact] public async Task An_exchange_no_route_owns_ends_its_unit_of_work_when_released() { var log = new List(); var exchange = new Exchange(new Message("x")); ExchangeResources.OnCompletion(exchange, new Recording(log)); log.Should().BeEmpty(); exchange.Exception = new InvalidOperationException("failed"); await exchange.DisposeAsync(); log.Should().Equal("c:failure"); } [Fact] public async Task Copies_do_not_inherit_completions() { var log = new List(); var exchange = new Exchange(new Message("x")); ExchangeResources.OnCompletion(exchange, new Recording(log)); await using (var copy = (Exchange)exchange.Clone()) copy.Properties.Keys.Should().NotContain(k => k.StartsWith("__redb_uow", StringComparison.Ordinal)); log.Should().BeEmpty("the copy has no unit of work of its own and ended nothing"); await exchange.DisposeAsync(); log.Should().Equal("c:complete"); } [Fact] public async Task The_unit_of_work_ends_once() { var log = new List(); var exchange = new Exchange(new Message("x")); ExchangeResources.OnCompletion(exchange, new Recording(log)); await exchange.ReleaseScopes(); await exchange.DisposeAsync(); log.Should().Equal("c:complete"); } } Path: redb-route/tests/redb.Route.Tests/Core/ExchangeContextTests.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/ExchangeContextTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Tests.Core; /// /// — Apache Camel's exchange.getContext(), the seam that /// lets a processor reach measurements and services without capturing the context into a lambda. /// Stamped by the route wrapper on entry, restored on exit, so /// "current" always means the route actually executing — inside a direct: sub-route the /// inner route's context, and the caller's own again after the sub-route returns. /// public sealed class ExchangeContextTests { [Fact] public async Task An_exchange_inside_a_route_knows_its_context() { IRouteContext? seen = null; await using var context = new RouteContext(); context.AddRoutes(r => r.From("direct:ctx").Process(e => seen = e.Context)); await context.Start(); var producer = context.GetEndpoint("direct:ctx").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("m"))); seen.Should().BeSameAs(context, "this is what replaces capturing the context into every lambda"); } [Fact] public void A_hand_made_exchange_has_no_context() { new Exchange(new Message("m")).Context.Should().BeNull( "it was never handed to a route, and pretending otherwise would lie about lifetime"); } [Fact] public async Task The_context_lets_a_step_read_endpoint_statistics_without_capture() { long? errors = null; await using var context = new RouteContext(); context.AddRoutes(r => r.From("direct:ctx-stats").Process(e => errors = ((IEndpointStatistics)e.Context!.GetEndpoint("direct:ctx-stats")).Errors)); await context.Start(); var producer = context.GetEndpoint("direct:ctx-stats").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("m"))); errors.Should().Be(0); } [Fact] public async Task Copies_inherit_the_context() { await using var context = new RouteContext(); IExchange? inRoute = null; context.AddRoutes(r => r.From("direct:ctx-copy").Process(e => inRoute = e.Clone())); await context.Start(); var producer = context.GetEndpoint("direct:ctx-copy").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("m"))); inRoute!.Context.Should().BeSameAs(context); inRoute.CreateChild(new Message("c")).Context.Should().BeSameAs(context); inRoute.Snapshot().Context.Should().BeSameAs(context); } [Fact] public async Task Parallel_branches_see_the_context() { var seen = new System.Collections.Concurrent.ConcurrentBag(); await using var context = new RouteContext(); context.AddRoutes(r => r.From("direct:ctx-multi") .Multicast() .To("direct:ctx-branch") .EndMulticast()); context.AddRoutes(r => r.From("direct:ctx-branch").Process(e => seen.Add(e.Context))); await context.Start(); var producer = context.GetEndpoint("direct:ctx-multi").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("m"))); seen.Should().NotBeEmpty().And.OnlyContain(c => ReferenceEquals(c, context)); } [Fact] public async Task After_the_route_returns_the_callers_view_is_restored() { // The stamp is scoped, not sticky: an exchange created by hand, pushed through a route, // comes back with the context it had before — null. Camel's "current context" semantics, // taken literally: outside any route there is no current route. await using var context = new RouteContext(); context.AddRoutes(r => r.From("direct:ctx-restore").Process(_ => { })); await context.Start(); var producer = context.GetEndpoint("direct:ctx-restore").CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("m")); await producer.Process(exchange); exchange.Context.Should().BeNull("the wrapper restores what the caller had on entry"); } } Path: redb-route/tests/redb.Route.Tests/Core/ExchangeIdTests.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/ExchangeIdTests.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using AwesomeAssertions; namespace redb.Route.Tests.Core; public class ExchangeIdTests { [Fact] public void NewExchange_HasNonEmptyExchangeId() { var ex = new Exchange(); ex.ExchangeId.Should().NotBeNullOrEmpty(); ex.ExchangeId.Should().HaveLength(32); // Guid without hyphens } [Fact] public void TwoExchanges_HaveDifferentIds() { var ex1 = new Exchange(); var ex2 = new Exchange(); ex1.ExchangeId.Should().NotBe(ex2.ExchangeId); } [Fact] public void Clone_PreservesExchangeId() { var original = new Exchange(new Message("test")); var clone = original.Clone(); clone.ExchangeId.Should().Be(original.ExchangeId); } [Fact] public void CreateChild_HasNewExchangeId() { var parent = new Exchange(new Message("parent")); var child = parent.CreateChild(new Message("child")); // CreateChild creates a new exchange — should have its own ExchangeId child.ExchangeId.Should().NotBeNullOrEmpty(); } [Fact] public void ExchangeId_IsAccessibleViaInterface() { IExchange ex = new Exchange(); ex.ExchangeId.Should().NotBeNullOrEmpty(); } } Path: redb-route/tests/redb.Route.Tests/Core/ExchangePrincipalTests.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/ExchangePrincipalTests.cs ---- using System.Security.Claims; using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Tests.Core; /// /// — the caller's identity as an exchange property (Camel /// Exchange.AUTHENTICATION). What makes it worth a well-known key is inheritance: a sub-route, /// a split part and an LLM tool call all run on derived exchanges, and each must still know who sent /// the request that started them. /// public sealed class ExchangePrincipalTests { private static ClaimsPrincipal User(string id) => new(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, id)], "test")); [Fact] public void A_hand_made_exchange_carries_no_identity() { ExchangePrincipal.Get(new Exchange(new Message("m"))).Should().BeNull(); } [Fact] public void Set_then_get_returns_the_same_principal_and_null_removes_it() { var exchange = new Exchange(new Message("m")); var user = User("u-1"); ExchangePrincipal.Set(exchange, user); ExchangePrincipal.Get(exchange).Should().BeSameAs(user); ExchangePrincipal.Set(exchange, null); ExchangePrincipal.Get(exchange).Should().BeNull(); exchange.Properties.Should().NotContainKey(ExchangePrincipal.PropertyKey); } [Fact] public void A_value_of_another_type_under_the_key_is_not_an_identity() { var exchange = new Exchange(new Message("m")); exchange.Properties[ExchangePrincipal.PropertyKey] = "user-42"; ExchangePrincipal.Get(exchange).Should().BeNull( "a string under the key is not a principal, and building one from it would forge an identity from data"); } public static TheoryData Copies => new() { "CreateChild", "CreateLinkedChild", "Clone", "CloneLinked", "Snapshot" }; [Theory] [MemberData(nameof(Copies))] public void Every_exchange_copy_inherits_the_identity(string copy) { var exchange = new Exchange(new Message("m")); var user = User("u-7"); ExchangePrincipal.Set(exchange, user); IExchange derived = copy switch { "CreateChild" => exchange.CreateChild(new Message("part")), "CreateLinkedChild" => exchange.CreateLinkedChild(new Message("tool")), "Clone" => exchange.Clone(), "CloneLinked" => exchange.CloneLinked(), "Snapshot" => exchange.Snapshot(), _ => throw new ArgumentOutOfRangeException(nameof(copy)), }; ExchangePrincipal.Get(derived).Should().BeSameAs(user, $"{copy} runs code on behalf of the same caller"); } } Path: redb-route/tests/redb.Route.Tests/Core/ExchangeResourceReleaseTests.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/ExchangeResourceReleaseTests.cs ---- using AwesomeAssertions; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Tests.Core; /// /// Resources registered with — the counterpart of Apache Camel's /// addOnCompletion — are released when the exchange ends, most recent first and before its DI scopes, once, and /// independently of each other; copies of the exchange do not inherit them. /// public sealed class ExchangeResourceReleaseTests { private sealed class TrackingResource(List log, string name, bool fail = false) : IAsyncDisposable { public int DisposeCount; public ValueTask DisposeAsync() { Interlocked.Increment(ref DisposeCount); lock (log) log.Add(name); if (fail) throw new InvalidOperationException($"{name}: release failed"); return ValueTask.CompletedTask; } } private sealed class TrackingScope(List log) : IServiceScope, IAsyncDisposable { public IServiceProvider ServiceProvider => null!; public void Dispose() { lock (log) log.Add("scope"); } public ValueTask DisposeAsync() { lock (log) log.Add("scope"); return ValueTask.CompletedTask; } } [Fact] public async Task A_registered_resource_is_released_when_the_exchange_is_disposed() { var log = new List(); var exchange = new Exchange(new Message("m")); var resource = new TrackingResource(log, "stream"); ExchangeResources.ReleaseWithExchange(exchange, resource); await exchange.DisposeAsync(); resource.DisposeCount.Should().Be(1); exchange.Properties.Keys.Should().NotContain(k => k.StartsWith(ExchangeResources.PropertyPrefix)); } [Fact] public async Task Resources_are_released_most_recent_first_and_before_the_exchange_scopes() { var log = new List(); var exchange = new Exchange(new Message("m")); exchange.Properties["__redb_scope:audit"] = new TrackingScope(log); ExchangeResources.ReleaseWithExchange(exchange, new TrackingResource(log, "first")); ExchangeResources.ReleaseWithExchange(exchange, new TrackingResource(log, "second")); await exchange.ReleaseScopes(); log.Should().Equal(new[] { "second", "first", "scope" }, "a later resource may depend on an earlier one, and a resource may come from a factory living in a scope"); } [Fact] public async Task A_failing_release_does_not_stop_the_other_releases() { var log = new List(); var exchange = new Exchange(new Message("m")); var healthy = new TrackingResource(log, "healthy"); ExchangeResources.ReleaseWithExchange(exchange, healthy); ExchangeResources.ReleaseWithExchange(exchange, new TrackingResource(log, "broken", fail: true)); await exchange.DisposeAsync(); healthy.DisposeCount.Should().Be(1); log.Should().Equal("broken", "healthy"); } [Fact] public async Task Releasing_twice_releases_each_resource_once() { var exchange = new Exchange(new Message("m")); var resource = new TrackingResource([], "stream"); ExchangeResources.ReleaseWithExchange(exchange, resource); await exchange.ReleaseScopes(); await exchange.DisposeAsync(); resource.DisposeCount.Should().Be(1); } [Fact] public async Task Resources_handed_over_are_released_with_the_receiving_exchange() { var resourceExchange = new Exchange(new Message("resource")); var original = new Exchange(new Message("original")); var resource = new TrackingResource([], "stream"); ExchangeResources.ReleaseWithExchange(resourceExchange, resource); ExchangeResources.HandOver(resourceExchange, original); await resourceExchange.DisposeAsync(); resource.DisposeCount.Should().Be(0, "the resource now belongs to the receiving exchange (Apache Camel: handoverCompletions)"); resourceExchange.Properties.Keys.Should().NotContain(k => k.StartsWith(ExchangeResources.PropertyPrefix)); await original.DisposeAsync(); resource.DisposeCount.Should().Be(1); } [Fact] public async Task A_failing_release_is_logged_through_the_context_when_the_exchange_has_no_scope() { var logs = new CapturingLoggerFactory(); await using var context = new RouteContext(loggerFactory: logs); var exchange = new Exchange(new Message("m")) { Context = context }; ExchangeResources.ReleaseWithExchange(exchange, new TrackingResource([], "broken", fail: true)); await exchange.DisposeAsync(); logs.Entries.Should().Contain(e => e.Level == LogLevel.Error && e.Message.Contains("Releasing resource"), "an exchange without a DI scope (ProducerTemplate, tests) still has a context to log through; " + $"logged: {string.Join(" | ", logs.Entries.Select(e => e.Message))}"); } private sealed class CapturingLoggerFactory : ILoggerFactory { public List<(LogLevel Level, string Message)> Entries { get; } = []; public ILogger CreateLogger(string categoryName) => new CapturingLogger(this); public void AddProvider(ILoggerProvider provider) { } public void Dispose() { } private sealed class CapturingLogger(CapturingLoggerFactory 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) { lock (owner.Entries) owner.Entries.Add((logLevel, formatter(state, exception))); } } } [Fact] public void Copies_of_the_exchange_do_not_inherit_registered_resources() { var exchange = new Exchange(new Message("m")); ExchangeResources.ReleaseWithExchange(exchange, new TrackingResource([], "stream")); exchange.Properties["user"] = "kept"; var copies = new[] { exchange.CreateChild(new Message("child")), exchange.CreateLinkedChild(new Message("linked")), exchange.Clone(), exchange.CloneLinked(), exchange.Snapshot(), }; foreach (var copy in copies) { copy.Properties.Should().ContainKey("user"); copy.Properties.Keys.Should().NotContain(k => k.StartsWith(ExchangeResources.PropertyPrefix), "a resource belongs to the exchange that registered it; a copy releasing it would close it under the original"); } } } Path: redb-route/tests/redb.Route.Tests/Core/ExchangeScopeReleaseTests.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/ExchangeScopeReleaseTests.cs ---- using AwesomeAssertions; using Microsoft.Extensions.DependencyInjection; using redb.Route.Core; namespace redb.Route.Tests.Core; /// /// used to be a one-shot latch: the first call spent it for /// the life of the exchange. Downstream code calls it manually in error handlers (a production /// integration carries three such call sites), and any redb access on the same exchange afterwards caches a fresh /// scope under __redb_scope:* — which the spent latch then prevented /// from ever releasing. A landmine rather than a proven live /// leak, because today's handlers end the route; these tests defuse it either way. /// /// The latch's real job was mutual exclusion and once-only disposal, and both survive without the /// mine: entries leave the property bag as they are released, the owned scope nulls out, and the /// latch re-arms after each sweep — so calling again releases only what appeared since. /// /// public sealed class ExchangeScopeReleaseTests { private sealed class TrackingScope : IServiceScope, IAsyncDisposable { public int DisposeCount; public IServiceProvider ServiceProvider => null!; public void Dispose() => Interlocked.Increment(ref DisposeCount); public ValueTask DisposeAsync() { Interlocked.Increment(ref DisposeCount); return ValueTask.CompletedTask; } } [Fact] public async Task A_scope_created_after_a_manual_release_is_still_released_on_dispose() { var exchange = new Exchange(new Message("m")); var beforeRelease = new TrackingScope(); exchange.Properties["__redb_scope:audit"] = beforeRelease; await exchange.ReleaseScopes(); beforeRelease.DisposeCount.Should().Be(1); // What an error handler's tail does: touch redb again on the same exchange, which caches // a fresh scope. The manual release must not have cost the exchange its cleanup. var afterRelease = new TrackingScope(); exchange.Properties["__redb_scope:usage"] = afterRelease; await exchange.DisposeAsync(); afterRelease.DisposeCount.Should().Be(1, "a spent latch here means a live connection held until the GC finds it"); } [Fact] public async Task Releasing_twice_disposes_each_scope_once() { var exchange = new Exchange(new Message("m")); var scope = new TrackingScope(); exchange.Properties["__redb_scope:audit"] = scope; await exchange.ReleaseScopes(); await exchange.ReleaseScopes(); scope.DisposeCount.Should().Be(1, "the entry leaves the property bag as it is released"); } [Fact] public async Task The_owned_scope_is_disposed_once_across_repeated_releases() { var scope = new TrackingScope(); var factory = Substitute.For(); factory.CreateScope().Returns(scope); var exchange = new Exchange(new Message("m"), factory); await exchange.ReleaseScopes(); await exchange.ReleaseScopes(); await exchange.DisposeAsync(); scope.DisposeCount.Should().Be(1, "the owned scope nulls out after its first disposal"); } } Path: redb-route/tests/redb.Route.Tests/Core/ExchangeScopeTests.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/ExchangeScopeTests.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Tests.Core; /// /// Tests for Exchange DI scope lifecycle: creation, propagation, disposal. /// public class ExchangeScopeTests { // ── Factory tests ── [Fact] public void Create_WithoutScopeFactory_HasNullServiceProvider() { var exchange = Exchange.Create(new Message("test"), null); exchange.ServiceProvider.Should().BeNull(); exchange.In.Body.Should().Be("test"); } [Fact] public void Create_WithScopeFactory_HasServiceProvider() { var services = new ServiceCollection() .AddSingleton("hello") .BuildServiceProvider(); var factory = services.GetRequiredService(); var exchange = Exchange.Create(new Message("test"), factory); exchange.ServiceProvider.Should().NotBeNull(); exchange.ServiceProvider!.GetService().Should().Be("hello"); } [Fact] public void Create_EachCall_CreatesIsolatedScope() { var services = new ServiceCollection() .AddScoped() .BuildServiceProvider(); var factory = services.GetRequiredService(); var ex1 = Exchange.Create(new Message(), factory); var ex2 = Exchange.Create(new Message(), factory); var m1 = ex1.ServiceProvider!.GetRequiredService(); var m2 = ex2.ServiceProvider!.GetRequiredService(); m1.Should().NotBeSameAs(m2); } // ── Clone tests ── [Fact] public void Clone_WithScopeFactory_CreatesNewScope() { var services = new ServiceCollection() .AddScoped() .BuildServiceProvider(); var factory = services.GetRequiredService(); var original = Exchange.Create(new Message("data"), factory); var clone = original.Clone(); clone.ServiceProvider.Should().NotBeNull(); clone.In.Body.Should().Be("data"); var originalMarker = original.ServiceProvider!.GetRequiredService(); var cloneMarker = clone.ServiceProvider!.GetRequiredService(); cloneMarker.Should().NotBeSameAs(originalMarker); } [Fact] public void Clone_WithoutScopeFactory_HasNullServiceProvider() { var original = new Exchange(new Message("data")); var clone = original.Clone(); clone.ServiceProvider.Should().BeNull(); } // ── CreateChild tests ── [Fact] public void CreateChild_CreatesNewScopeWithDifferentMessage() { var services = new ServiceCollection() .AddScoped() .BuildServiceProvider(); var factory = services.GetRequiredService(); var parent = Exchange.Create(new Message("parent"), factory); parent.RouteId = "route-1"; parent.Properties["key"] = "value"; var child = parent.CreateChild(new Message("child")); child.In.Body.Should().Be("child"); child.RouteId.Should().Be("route-1"); child.Properties["key"].Should().Be("value"); child.ServiceProvider.Should().NotBeNull(); var parentMarker = parent.ServiceProvider!.GetRequiredService(); var childMarker = child.ServiceProvider!.GetRequiredService(); childMarker.Should().NotBeSameAs(parentMarker); } // ── Dispose tests ── [Fact] public async Task DisposeAsync_DisposesScope() { var services = new ServiceCollection() .AddScoped() .BuildServiceProvider(); var factory = services.GetRequiredService(); var exchange = Exchange.Create(new Message(), factory); exchange.ServiceProvider.Should().NotBeNull(); await exchange.DisposeAsync(); exchange.ServiceProvider.Should().BeNull(); } [Fact] public async Task DisposeAsync_WithoutScope_DoesNotThrow() { var exchange = new Exchange(new Message()); await exchange.DisposeAsync(); // Should not throw } [Fact] public async Task DisposeAsync_CalledTwice_DoesNotThrow() { var services = new ServiceCollection().BuildServiceProvider(); var factory = services.GetRequiredService(); var exchange = Exchange.Create(new Message(), factory); await exchange.DisposeAsync(); await exchange.DisposeAsync(); // Second call should be safe } [Fact] public async Task DisposeAsync_Clone_DoesNotAffectOriginal() { var services = new ServiceCollection() .AddScoped() .BuildServiceProvider(); var factory = services.GetRequiredService(); var original = Exchange.Create(new Message(), factory); var clone = original.Clone(); await clone.DisposeAsync(); clone.ServiceProvider.Should().BeNull(); original.ServiceProvider.Should().NotBeNull(); } [Fact] public async Task DisposeAsync_DisposesRegisteredDisposables() { var services = new ServiceCollection() .AddScoped() .BuildServiceProvider(); var factory = services.GetRequiredService(); var exchange = Exchange.Create(new Message(), factory); var svc = exchange.ServiceProvider!.GetRequiredService(); svc.IsDisposed.Should().BeFalse(); await exchange.DisposeAsync(); svc.IsDisposed.Should().BeTrue(); } // ── IExchange default interface tests ── [Fact] public void IExchange_ServiceProvider_DefaultsToNull() { IExchange exchange = Substitute.For(); // Default interface member returns null // NSubstitute won't call the default impl, so we verify via concrete var concreteExchange = new Exchange(); ((IExchange)concreteExchange).ServiceProvider.Should().BeNull(); } [Fact] public async Task IExchange_DisposeAsync_DefaultIsNoop() { // The default IAsyncDisposable.DisposeAsync on IExchange returns default ValueTask IAsyncDisposable exchange = new Exchange(); await exchange.DisposeAsync(); // Should not throw } // ── Helpers ── private class Marker { } private class DisposableService : IDisposable { public bool IsDisposed { get; private set; } public void Dispose() => IsDisposed = true; } } Path: redb-route/tests/redb.Route.Tests/Core/ExchangeSnapshotTests.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/ExchangeSnapshotTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Tests.Core; /// /// Tests for the checkpoint-snapshot primitive / /// : unlike the body is deep-copied, /// so a snapshot is frozen against later in-place mutation of the payload. /// public class ExchangeSnapshotTests { // A mutable reference body that opts into deep copy via ICloneable. private sealed class Cart : ICloneable { public List Items { get; init; } = []; public object Clone() => new Cart { Items = [.. Items] }; } [Fact] public void Snapshot_FreezesMutableBody_CloneDoesNot() { var cart = new Cart { Items = { "a" } }; var ex = new Exchange(new Message(cart)); var snap = ex.Snapshot(); var clone = ex.Clone(); // mutate the live body AFTER capturing cart.Items.Add("b"); ((Cart)snap.In.Body!).Items.Should().ContainSingle().And.Contain("a"); // snapshot frozen ((Cart)clone.In.Body!).Items.Should().HaveCount(2); // clone shares reference } [Fact] public void Snapshot_CopiesByteArray() { var bytes = new byte[] { 1, 2, 3 }; var ex = new Exchange(new Message(bytes)); var snap = ex.Snapshot(); bytes[0] = 99; ((byte[])snap.In.Body!).Should().Equal(1, 2, 3); } [Theory] [InlineData("hello")] [InlineData(42)] [InlineData(true)] public void Snapshot_SharesImmutableBodies_AsIs(object body) { var ex = new Exchange(new Message(body)); var snap = ex.Snapshot(); snap.In.Body.Should().Be(body); } [Fact] public void Snapshot_ThrowsForNonSnapshotableBody() { // plain POCO, not ICloneable, not immutable var ex = new Exchange(new Message(new { Name = "x" })); var act = () => ex.Snapshot(); act.Should().Throw().WithMessage("*cannot deep-copy*"); } [Fact] public void Snapshot_DeepCopiesOut_AndPreservesMetadata() { var ex = new Exchange(new Message("in-body")) { Pattern = ExchangePattern.InOut, RouteId = "route-x", Out = new Message(new byte[] { 7, 8 }) }; ex.Properties["k"] = "v"; var snap = ex.Snapshot(); snap.Pattern.Should().Be(ExchangePattern.InOut); snap.RouteId.Should().Be("route-x"); snap.ExchangeId.Should().Be(ex.ExchangeId); // snapshot keeps identity, like Clone snap.Properties["k"].Should().Be("v"); ((byte[])snap.Out!.Body!).Should().Equal(7, 8); } [Fact] public void Snapshot_HeaderValuesShared_LikeClone() { var msg = new Message("body"); msg.Headers["h"] = "hv"; var ex = new Exchange(msg); var snap = ex.Snapshot(); snap.In.Headers["h"].Should().Be("hv"); snap.In.Headers.Should().NotBeSameAs(ex.In.Headers); // new container } [Fact] public void Snapshot_NullBody_Ok() { var ex = new Exchange(new Message((object?)null)); var snap = ex.Snapshot(); snap.In.Body.Should().BeNull(); } } Path: redb-route/tests/redb.Route.Tests/Core/ExchangeTests.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/ExchangeTests.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using AwesomeAssertions; namespace redb.Route.Tests.Core; public class ExchangeTests { [Fact] public void NewExchange_HasEmptyMessage() { var ex = new Exchange(); ex.In.Should().NotBeNull(); ex.In.Body.Should().BeNull(); } [Fact] public void Constructor_WithMessage_SetsIn() { var msg = new Message("hello"); var ex = new Exchange(msg); ex.In.Body.Should().Be("hello"); } [Fact] public void Out_IsNullByDefault() { var ex = new Exchange(); ex.Out.Should().BeNull(); ex.HasOut.Should().BeFalse(); } [Fact] public void Out_WhenSet_HasOutIsTrue() { var ex = new Exchange(); ex.Out = new Message("response"); ex.HasOut.Should().BeTrue(); ex.Out!.Body.Should().Be("response"); } [Fact] public void Pattern_DefaultIsInOnly() { var ex = new Exchange(); ex.Pattern.Should().Be(ExchangePattern.InOnly); } [Fact] public void Properties_AreCaseInsensitive() { var ex = new Exchange(); ex.Properties["RouteId"] = "test"; ex.Properties["routeid"].Should().Be("test"); } [Fact] public void GetProperty_ReturnsTypedValue() { var ex = new Exchange(); ex.Properties["retries"] = 3; ex.GetProperty("retries").Should().Be(3); } [Fact] public void GetProperty_ConvertsStringToInt() { var ex = new Exchange(); ex.Properties["retries"] = "5"; ex.GetProperty("retries").Should().Be(5); } [Fact] public void GetProperty_MissingKey_ReturnsDefault() { var ex = new Exchange(); ex.GetProperty("missing").Should().Be(0); } [Fact] public void Stop_SetsIsStopped() { var ex = new Exchange(); ex.IsStopped.Should().BeFalse(); ex.Stop(); ex.IsStopped.Should().BeTrue(); } [Fact] public void Exception_DefaultIsNull() { var ex = new Exchange(); ex.Exception.Should().BeNull(); ex.ExceptionHandled.Should().BeFalse(); } [Fact] public void Clone_CopiesAllState() { var ex = new Exchange(new Message("data")); ex.Pattern = ExchangePattern.InOut; ex.RouteId = "route-1"; ex.Properties["key"] = "value"; ex.Out = new Message("response"); var clone = ex.Clone(); clone.In.Body.Should().Be("data"); clone.Out!.Body.Should().Be("response"); clone.Pattern.Should().Be(ExchangePattern.InOut); clone.RouteId.Should().Be("route-1"); clone.Properties["key"].Should().Be("value"); clone.Should().NotBeSameAs(ex); } [Fact] public void Clone_IsDeepCopy_PropertiesIndependent() { var ex = new Exchange(); ex.Properties["key"] = "original"; var clone = ex.Clone(); clone.Properties["key"] = "changed"; ex.Properties["key"].Should().Be("original"); } // ── Java-style API tests ── [Fact] public void JavaStyle_GetIn_ReturnsIn() { IExchange ex = new Exchange(new Message("test")); ex.getIn().Body.Should().Be("test"); } [Fact] public void JavaStyle_GetOut_ReturnsOut() { IExchange ex = new Exchange(); ex.Out = new Message("resp"); ex.getOut()!.Body.Should().Be("resp"); } [Fact] public void JavaStyle_GetSetProperty() { IExchange ex = new Exchange(); ex.setProperty("key", "val"); ex.getProperty("key").Should().Be("val"); } [Fact] public void JavaStyle_IsStop_ReturnsFalse() { IExchange ex = new Exchange(); ex.isStop().Should().BeFalse(); } [Fact] public void JavaStyle_RouteStop_StopsExchange() { IExchange ex = new Exchange(); ex.RouteStop(); ex.IsStopped.Should().BeTrue(); ex.isStop().Should().BeTrue(); } [Fact] public void JavaStyle_Copy_ClonesExchange() { IExchange ex = new Exchange(new Message("data")); var clone = ex.copy(); clone.In.Body.Should().Be("data"); clone.Should().NotBeSameAs(ex); } } Path: redb-route/tests/redb.Route.Tests/Core/GracefulShutdownIntegrationTests.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/GracefulShutdownIntegrationTests.cs ---- using redb.Route.Abstractions; using redb.Route.Configuration; using redb.Route.Core; namespace redb.Route.Tests.Core; /// /// Integration tests covering graceful shutdown scenarios across Phases 2-5. /// Uses direct:// endpoints for full pipeline testing without external infrastructure. /// public sealed class GracefulShutdownIntegrationTests { // ═══════════════════════════════════════════════════════════════════ // Phase 2: InflightDrainGuard — drain under load // ═══════════════════════════════════════════════════════════════════ [Fact] public async Task Drain_InflightExchangesComplete_BeforeStopReturns() { // Arrange — route that takes 200ms to process each message var processedIds = new List(); var processingStarted = new TaskCompletionSource(); var ctx = new RouteContext(options: new RouteEngineOptions { EnableTelemetry = false, EnableMetrics = false, ShutdownTimeout = TimeSpan.FromSeconds(10) }); ctx.AddRoutes(r => { r.From("direct://drain-test") .RouteId("drain-route") .Process(async (e, ct) => { processingStarted.TrySetResult(); await Task.Delay(200, ct); lock (processedIds) processedIds.Add(e.ExchangeId); }); }); await ctx.Start(); var producer = ctx.GetEndpoint("direct://drain-test").CreateProducer(); await producer.Start(); // Act — send message, then immediately stop while it's still processing var exchange = new Exchange(new Message("inflight-msg")); var processTask = producer.Process(exchange, CancellationToken.None); // Wait for processing to actually start await processingStarted.Task; // Stop should wait for the inflight exchange to complete await ctx.Stop(); await processTask; // Assert — the exchange must have completed processing before stop returned processedIds.Should().Contain(exchange.ExchangeId); ctx.InflightRepository.Browse().Should().BeEmpty("all inflight should be drained"); await ctx.DisposeAsync(); } [Fact] public async Task Drain_MultipleInflightExchanges_AllCompleteBeforeStop() { var processedCount = 0; var allStarted = new CountdownEvent(3); var ctx = new RouteContext(options: new RouteEngineOptions { EnableTelemetry = false, EnableMetrics = false, ShutdownTimeout = TimeSpan.FromSeconds(10) }); ctx.AddRoutes(r => { r.From("direct://drain-multi") .RouteId("drain-multi") .Process(async (e, ct) => { allStarted.Signal(); await Task.Delay(300, ct); Interlocked.Increment(ref processedCount); }); }); await ctx.Start(); var producer = ctx.GetEndpoint("direct://drain-multi").CreateProducer(); await producer.Start(); // Act — send 3 messages concurrently var tasks = Enumerable.Range(0, 3).Select(_ => producer.Process(new Exchange(new Message("msg")), CancellationToken.None)).ToArray(); // Wait for all to start processing allStarted.Wait(TimeSpan.FromSeconds(5)); // Stop while all 3 are in flight await ctx.Stop(); await Task.WhenAll(tasks); // Assert processedCount.Should().Be(3, "all inflight exchanges should complete before stop"); ctx.InflightRepository.Browse().Should().BeEmpty(); await ctx.DisposeAsync(); } [Fact] public async Task Drain_InflightRepository_TracksExchangesDuringProcessing() { var processingReached = new TaskCompletionSource(); var canFinish = new TaskCompletionSource(); var ctx = new RouteContext(options: new RouteEngineOptions { EnableTelemetry = false, EnableMetrics = false }); ctx.AddRoutes(r => { r.From("direct://inflight-track") .RouteId("inflight-track") .Process(async (e, ct) => { processingReached.TrySetResult(); await canFinish.Task; }); }); await ctx.Start(); var producer = ctx.GetEndpoint("direct://inflight-track").CreateProducer(); await producer.Start(); // Act — send message, wait for processing to start var processTask = producer.Process(new Exchange(new Message("tracked")), CancellationToken.None); await processingReached.Task; // Assert — inflight repo shows 1 exchange while processing ctx.InflightRepository.Browse("inflight-track").Should().HaveCount(1); // Let it finish canFinish.SetResult(); await processTask; // After completion — inflight is empty ctx.InflightRepository.Browse("inflight-track").Should().BeEmpty(); await ctx.Stop(); await ctx.DisposeAsync(); } // ═══════════════════════════════════════════════════════════════════ // Phase 3: ShutdownTimeout — enforcement under real pipeline // ═══════════════════════════════════════════════════════════════════ [Fact] public async Task ShutdownTimeout_ForcesStop_WhenProcessingExceedsTimeout() { var ctx = new RouteContext(options: new RouteEngineOptions { EnableTelemetry = false, EnableMetrics = false, ShutdownTimeout = TimeSpan.FromMilliseconds(300) }); ctx.AddRoutes(r => { r.From("direct://slow-shutdown") .RouteId("slow-shutdown") .Process(async (e, ct) => { // Very slow processing — should be force-cancelled by ShutdownTimeout await Task.Delay(TimeSpan.FromMinutes(5), ct); }); }); await ctx.Start(); var producer = ctx.GetEndpoint("direct://slow-shutdown").CreateProducer(); await producer.Start(); // Start slow processing _ = producer.Process(new Exchange(new Message("slow")), CancellationToken.None); await Task.Delay(50); // let processing start // Act — Stop with timeout var sw = System.Diagnostics.Stopwatch.StartNew(); await ctx.Stop(); sw.Stop(); // Assert — should complete roughly within ShutdownTimeout, not 5 minutes sw.Elapsed.Should().BeLessThan(TimeSpan.FromSeconds(5), "shutdown should be forced after ShutdownTimeout, not wait for slow processing"); await ctx.DisposeAsync(); } [Fact] public async Task ShutdownTimeout_AllowsCompletion_WhenProcessingFinishesInTime() { var completed = false; var ctx = new RouteContext(options: new RouteEngineOptions { EnableTelemetry = false, EnableMetrics = false, ShutdownTimeout = TimeSpan.FromSeconds(5) }); ctx.AddRoutes(r => { r.From("direct://fast-shutdown") .RouteId("fast-shutdown") .Process(async (e, ct) => { await Task.Delay(50, ct); completed = true; }); }); await ctx.Start(); var producer = ctx.GetEndpoint("direct://fast-shutdown").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("fast")), CancellationToken.None); await ctx.Stop(); // Assert — processing completed gracefully completed.Should().BeTrue("processing finished within ShutdownTimeout"); await ctx.DisposeAsync(); } // ═══════════════════════════════════════════════════════════════════ // Phase 5: ProcessingTimeout — per-exchange timeout integration // ═══════════════════════════════════════════════════════════════════ [Fact] public async Task ProcessingTimeout_FiresOnExchangeTimedOut_ThroughFullPipeline() { var timedOutExchangeIds = new List(); var listener = new TimeoutTrackingListener(timedOutExchangeIds); var ctx = new RouteContext(options: new RouteEngineOptions { EnableTelemetry = false, EnableMetrics = false }); ctx.AddLifecycleListener(listener); ctx.AddRoutes(r => { r.From("direct://timeout-pipeline") .RouteId("timeout-pipeline") .ProcessingTimeout(TimeSpan.FromMilliseconds(50)) .Process(async (e, ct) => { await Task.Delay(TimeSpan.FromSeconds(10), ct); }); r.OnException() .Process(e => e.ExceptionHandled = true); }); await ctx.Start(); var producer = ctx.GetEndpoint("direct://timeout-pipeline").CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("will-timeout")); await producer.Process(exchange, CancellationToken.None); await ctx.Stop(); await ctx.DisposeAsync(); // Assert — lifecycle listener received the timeout event timedOutExchangeIds.Should().Contain(exchange.ExchangeId); // Assert — exchange has the timeout properties set exchange.Exception.Should().BeOfType(); ((ExchangeTimedOutException)exchange.Exception!).RouteId.Should().Be("timeout-pipeline"); } [Fact] public async Task ProcessingTimeout_InflightCleanedUp_AfterTimeout() { var ctx = new RouteContext(options: new RouteEngineOptions { EnableTelemetry = false, EnableMetrics = false }); ctx.AddRoutes(r => { r.From("direct://timeout-inflight") .RouteId("timeout-inflight") .ProcessingTimeout(TimeSpan.FromMilliseconds(50)) .Process(async (e, ct) => { await Task.Delay(TimeSpan.FromSeconds(10), ct); }); r.OnException() .Process(e => e.ExceptionHandled = true); }); await ctx.Start(); var producer = ctx.GetEndpoint("direct://timeout-inflight").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("timeout")), CancellationToken.None); // Assert — inflight was registered and unregistered despite timeout ctx.InflightRepository.Browse("timeout-inflight").Should().BeEmpty( "inflight entry should be cleaned up after timeout"); await ctx.Stop(); await ctx.DisposeAsync(); } [Fact] public async Task ProcessingTimeout_NormalProcessing_NoTimeout() { var processed = false; var ctx = new RouteContext(options: new RouteEngineOptions { EnableTelemetry = false, EnableMetrics = false }); ctx.AddRoutes(r => { r.From("direct://fast-processing") .RouteId("fast-route") .ProcessingTimeout(TimeSpan.FromSeconds(5)) .Process(e => { processed = true; }); }); await ctx.Start(); var producer = ctx.GetEndpoint("direct://fast-processing").CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("fast")); await producer.Process(exchange, CancellationToken.None); // Assert — no timeout, clean processing processed.Should().BeTrue(); exchange.Exception.Should().BeNull(); ctx.InflightRepository.Browse("fast-route").Should().BeEmpty(); await ctx.Stop(); await ctx.DisposeAsync(); } // ═══════════════════════════════════════════════════════════════════ // Cross-phase: End-to-end graceful shutdown scenario // ═══════════════════════════════════════════════════════════════════ [Fact] public async Task EndToEnd_GracefulShutdown_AllPhasesWork() { // Tests: ExchangeId tracking (P1), Drain (P2), ShutdownTimeout (P3), // RouteStatus (P4), ProcessingTimeout (P5), Lifecycle events (P6) var listener = new FullLifecycleListener(); var ctx = new RouteContext(options: new RouteEngineOptions { EnableTelemetry = false, EnableMetrics = false, ShutdownTimeout = TimeSpan.FromSeconds(5), DefaultProcessingTimeout = TimeSpan.FromSeconds(2) }); ctx.AddLifecycleListener(listener); ctx.AddRoutes(r => { r.From("direct://e2e-fast") .RouteId("e2e-fast") .Process(async (e, ct) => { await Task.Delay(50, ct); }); r.From("direct://e2e-slow") .RouteId("e2e-slow") .ProcessingTimeout(TimeSpan.FromMilliseconds(80)) .Process(async (e, ct) => { await Task.Delay(TimeSpan.FromSeconds(30), ct); }); r.OnException() .Process(e => e.ExceptionHandled = true); }); await ctx.Start(); // P4: RouteStatus — both started ctx.GetRoute("e2e-fast")!.Status.Should().Be(RouteStatus.Started); ctx.GetRoute("e2e-slow")!.Status.Should().Be(RouteStatus.Started); // P6: Lifecycle — started events listener.Events.Should().Contain("Started:e2e-fast"); listener.Events.Should().Contain("Started:e2e-slow"); var fastProducer = ctx.GetEndpoint("direct://e2e-fast").CreateProducer(); await fastProducer.Start(); var slowProducer = ctx.GetEndpoint("direct://e2e-slow").CreateProducer(); await slowProducer.Start(); // P1: ExchangeId — each exchange gets unique id var ex1 = new Exchange(new Message("fast")); var ex2 = new Exchange(new Message("slow")); ex1.ExchangeId.Should().NotBe(ex2.ExchangeId); // Send fast + slow messages await fastProducer.Process(ex1, CancellationToken.None); _ = slowProducer.Process(ex2, CancellationToken.None); await Task.Delay(20); // let slow start processing // P5: slow exchange should timeout await Task.Delay(200); // exceed the 80ms timeout // P6: timeout event should have fired listener.TimedOutIds.Should().NotBeEmpty("slow exchange should have timed out"); // P2+P3: Stop should drain fast, force-cancel slow await ctx.Stop(); // P2: inflight drained ctx.InflightRepository.Browse().Should().BeEmpty(); // P6: lifecycle events (routes cleared after stop, but listener captured events) listener.Events.Should().Contain("Suspending:e2e-fast"); listener.Events.Should().Contain("Stopped:e2e-fast"); listener.Events.Should().Contain("Suspending:e2e-slow"); listener.Events.Should().Contain("Stopped:e2e-slow"); await ctx.DisposeAsync(); } // ───── Helpers ───── private sealed class TimeoutTrackingListener : IRouteLifecycleListener { private readonly List _timedOutIds; public TimeoutTrackingListener(List timedOutIds) => _timedOutIds = timedOutIds; public Task OnExchangeTimedOut(string routeId, string exchangeId, TimeSpan elapsed, CancellationToken ct) { lock (_timedOutIds) _timedOutIds.Add(exchangeId); return Task.CompletedTask; } } private sealed class FullLifecycleListener : IRouteLifecycleListener { public List Events { get; } = []; public List TimedOutIds { get; } = []; public Task OnRouteStarted(string routeId, CancellationToken ct) { lock (Events) Events.Add($"Started:{routeId}"); return Task.CompletedTask; } public Task OnRouteStopped(string routeId, CancellationToken ct) { lock (Events) Events.Add($"Stopped:{routeId}"); return Task.CompletedTask; } public Task OnRouteSuspending(string routeId, CancellationToken ct) { lock (Events) Events.Add($"Suspending:{routeId}"); return Task.CompletedTask; } public Task OnRouteErrored(string routeId, Exception ex, CancellationToken ct) { lock (Events) Events.Add($"Errored:{routeId}"); return Task.CompletedTask; } public Task OnExchangeTimedOut(string routeId, string exchangeId, TimeSpan elapsed, CancellationToken ct) { lock (TimedOutIds) TimedOutIds.Add(exchangeId); return Task.CompletedTask; } } } Path: redb-route/tests/redb.Route.Tests/Core/GracefulShutdownRobustnessTests.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/GracefulShutdownRobustnessTests.cs ---- using redb.Route.Abstractions; using redb.Route.Configuration; using redb.Route.Core; namespace redb.Route.Tests.Core; /// /// Integration tests validating robustness fixes: /// Start/Stop race conditions (#1), idempotency, restart safety (#8). /// public sealed class GracefulShutdownRobustnessTests { // ═══════════════════════════════════════════════════════════════════ // Fix #1: _routeLock — concurrent Start/Stop must not deadlock // ═══════════════════════════════════════════════════════════════════ [Fact] public async Task ConcurrentStartStop_DoesNotDeadlockOrThrow() { var ctx = new RouteContext(options: new RouteEngineOptions { EnableTelemetry = false, EnableMetrics = false, ShutdownTimeout = TimeSpan.FromSeconds(5) }); ctx.AddRoutes(r => { r.From("direct://race-test") .RouteId("race-route") .Process(async (e, ct) => await Task.Delay(10, ct)); }); var tasks = new List(); for (int i = 0; i < 10; i++) { tasks.Add(Task.Run(async () => { try { await ctx.Start(); } catch (OperationCanceledException) { } })); tasks.Add(Task.Run(async () => { try { await ctx.Stop(); } catch (OperationCanceledException) { } })); } var allDone = Task.WhenAll(tasks); var completed = await Task.WhenAny(allDone, Task.Delay(TimeSpan.FromSeconds(30))); completed.Should().Be(allDone, "concurrent Start/Stop should complete without deadlock"); await ctx.DisposeAsync(); } [Fact] public async Task DoubleStart_IsIdempotent() { var ctx = new RouteContext(options: new RouteEngineOptions { EnableTelemetry = false, EnableMetrics = false }); ctx.AddRoutes(r => { r.From("direct://double-start") .RouteId("double-start") .Process(e => { }); }); await ctx.Start(); await ctx.Start(); // second call — must be no-op ctx.GetRoute("double-start")!.Status.Should().Be(RouteStatus.Started); await ctx.Stop(); await ctx.DisposeAsync(); } [Fact] public async Task DoubleStop_IsIdempotent() { var ctx = new RouteContext(options: new RouteEngineOptions { EnableTelemetry = false, EnableMetrics = false }); ctx.AddRoutes(r => { r.From("direct://double-stop") .RouteId("double-stop") .Process(e => { }); }); await ctx.Start(); await ctx.Stop(); await ctx.Stop(); // second call — must not throw await ctx.DisposeAsync(); } // ═══════════════════════════════════════════════════════════════════ // Fix #8: Compile temp list — restart re‑compiles cleanly // ═══════════════════════════════════════════════════════════════════ [Fact] public async Task StartStopRestart_RoutesWorkAcrossRestarts() { var processedCount = 0; var ctx = new RouteContext(options: new RouteEngineOptions { EnableTelemetry = false, EnableMetrics = false, ShutdownTimeout = TimeSpan.FromSeconds(5) }); ctx.AddRoutes(r => { r.From("direct://restart-test") .RouteId("restart-route") .Process(e => Interlocked.Increment(ref processedCount)); }); // First cycle await ctx.Start(); var p1 = ctx.GetEndpoint("direct://restart-test").CreateProducer(); await p1.Start(); await p1.Process(new Exchange(new Message("msg1"))); await ctx.Stop(); // Second cycle — restart await ctx.Start(); var p2 = ctx.GetEndpoint("direct://restart-test").CreateProducer(); await p2.Start(); await p2.Process(new Exchange(new Message("msg2"))); await ctx.Stop(); processedCount.Should().Be(2, "both messages should be processed across restart cycles"); await ctx.DisposeAsync(); } [Fact] public async Task StopUnderLoad_DrainsAllInflight_BeforeReturning() { var processedCount = 0; var allStarted = new CountdownEvent(5); var ctx = new RouteContext(options: new RouteEngineOptions { EnableTelemetry = false, EnableMetrics = false, ShutdownTimeout = TimeSpan.FromSeconds(10) }); ctx.AddRoutes(r => { r.From("direct://load-drain") .RouteId("load-drain") .Process(async (e, ct) => { allStarted.Signal(); await Task.Delay(300, ct); Interlocked.Increment(ref processedCount); }); }); await ctx.Start(); var producer = ctx.GetEndpoint("direct://load-drain").CreateProducer(); await producer.Start(); // Fire 5 concurrent messages var tasks = Enumerable.Range(0, 5) .Select(_ => producer.Process(new Exchange(new Message("msg")), CancellationToken.None)) .ToArray(); allStarted.Wait(TimeSpan.FromSeconds(5)); // Stop while all 5 are in-flight await ctx.Stop(); await Task.WhenAll(tasks); processedCount.Should().Be(5, "all in-flight exchanges must complete before Stop returns"); ctx.InflightRepository.Browse().Should().BeEmpty(); await ctx.DisposeAsync(); } } Path: redb-route/tests/redb.Route.Tests/Core/InProcessRouteIdTests.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/InProcessRouteIdTests.cs ---- using AwesomeAssertions; using Microsoft.Extensions.DependencyInjection; using redb.Route.Abstractions; using redb.Route.Components; using redb.Route.Core; namespace redb.Route.Tests.Core; /// /// A direct:/direct-vm: call runs the target route's pipeline on the CALLER's exchange, and the target's /// first step stamps exchange.RouteId, which nothing used to restore: after to("direct:callee") /// the caller carried the callee's id, so the caller's route span and its later step metrics were attributed /// to the callee. The caller must get its own id back, as it already does for IExchange.Context. /// public class InProcessRouteIdTests : IAsyncLifetime { private readonly ServiceProvider _sp; public InProcessRouteIdTests() { var services = new ServiceCollection(); services.AddSingleton(new SharedVmRegistry()); _sp = services.BuildServiceProvider(); } public Task InitializeAsync() => Task.CompletedTask; public Task DisposeAsync() { _sp.Dispose(); GC.SuppressFinalize(this); return Task.CompletedTask; } private RouteContext New(string name) => new(_sp, $"{name}-{Guid.NewGuid():N}"); private static async Task SendAsync(RouteContext ctx, string uri) { var producer = ctx.GetEndpoint(uri).CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("x"))); } [Fact] public async Task Direct_call_gives_the_caller_its_route_id_back() { await using var ctx = New("routeid-direct"); string? insideCallee = null; string? afterCall = null; ctx.AddRoutes(r => { r.From("direct://callee").RouteId("callee").Process(e => insideCallee = e.RouteId); r.From("direct://caller").RouteId("caller").To("direct://callee").Process(e => afterCall = e.RouteId); }); await ctx.Start(); await SendAsync(ctx, "direct://caller"); insideCallee.Should().Be("callee", "inside the sub-route the current route is the sub-route"); afterCall.Should().Be("caller", "after the direct: call the caller is attributed to its own route again"); } [Fact] public async Task Nested_direct_calls_restore_each_frame() { await using var ctx = New("routeid-nested"); string? insideC = null; string? insideB = null; string? afterB = null; ctx.AddRoutes(r => { r.From("direct://c").RouteId("c").Process(e => insideC = e.RouteId); r.From("direct://b").RouteId("b").To("direct://c").Process(e => insideB = e.RouteId); r.From("direct://a").RouteId("a").To("direct://b").Process(e => afterB = e.RouteId); }); await ctx.Start(); await SendAsync(ctx, "direct://a"); insideC.Should().Be("c"); insideB.Should().Be("b", "when C returns, B is the current route again"); afterB.Should().Be("a", "when B returns, A is the current route again"); } [Fact] public async Task A_failing_sub_route_still_gives_the_caller_its_route_id_back() { await using var ctx = New("routeid-fail"); string? caughtInCaller = null; ctx.AddRoutes(r => { r.From("direct://boom").RouteId("boom").Process(_ => throw new InvalidOperationException("boom")); r.From("direct://caller").RouteId("caller") .TryCatch() .To("direct://boom") .Catch() .Process(e => caughtInCaller = e.RouteId) .EndTryCatch(); }); await ctx.Start(); await SendAsync(ctx, "direct://caller"); caughtInCaller.Should().Be("caller", "the caller's id is restored on the way out, before its own error handler runs"); } [Fact] public async Task DirectVm_call_gives_the_caller_its_route_id_back() { await using var ctx = New("routeid-directvm"); string? afterCall = null; ctx.AddRoutes(r => { r.From("direct-vm://callee").RouteId("vm-callee").Process(_ => { }); r.From("direct://caller").RouteId("vm-caller").To("direct-vm://callee").Process(e => afterCall = e.RouteId); }); await ctx.Start(); await SendAsync(ctx, "direct://caller"); afterCall.Should().Be("vm-caller"); } } Path: redb-route/tests/redb.Route.Tests/Core/InflightReentryTests.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/InflightReentryTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Components; using redb.Route.Core; namespace redb.Route.Tests.Core; /// /// An exchange is in flight until its last entry into a route has finished. A copy keeps the exchange id, so an exchange /// entering a route again (a route calling itself through direct:, parallel branches through the same sub-route) /// registers the same id more than once; the repository counts the entries, and the first to finish no longer takes /// the exchange off while the others still run. It used to: the dashboard showed nothing in flight under load. /// public class InflightReentryTests { private static InflightExchange Entry(string id) => new(id, "route-1", DateTime.UtcNow, Environment.CurrentManagedThreadId, "direct:in"); [Fact] public void An_exchange_registered_twice_stays_in_flight_until_both_entries_finish() { var repository = new DefaultInflightRepository(); repository.Register(Entry("ex-1")); repository.Register(Entry("ex-1")); repository.Unregister("ex-1"); repository.Count.Should().Be(1, "the other entry is still running"); repository.Browse().Should().ContainSingle(); repository.Unregister("ex-1"); repository.Count.Should().Be(0); } [Fact] public async Task A_route_re_entered_by_the_same_exchange_shows_it_in_flight_until_the_outer_run_ends() { await using var context = new RouteContext($"inflight-reentry-{Guid.NewGuid():N}"); context.AddComponent(new DirectComponent()); int? inFlightAfterInnerRun = null; context.AddRoutes(r => r.From("direct://inflight-reentry").RouteId("inflight-reentry") .Choice() .When(e => e.In.GetHeader("depth") == "outer") .SetHeader("depth", "inner") .To("direct://inflight-reentry") .Process(_ => inFlightAfterInnerRun = context.InflightRepository.CountByRoute("inflight-reentry")) .End()); await context.Start(); var template = new ProducerTemplate(context); template.Start(); var message = new Message("x"); message.Headers["depth"] = "outer"; await template.SendAsync("direct://inflight-reentry", message); await template.DisposeAsync(); inFlightAfterInnerRun.Should().Be(1, "the outer run of the exchange is still in flight"); } } Path: redb-route/tests/redb.Route.Tests/Core/InflightWaitTests.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/InflightWaitTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.ErrorHandling; namespace redb.Route.Tests.Core; /// /// The planned waits of the engine are marked in the in-flight registry (), so a /// monitor such as the Tsak watchdog does not take an exchange that waits for its redelivery, or in a delay step, for a /// hung one. After the wait is set and the mark is gone. /// public sealed class InflightWaitTests : IAsyncLifetime { private static readonly TimeSpan Wait = TimeSpan.FromMilliseconds(400); private readonly RouteContext _context = new(); public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() => await _context.DisposeAsync(); /// Runs and returns the in-flight entry seen while the exchange waited. private async Task WaitingEntryDuring(Func send) { var running = send(); InflightExchange? seen = null; var deadline = DateTime.UtcNow.AddSeconds(5); while (seen is null && !running.IsCompleted && DateTime.UtcNow < deadline) { seen = _context.InflightRepository.Browse().FirstOrDefault(e => e.WaitingUntil is not null); if (seen is null) await Task.Delay(5); } await running; return seen; } private async Task SendAsync(string uri) { var producer = _context.GetEndpoint(uri).CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message { Body = "x" })); } [Fact] public async Task OnException_redelivery_delay_is_marked_as_a_wait() { var attempts = 0; _context.AddRoutes(r => { r.OnException().MaximumRedeliveries(1).RedeliveryDelay(Wait).Handled(); r.From("direct://redeliver").Process(_ => { if (Interlocked.Increment(ref attempts) == 1) throw new InvalidOperationException("first attempt"); }); }); await _context.Start(); var seen = await WaitingEntryDuring(() => SendAsync("direct://redeliver")); seen.Should().NotBeNull("the exchange waits for its redelivery"); seen!.WaitingUntil!.Value.Should().BeAfter(seen.StartedAt); attempts.Should().Be(2); } [Fact] public async Task Delay_step_is_marked_as_a_wait() { _context.AddRoutes(r => r.From("direct://delayed").Delay(Wait).Process(_ => { })); await _context.Start(); var seen = await WaitingEntryDuring(() => SendAsync("direct://delayed")); seen.Should().NotBeNull("a delay step holds the exchange by design"); } [Fact] public async Task Retry_delay_is_marked_as_a_wait() { var attempts = 0; _context.AddRoutes(r => r.From("direct://retried") .Transaction().Retry(1, Wait) .Process(_ => { if (Interlocked.Increment(ref attempts) == 1) throw new InvalidOperationException("first attempt"); }) .EndTransaction()); await _context.Start(); var seen = await WaitingEntryDuring(() => SendAsync("direct://retried")); seen.Should().NotBeNull("the retry waits before its next attempt"); attempts.Should().Be(2); } [Fact] public async Task Dead_letter_redelivery_delay_is_marked_and_ends_with_LastWaitEndedAt() { var attempts = 0; var inner = new LambdaProcessor(_ => { if (Interlocked.Increment(ref attempts) == 1) throw new InvalidOperationException("first attempt"); return Task.CompletedTask; }); var sut = new DeadLetterProcessor(inner, new LambdaProcessor(_ => Task.CompletedTask), RetryPolicy.Fixed(1, Wait)); var exchange = new Exchange(new Message { Body = "x" }) { Context = _context }; _context.InflightRepository.Register(new InflightExchange(exchange.ExchangeId, "dlc", DateTime.UtcNow, 1, null)); var seen = await WaitingEntryDuring(() => sut.Process(exchange)); seen.Should().NotBeNull("the dead letter channel waits before its redelivery"); var after = _context.InflightRepository.Browse().Single(); after.WaitingUntil.Should().BeNull("the mark is removed when the wait ends"); after.LastWaitEndedAt.Should().NotBeNull(); } [Fact] public void A_repository_of_ones_own_keeps_working_through_the_default_BeginWait() { IInflightRepository custom = new CountingOnlyRepository(); using var wait = custom.BeginWait("any", Wait); wait.Should().NotBeNull(); } private sealed class LambdaProcessor(Func body) : IProcessor { public Task Process(IExchange exchange, CancellationToken ct = default) => body(exchange); } /// A third-party repository written before BeginWait existed. private sealed class CountingOnlyRepository : IInflightRepository { public void Register(InflightExchange entry) { } public void Unregister(string exchangeId) { } public IReadOnlyList Browse() => []; public IReadOnlyList Browse(string routeId) => []; public int Count => 0; public int CountByRoute(string routeId) => 0; } } Path: redb-route/tests/redb.Route.Tests/Core/LifecycleListenerReviewTests.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/LifecycleListenerReviewTests.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.TestKit; namespace redb.Route.Tests.Core; /// /// Code review 2026-09-01: the listener list is enumerated per exchange, so registering a listener /// while exchanges flow (NotifyBuilder on a running context, a listener adding another from a /// callback) must never race that enumeration. Before, a plain List threw "Collection was modified" /// out of the notification and failed an unrelated in-flight message. /// public class LifecycleListenerReviewTests { [Fact] public async Task AListenerMayRegisterAnotherListener_FromAnExchangeCallback() { await using var ctx = new RouteContext().AddRoutes(b => b.From("direct://listen").To("mock://listen")); var added = 0; ctx.AddLifecycleListener(new RegisteringListener(() => { ctx.AddLifecycleListener(new Silent()); added++; })); await ctx.Start(); await ctx.SendBody("direct://listen", "x"); await ctx.SendBody("direct://listen", "y"); added.Should().Be(2); await ctx.Mock("mock://listen").ExpectMessageCount(2).AssertIsSatisfiedAsync(TimeSpan.FromSeconds(2)); } private sealed class RegisteringListener(Action onReceived) : IRouteLifecycleListener { public Task OnExchangeReceived(string routeId, IExchange exchange, CancellationToken ct) { onReceived(); return Task.CompletedTask; } } private sealed class Silent : IRouteLifecycleListener; } Path: redb-route/tests/redb.Route.Tests/Core/LifecycleListenerTests.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/LifecycleListenerTests.cs ---- using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Tests.Core; /// /// Tests for Phase 6: Route Lifecycle Events. /// public sealed class LifecycleListenerTests { private sealed class TestListener : IRouteLifecycleListener { public List Events { get; } = []; public Task OnRouteStarted(string routeId, CancellationToken ct) { Events.Add($"Started:{routeId}"); return Task.CompletedTask; } public Task OnRouteStopped(string routeId, CancellationToken ct) { Events.Add($"Stopped:{routeId}"); return Task.CompletedTask; } public Task OnRouteSuspending(string routeId, CancellationToken ct) { Events.Add($"Suspending:{routeId}"); return Task.CompletedTask; } public Task OnRouteErrored(string routeId, Exception ex, CancellationToken ct) { Events.Add($"Errored:{routeId}:{ex.GetType().Name}"); return Task.CompletedTask; } public Task OnExchangeTimedOut(string routeId, string exchangeId, TimeSpan elapsed, CancellationToken ct) { Events.Add($"TimedOut:{routeId}:{exchangeId}"); return Task.CompletedTask; } } [Fact] public async Task Listener_ReceivesStartedAndStopped_OnContextLifecycle() { var listener = new TestListener(); var ctx = new RouteContext(options: new Configuration.RouteEngineOptions { EnableTelemetry = false, EnableMetrics = false }); ctx.AddLifecycleListener(listener); ctx.AddRoutes(r => { r.From("direct://lifecycle-test") .RouteId("lc-route") .Process(e => { }); }); await ctx.Start(); await ctx.Stop(); await ctx.DisposeAsync(); listener.Events.Should().ContainInOrder( "Started:lc-route", "Suspending:lc-route", "Stopped:lc-route"); } [Fact] public async Task Listener_ReceivesStartedAndStopped_OnIndividualRoute() { var listener = new TestListener(); var ctx = new RouteContext(options: new Configuration.RouteEngineOptions { EnableTelemetry = false, EnableMetrics = false }); ctx.AddLifecycleListener(listener); ctx.AddRoutes(r => { r.From("direct://individual") .RouteId("ind-route") .AutoStart(false) .Process(e => { }); }); await ctx.Start(); // Route not started yet (AutoStart=false) listener.Events.Should().BeEmpty(); await ctx.StartRoute("ind-route"); listener.Events.Should().Contain("Started:ind-route"); await ctx.StopRoute("ind-route"); listener.Events.Should().Contain("Suspending:ind-route"); listener.Events.Should().Contain("Stopped:ind-route"); await ctx.Stop(); await ctx.DisposeAsync(); } [Fact] public async Task MultipleListeners_AllReceiveEvents() { var listener1 = new TestListener(); var listener2 = new TestListener(); var ctx = new RouteContext(options: new Configuration.RouteEngineOptions { EnableTelemetry = false, EnableMetrics = false }); ctx.AddLifecycleListener(listener1); ctx.AddLifecycleListener(listener2); ctx.AddRoutes(r => { r.From("direct://multi") .RouteId("multi-route") .Process(e => { }); }); await ctx.Start(); await ctx.Stop(); await ctx.DisposeAsync(); listener1.Events.Should().Contain("Started:multi-route"); listener2.Events.Should().Contain("Started:multi-route"); listener1.Events.Should().Contain("Stopped:multi-route"); listener2.Events.Should().Contain("Stopped:multi-route"); } [Fact] public async Task ListenerException_DoesNotBreakRouteLifecycle() { var goodListener = new TestListener(); var ctx = new RouteContext(options: new Configuration.RouteEngineOptions { EnableTelemetry = false, EnableMetrics = false }); // Bad listener that throws ctx.AddLifecycleListener(new ThrowingListener()); ctx.AddLifecycleListener(goodListener); ctx.AddRoutes(r => { r.From("direct://resilient") .RouteId("resilient-route") .Process(e => { }); }); // Should not throw despite bad listener await ctx.Start(); await ctx.Stop(); await ctx.DisposeAsync(); // Good listener should still receive all events goodListener.Events.Should().Contain("Started:resilient-route"); goodListener.Events.Should().Contain("Stopped:resilient-route"); } [Fact] public async Task Listener_ReceivesSuspending_BeforeStopped() { var listener = new TestListener(); var ctx = new RouteContext(options: new Configuration.RouteEngineOptions { EnableTelemetry = false, EnableMetrics = false }); ctx.AddLifecycleListener(listener); ctx.AddRoutes(r => { r.From("direct://order-test") .RouteId("order-route") .Process(e => { }); }); await ctx.Start(); await ctx.Stop(); await ctx.DisposeAsync(); var suspendIdx = listener.Events.IndexOf("Suspending:order-route"); var stoppedIdx = listener.Events.IndexOf("Stopped:order-route"); suspendIdx.Should().BeGreaterThanOrEqualTo(0, "Suspending event should fire"); stoppedIdx.Should().BeGreaterThanOrEqualTo(0, "Stopped event should fire"); suspendIdx.Should().BeLessThan(stoppedIdx, "Suspending should fire before Stopped"); } [Fact] public async Task Listener_ReceivesExchangeTimedOut() { var listener = new TestListener(); var ctx = new RouteContext(options: new Configuration.RouteEngineOptions { EnableTelemetry = false, EnableMetrics = false }); ctx.AddLifecycleListener(listener); ctx.AddRoutes(r => { r.From("direct://timeout-lifecycle") .RouteId("timeout-lc") .ProcessingTimeout(TimeSpan.FromMilliseconds(50)) .Process(async (e, ct) => { await Task.Delay(TimeSpan.FromSeconds(10), ct); }); r.OnException() .Process(e => e.ExceptionHandled = true); }); await ctx.Start(); var producer = ctx.GetEndpoint("direct://timeout-lifecycle").CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("test")); await producer.Process(exchange, CancellationToken.None); await ctx.Stop(); await ctx.DisposeAsync(); listener.Events.Should().Contain(e => e.StartsWith("TimedOut:timeout-lc:")); } [Fact] public async Task DefaultInterfaceMethods_AreNoOp() { // IRouteLifecycleListener default methods should not throw IRouteLifecycleListener listener = new MinimalListener(); await listener.OnRouteStarted("r1", CancellationToken.None); await listener.OnRouteStopped("r1", CancellationToken.None); await listener.OnRouteSuspending("r1", CancellationToken.None); await listener.OnRouteErrored("r1", new Exception("test"), CancellationToken.None); await listener.OnExchangeTimedOut("r1", "ex1", TimeSpan.FromSeconds(5), CancellationToken.None); } [Fact] public async Task LoggingLifecycleListener_DoesNotThrow() { var loggerFactory = Microsoft.Extensions.Logging.LoggerFactory.Create(b => { }); var logger = loggerFactory.CreateLogger("test"); var listener = new LoggingLifecycleListener(logger); await listener.OnRouteStarted("r1", CancellationToken.None); await listener.OnRouteStopped("r1", CancellationToken.None); await listener.OnRouteSuspending("r1", CancellationToken.None); await listener.OnRouteErrored("r1", new InvalidOperationException("boom"), CancellationToken.None); await listener.OnExchangeTimedOut("r1", "ex1", TimeSpan.FromSeconds(3), CancellationToken.None); } [Fact] public async Task AddLifecycleListener_ReturnsContextForChaining() { var ctx = new RouteContext(options: new Configuration.RouteEngineOptions { EnableTelemetry = false, EnableMetrics = false }); var result = ctx.AddLifecycleListener(new TestListener()); result.Should().BeSameAs(ctx); await ctx.DisposeAsync(); } // ── Helpers ── private sealed class ThrowingListener : IRouteLifecycleListener { public Task OnRouteStarted(string routeId, CancellationToken ct) => throw new InvalidOperationException("Boom from listener!"); public Task OnRouteStopped(string routeId, CancellationToken ct) => throw new InvalidOperationException("Boom from listener!"); public Task OnRouteSuspending(string routeId, CancellationToken ct) => throw new InvalidOperationException("Boom from listener!"); public Task OnRouteErrored(string routeId, Exception ex, CancellationToken ct) => throw new InvalidOperationException("Boom from listener!"); } /// /// Implements IRouteLifecycleListener without overriding any methods — tests default members. /// private sealed class MinimalListener : IRouteLifecycleListener { } } Path: redb-route/tests/redb.Route.Tests/Core/ListBodyTests.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/ListBodyTests.cs ---- using System.Text.Json.Nodes; using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Tests.Core; /// A list body at a producer: what is a list of messages, what is a plain list, and the exchange of one element. public class ListBodyTests { [Fact] public void A_list_of_messages_is_recognised() { var body = new List { new Message("a"), new Message("b") }; ListBody.Messages(body).Should().HaveCount(2); ListBody.IsPlainList(body).Should().BeFalse(); } [Theory] [MemberData(nameof(PlainLists))] public void A_collection_without_a_text_form_is_a_plain_list(object body) => ListBody.IsPlainList(body).Should().BeTrue(); public static TheoryData PlainLists => new() { new List { 1 }, new object[] { "a" }, new HashSet { "x" } }; [Theory] [MemberData(nameof(NotLists))] public void Text_bytes_and_collections_that_write_themselves_are_not_plain_lists(object body) { ListBody.IsPlainList(body).Should().BeFalse(); ListBody.Messages(body).Should().BeNull(); } public static TheoryData NotLists => new() { "text", new byte[] { 1 }, new JsonArray(1, 2), 42 }; [Fact] public void A_message_element_is_a_copy_with_its_own_headers_and_none_of_the_parents() { var parent = new Exchange(new Message("parent")); parent.In.Headers["parent-header"] = "p"; parent.Properties["prop"] = "kept"; var element = new Message("one") { ContentType = "text/plain" }; element.Headers["key"] = "k1"; var child = ListBody.ElementExchange(parent, element); child.In.Body.Should().Be("one"); child.In.ContentType.Should().Be("text/plain"); child.In.Headers.Should().ContainKey("key").And.NotContainKey("parent-header"); child.In.Should().NotBeSameAs(element); child.Properties["prop"].Should().Be("kept"); } [Fact] public void A_plain_element_is_the_body_under_the_parents_headers() { var parent = new Exchange(new Message(new List { 7 }) { ContentType = "application/json" }); parent.In.Headers["parent-header"] = "p"; var child = ListBody.ElementExchange(parent, 7); child.In.Body.Should().Be(7); child.In.Headers["parent-header"].Should().Be("p"); child.In.ContentType.Should().Be("application/json"); } [Fact] public void The_refusals_name_the_endpoint_and_the_way_out() { ListBody.RequestReplyRefusal("rabbitmq://q", 3).Message.Should().Contain("rabbitmq://q").And.Contain("Split the list"); ListBody.PlainListRefusal("wmq://Q", new List()).Message.Should().Contain("wmq://Q").And.Contain("List").And.Contain("IMessage"); } } Path: redb-route/tests/redb.Route.Tests/Core/MessageAttachmentsTests.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/MessageAttachmentsTests.cs ---- using System.Text; using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Components; using redb.Route.Configuration; using redb.Route.Core; using redb.Route.Expressions; namespace redb.Route.Tests.Core; /// /// The attachments of a message (Camel's AttachmentMessage): a list on the message, not a property of the /// exchange, with re-readable content that follows the body's rules for copying, snapshots and disposal. /// public class MessageAttachmentsTests { private static Attachment Bytes(string name, string text, string? fileName = null, string contentType = "text/plain") => new() { Name = name, FileName = fileName, ContentType = contentType, Content = AttachmentContent.FromBytes(Encoding.UTF8.GetBytes(text)) }; private static string Text(Attachment attachment) => Encoding.UTF8.GetString(attachment.Content.ReadAllBytes()); private static StreamCache Cache(string text) { var cache = new StreamCache(); cache.Write(Encoding.UTF8.GetBytes(text)); cache.CompleteWriting(); return cache; } // ── The list ── [Fact] public void Names_may_repeat_and_lookups_answer_the_first() { var message = new Message(); message.Attachments.Add(Bytes("files", "one", "a.pdf")); message.Attachments.Add(Bytes("files", "two", "b.pdf")); message.Attachments.Add(Bytes("note", "three")); message.Attachments.Should().HaveCount(3, "a form posts several files under one field"); message.Attachments.Find("files")!.FileName.Should().Be("a.pdf"); message.Attachments.FindAll("files").Select(a => a.FileName).Should().Equal("a.pdf", "b.pdf"); message.Attachments.Find("Files").Should().BeNull("names compare ordinally"); } [Fact] public void Set_replaces_every_attachment_of_the_name_at_the_first_position() { var message = new Message(); message.Attachments.Add(Bytes("a", "1")); message.Attachments.Add(Bytes("b", "2")); message.Attachments.Add(Bytes("a", "3")); message.Attachments.Set(Bytes("a", "new")); message.Attachments.Select(a => a.Name).Should().Equal("a", "b"); Text(message.Attachments[0]).Should().Be("new"); message.Attachments.Remove("b").Should().Be(1); message.Attachments.Should().ContainSingle(); } [Fact] public void A_line_break_in_a_name_is_refused_before_it_can_reach_a_MIME_header() { var act = () => new Attachment { Name = "a\r\nBcc: x", Content = AttachmentContent.FromBytes([1]) }; act.Should().Throw().WithMessage("*line break*"); } [Fact] public void A_message_type_without_attachments_reads_none_and_refuses_additions() { IMessage foreign = new ForeignMessage(); foreign.Attachments.Should().BeEmpty(); var add = () => foreign.Attachments.Add(Bytes("a", "1")); add.Should().Throw(); } // ── Content ── [Fact] public async Task Content_is_read_from_the_start_on_every_open() { var content = AttachmentContent.FromStreamCache(Cache("payload")); (await content.ReadAllBytesAsync()).Should().Equal("payload"u8.ToArray()); content.ReadAllBytes().Should().Equal("payload"u8.ToArray(), "a resend reads the same attachment again"); content.Length.Should().Be(7); } [Fact] public void Readers_of_one_StreamCache_do_not_move_each_other_or_the_cache() { using var cache = Cache("abcdef"); var first = cache.OpenReader(); var second = cache.OpenReader(); var buffer = new byte[3]; first.ReadExactly(buffer); Encoding.ASCII.GetString(buffer).Should().Be("abc"); second.ReadExactly(buffer); Encoding.ASCII.GetString(buffer).Should().Be("abc", "each reader has its own position"); first.ReadExactly(buffer); Encoding.ASCII.GetString(buffer).Should().Be("def"); cache.Position.Should().Be(0, "the readers leave the cache's own position alone"); } [Fact] public async Task A_file_attachment_is_deleted_with_the_exchange_only_when_asked() { var kept = Path.GetTempFileName(); var owned = Path.GetTempFileName(); try { var message = new Message(); message.Attachments.Add(new Attachment { Name = "kept", Content = AttachmentContent.FromFile(kept) }); message.Attachments.Add(new Attachment { Name = "owned", Content = AttachmentContent.FromFile(owned, deleteWithExchange: true) }); await new Exchange(message).DisposeAsync(); File.Exists(kept).Should().BeTrue(); File.Exists(owned).Should().BeFalse(); } finally { File.Delete(kept); File.Delete(owned); } } // ── Copies, snapshots, disposal ── [Fact] public void Clone_gets_its_own_list_over_the_same_content() { var original = new Message(); original.Attachments.Add(Bytes("a", "1")); var clone = original.Clone(); clone.Attachments.Add(Bytes("b", "2")); original.Attachments.Should().ContainSingle("the clone's list is its own"); clone.Attachments[0].Content.Should().BeSameAs(original.Attachments[0].Content, "content is shared like the body"); } [Fact] public void Snapshot_freezes_the_content() { var bytes = Encoding.UTF8.GetBytes("frozen"); var original = new Message(); original.Attachments.Add(new Attachment { Name = "a", Content = AttachmentContent.FromBytes(bytes) }); var snapshot = original.Snapshot(); bytes[0] = (byte)'X'; Text(snapshot.Attachments[0]).Should().Be("frozen"); } [Fact] public async Task A_StreamCache_attachment_is_disposed_once_by_the_owner_and_not_by_a_copy() { var cache = Cache("x"); var root = new Exchange(new Message("body")); root.In.Attachments.Add(new Attachment { Name = "a", Content = AttachmentContent.FromStreamCache(cache) }); var copy = root.Clone(); await copy.DisposeAsync(); cache.CanRead.Should().BeTrue("the origin still carries it"); await root.DisposeAsync(); cache.CanRead.Should().BeFalse(); } [Fact] public async Task A_checkpoint_is_not_captured_when_attachments_exceed_MaxReplayableBytes() { var options = new RouteEngineOptions { Attachments = { MaxReplayableBytes = 4 } }; await using var context = new RouteContext($"att-replay-{Guid.NewGuid():N}", options: options); context.AddComponent(new DirectComponent()); IExchange? seen = null; context.AddRoutes(r => r.From("direct://att-replay") .AddAttachment("big", new ConstantExpression("12345")) .Replayable("m") .Process(e => seen = e)); await context.Start(); var template = new ProducerTemplate(context); template.Start(); await template.SendAsync("direct://att-replay", "body"); seen!.Properties.ContainsKey(RouteCheckpoint.PropertyKey).Should().BeFalse( "a snapshot keeps at most RedbRoute:Attachments:MaxReplayableBytes of attachments"); } [Fact] public async Task A_checkpoint_keeps_attachments_within_MaxReplayableBytes() { await using var context = new RouteContext($"att-replay-ok-{Guid.NewGuid():N}"); context.AddComponent(new DirectComponent()); IExchange? seen = null; context.AddRoutes(r => r.From("direct://att-replay-ok") .AddAttachment("small", new ConstantExpression("12345")) .Replayable("m") .Process(e => seen = e)); await context.Start(); var template = new ProducerTemplate(context); template.Start(); await template.SendAsync("direct://att-replay-ok", "body"); var checkpoint = (RouteCheckpoint)seen!.Properties[RouteCheckpoint.PropertyKey]!; Text(checkpoint.Snapshot.In.Attachments.Single()).Should().Be("12345"); } // ── Through a route ── private static async Task<(RouteContext Context, ProducerTemplate Template)> Route(Action build) { var context = new RouteContext($"attachments-{Guid.NewGuid():N}"); context.AddComponent(new DirectComponent()); context.AddRoutes(build); await context.Start(); var template = new ProducerTemplate(context); template.Start(); return (context, template); } [Fact] public async Task A_step_that_writes_Out_without_attachments_leaves_those_of_In() { IExchange? seen = null; var (context, template) = await Route(r => r.From("direct://att-out") .AddAttachment("kept", new ConstantExpression("k")) .Process(e => e.Out = new Message("reply")) .Process(e => seen = e)); await using var _ = context; await template.SendAsync("direct://att-out", "in"); seen!.In.Body.Should().Be("reply"); seen.In.Attachments.Select(a => a.Name).Should().Equal("kept"); } [Fact] public async Task A_step_that_writes_Out_with_attachments_replaces_those_of_In() { IExchange? seen = null; var (context, template) = await Route(r => r.From("direct://att-out2") .AddAttachment("old", new ConstantExpression("o")) .Process(e => { var reply = new Message("reply"); reply.Attachments.Add(Bytes("new", "n")); e.Out = reply; }) .Process(e => seen = e)); await using var _ = context; await template.SendAsync("direct://att-out2", "in"); seen!.In.Attachments.Select(a => a.Name).Should().Equal("new"); } [Fact] public async Task Every_split_part_carries_the_attachments() { var parts = new List(); var (context, template) = await Route(r => r.From("direct://att-split") .AddAttachment("doc", new ConstantExpression("d")) .Split(e => new object?[] { "a", "b" }) .Process(e => parts.Add($"{e.In.Body}:{e.In.Attachments.Count}")) .End()); await using var _ = context; await template.SendAsync("direct://att-split", "in"); parts.Should().Equal("a:1", "b:1"); } [Fact] public async Task The_attachment_steps_add_from_an_expression_the_body_and_a_file_and_remove() { var path = Path.Combine(Path.GetTempPath(), $"att-{Guid.NewGuid():N}.txt"); await File.WriteAllTextAsync(path, "from file"); try { IExchange? seen = null; var (context, template) = await Route(r => r.From("direct://att-steps") .SetHeader("who", "anna") .AddAttachment("note", new StringExpression("${header.who}"), new StringExpression("${header.who}.txt")) .AddAttachment("literal", new ConstantExpression("x"), fileName: "${not.a.template}") .AddAttachmentFromBody("body.bin", contentType: "application/pdf") .AddAttachmentFromFile(path) .AddAttachment("gone", new ConstantExpression("x")) .RemoveAttachment("gone") .Process(e => seen = e)); await using var _ = context; await template.SendAsync("direct://att-steps", "the body"); var attachments = seen!.In.Attachments; attachments.Select(a => a.Name).Should().Equal("note", "literal", "body.bin", Path.GetFileName(path)); Text(attachments[0]).Should().Be("anna"); attachments[0].FileName.Should().Be("anna.txt"); attachments[0].ContentType.Should().Be("text/plain; charset=utf-8"); attachments[1].FileName.Should().Be("${not.a.template}", "a literal stays literal, whatever its text"); Text(attachments[2]).Should().Be("the body"); attachments[2].ContentType.Should().Be("application/pdf"); Text(attachments[3]).Should().Be("from file"); seen.In.Body.Should().Be("the body", "attaching the body leaves it in place"); } finally { File.Delete(path); } } [Fact] public async Task RemoveAttachments_clears_the_list() { IExchange? seen = null; var (context, template) = await Route(r => r.From("direct://att-clear") .AddAttachment("a", new ConstantExpression("1")) .AddAttachment("b", new ConstantExpression("2")) .RemoveAttachments() .Process(e => seen = e)); await using var _ = context; await template.SendAsync("direct://att-clear", "in"); seen!.In.Attachments.Should().BeEmpty(); } // ── In the expression language ── private static IExchange WithAttachments() { var message = new Message("body"); message.Attachments.Add(new Attachment { Name = "note", FileName = "note.txt", ContentType = "text/plain; charset=windows-1251", Headers = new Dictionary { ["Content-Disposition"] = "attachment; filename=note.txt" }, Content = AttachmentContent.FromBytes(Encoding.GetEncoding(1251).GetBytes("привет")) }); message.Attachments.Add(Bytes("scan", "%PDF", "scan.pdf", "application/pdf")); return new Exchange(message); } static MessageAttachmentsTests() => Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); [Theory] [InlineData("${attachments.size}", "2")] [InlineData("${attachments[1].fileName}", "scan.pdf")] [InlineData("${attachments[0].length}", "6")] [InlineData("${attachmentContentAsText('note')}", "привет")] [InlineData("${attachmentContentType('scan')}", "application/pdf")] [InlineData("${attachmentHeader('note', 'content-disposition')}", "attachment; filename=note.txt")] [InlineData("${attachmentContentType('missing') ?? 'none'}", "none")] public void Templates_read_attachments_with_the_Camel_Simple_names(string template, string expected) { ExpressionResolver.ProcessTemplate(template, WithAttachments()).Should().Be(expected); } [Fact] public void A_condition_and_a_value_read_attachments_too() { var exchange = WithAttachments(); new StringExpression("attachments.size > 1").Evaluate(exchange).Should().BeTrue(); new StringExpression("${attachmentContent('scan')}").Evaluate(exchange).Should().Equal("%PDF"u8.ToArray()); new StringExpression("${attachments}").Evaluate(exchange).Should().HaveCount(2); } [Fact] public void The_interpreter_and_the_compiler_agree() { var exchange = WithAttachments(); foreach (var expression in new[] { "attachmentContentAsText('note')", "attachmentContentType('scan')", "attachmentHeader('note', 'Content-Disposition')" }) { var interpreted = new redb.Route.Expressions.Ast.Parser(new redb.Route.Expressions.Ast.Tokenizer(expression).GetAllTokens()).Parse().Evaluate(exchange); var compiled = new StringExpression("${" + expression + "}").Evaluate(exchange); compiled.Should().Be(interpreted, expression); } } private sealed class ForeignMessage : IMessage { public object? Body { get; set; } public string? ContentType { get; set; } public IDictionary Headers { get; } = new Dictionary(); public T? GetHeader(string key) => default; public IMessage Clone() => this; public IMessage Snapshot() => this; } } Path: redb-route/tests/redb.Route.Tests/Core/MessageTests.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/MessageTests.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using AwesomeAssertions; namespace redb.Route.Tests.Core; public class MessageTests { [Fact] public void NewMessage_HasNullBody() { var msg = new Message(); msg.Body.Should().BeNull(); } [Fact] public void Constructor_WithBody_SetsBody() { var msg = new Message("hello"); msg.Body.Should().Be("hello"); } [Fact] public void Headers_AreCaseInsensitive() { var msg = new Message(); msg.Headers["Content-Type"] = "application/json"; msg.Headers["content-type"].Should().Be("application/json"); } [Fact] public void GetHeader_ReturnsTypedValue() { var msg = new Message(); msg.Headers["count"] = 42; msg.GetHeader("count").Should().Be(42); } [Fact] public void GetHeader_ConvertsStringToInt() { var msg = new Message(); msg.Headers["count"] = "42"; msg.GetHeader("count").Should().Be(42); } [Fact] public void GetHeader_MissingKey_ReturnsDefault() { var msg = new Message(); msg.GetHeader("missing").Should().Be(0); } [Fact] public void GetHeader_NullValue_ReturnsDefault() { var msg = new Message(); msg.Headers["key"] = null; msg.GetHeader("key").Should().BeNull(); } [Fact] public void Clone_CopiesBodyAndHeaders() { var msg = new Message("data"); msg.Headers["region"] = "us-east"; var clone = msg.Clone(); clone.Body.Should().Be("data"); clone.Headers["region"].Should().Be("us-east"); clone.Should().NotBeSameAs(msg); } [Fact] public void Clone_IsDeepCopy_HeadersAreIndependent() { var msg = new Message(); msg.Headers["key"] = "original"; var clone = msg.Clone(); clone.Headers["key"] = "changed"; msg.Headers["key"].Should().Be("original"); } // ── Java-style API tests ── [Fact] public void JavaStyle_GetBody_ReturnsBody() { IMessage msg = new Message("test"); msg.getBody().Should().Be("test"); } [Fact] public void JavaStyle_SetBody_SetsBody() { IMessage msg = new Message(); msg.setBody("hello"); msg.Body.Should().Be("hello"); } [Fact] public void JavaStyle_GetSetHeader() { IMessage msg = new Message(); msg.setHeader("key", "value"); msg.getHeader("key").Should().Be("value"); } [Fact] public void JavaStyle_GetHeaders_ReturnsSameInstance() { IMessage msg = new Message(); msg.getHeaders().Should().BeSameAs(msg.Headers); } [Fact] public void JavaStyle_Copy_ClonesMessage() { IMessage msg = new Message("data"); var clone = msg.copy(); clone.Body.Should().Be("data"); clone.Should().NotBeSameAs(msg); } // ── ContentType tests ── [Fact] public void ContentType_DefaultIsNull() { var msg = new Message(); msg.ContentType.Should().BeNull(); } [Fact] public void ContentType_SetAndGet() { var msg = new Message("x") { ContentType = "application/json" }; msg.ContentType.Should().Be("application/json"); } [Fact] public void Clone_CopiesContentType() { var msg = new Message("data") { ContentType = "text/xml" }; msg.Headers["key"] = "val"; var clone = msg.Clone(); clone.ContentType.Should().Be("text/xml"); clone.Body.Should().Be("data"); clone.Headers["key"].Should().Be("val"); } [Fact] public void Clone_ContentType_IsIndependent() { var msg = new Message { ContentType = "application/json" }; var clone = msg.Clone(); clone.ContentType = "text/plain"; msg.ContentType.Should().Be("application/json"); } [Fact] public void Clone_NullContentType_StaysNull() { var msg = new Message("body"); msg.ContentType.Should().BeNull(); var clone = msg.Clone(); clone.ContentType.Should().BeNull(); } [Fact] public void JavaStyle_GetSetContentType() { IMessage msg = new Message(); msg.setContentType("application/xml"); msg.getContentType().Should().Be("application/xml"); } } Path: redb-route/tests/redb.Route.Tests/Core/OptionGroupTests.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/OptionGroupTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Tests.Core; /// /// Option groups (): Apache Camel's prefixed options, group.member=value, bound /// by the one binder; an unknown member is refused naming the group and its members; [Sensitive] members are masked as /// group.member; endpoints without groups bind exactly as before. /// public sealed class OptionGroupTests { public sealed class Filter { [OptionGroupValue] public string? Reference { get; set; } public bool Unseen { get; set; } = true; public string? Subject { get; set; } public int Limit { get; set; } [Sensitive] public string? Token { get; set; } public DynamicValue? Label { get; set; } } public sealed class Plain { public string? Name { get; set; } } public sealed class GroupedOptions : EndpointOptions { public string? Host { get; set; } [EndpointRole(EndpointRole.Consumer)] [OptionGroup] public Filter? SearchTerm { get; set; } [OptionGroup] public Plain? Extra { get; set; } public override void Validate() { } } /// A plain option named like the group of another endpoint: not a group, binds as ever. public sealed class PlainSearchTermOptions : EndpointOptions { public string? SearchTerm { get; set; } public override void Validate() { } } [LenientProperties] public sealed class LenientDottedOptions : EndpointOptions { public string? Host { get; set; } public override void Validate() { } } private static GroupedOptions Bind(params (string Key, string Value)[] parameters) { var options = new GroupedOptions(); options.BindFromUri(parameters.ToDictionary(p => p.Key, p => p.Value, StringComparer.OrdinalIgnoreCase)); return options; } [Fact] public void Members_bind_into_the_group_which_is_created_on_first_use() { var options = Bind(("host", "h"), ("searchTerm.subject", "invoice"), ("SEARCHTERM.LIMIT", "5"), ("searchTerm.unseen", "false")); options.Host.Should().Be("h"); options.SearchTerm.Should().NotBeNull(); options.SearchTerm!.Subject.Should().Be("invoice"); options.SearchTerm.Limit.Should().Be(5); options.SearchTerm.Unseen.Should().BeFalse(); options.Extra.Should().BeNull("no member of it was written"); options.UnmappedParameters.Should().BeEmpty(); } [Fact] public void A_member_takes_an_expression_as_an_option_of_the_endpoint_does() { var options = Bind(("searchTerm.label", "${header.x}")); options.SearchTerm!.Label!.Value.IsDynamic.Should().BeTrue(); } [Fact] public void The_bare_group_name_binds_the_value_member() { var options = Bind(("searchTerm", "#query"), ("searchTerm.subject", "x")); options.SearchTerm!.Reference.Should().Be("#query"); options.SearchTerm.Subject.Should().Be("x"); } [Fact] public void An_unknown_member_is_refused_naming_the_group_and_its_members() { var act = () => Bind(("searchTerm.subjct", "x")); act.Should().Throw() .WithMessage("'searchTerm.subjct' is not an option of the Grouped endpoint: the group searchTerm takes searchTerm, " + "searchTerm.unseen, searchTerm.subject, searchTerm.limit, searchTerm.token, searchTerm.label." + " Did you mean 'searchTerm.subject'?*"); } [Fact] public void A_bare_group_without_a_value_member_is_refused_naming_its_members() { var act = () => Bind(("extra", "x")); act.Should().Throw() .WithMessage("'extra' is a group of options of the Grouped endpoint, written extra.member: extra.name.*"); } [Fact] public void A_value_that_does_not_convert_names_the_member() { var act = () => Bind(("searchTerm.limit", "many")); act.Should().Throw().WithMessage("'searchTerm.limit=many' is not a valid value*"); } [Fact] public void BindableOptions_names_each_member_as_the_uri_writes_it() { EndpointOptions.BindableOptions(typeof(GroupedOptions)).Select(o => o.Name).Should().BeEquivalentTo( "Host", "SearchTerm", "SearchTerm.Unseen", "SearchTerm.Subject", "SearchTerm.Limit", "SearchTerm.Token", "SearchTerm.Label", "Extra.Name"); } [Fact] public void A_sensitive_member_is_masked_as_group_member() { var options = Bind(("searchTerm.token", "s3cret-token")); EndpointUri.Sanitize("grouped:x?searchTerm.token=s3cret-token&host=h") .Should().Be("grouped:x?searchTerm.token=****&host=h"); options.SensitiveValues().Should().Contain("s3cret-token"); } [Fact] public void A_member_belongs_to_the_side_of_its_group() { var uri = EndpointUriParser.Parse("grouped:x?searchTerm.subject=a&searchTerm=%23q&host=h"); EndpointOptions.WrittenForOtherRole(typeof(GroupedOptions), uri, EndpointRole.Producer) .Should().BeEquivalentTo("searchTerm.subject", "searchTerm"); EndpointOptions.WrittenForOtherRole(typeof(GroupedOptions), uri, EndpointRole.Consumer).Should().BeEmpty(); } [Fact] public void A_plain_option_named_like_a_group_elsewhere_binds_as_before() { var plain = new PlainSearchTermOptions(); plain.BindFromUri(new Dictionary(StringComparer.OrdinalIgnoreCase) { ["searchTerm"] = "x" }); plain.SearchTerm.Should().Be("x"); var dotted = () => new PlainSearchTermOptions().BindFromUri( new Dictionary(StringComparer.OrdinalIgnoreCase) { ["searchTerm.subject"] = "x" }); dotted.Should().Throw().WithMessage("'searchTerm.subject' is not an option of the PlainSearchTerm endpoint.*"); } [Fact] public void A_lenient_endpoint_keeps_dotted_parameters_it_has_no_group_for() { var options = new LenientDottedOptions(); options.BindFromUri(new Dictionary(StringComparer.OrdinalIgnoreCase) { ["host"] = "h", ["param.id"] = "7", ["searchTerm.subject"] = "x", }); options.UnmappedParameters.Should().BeEquivalentTo(new Dictionary { ["param.id"] = "7", ["searchTerm.subject"] = "x", }); } [Fact] public void The_short_log_form_cuts_before_a_member_not_inside_it() { var uri = "grouped:inbox?host=mail.example.com&searchTerm.subject=" + new string('s', 60) + "&searchTerm.fromSentDate=now-24h&searchTerm.to=" + new string('t', 60); var form = EndpointUri.ForLog(uri); var kept = form[..form.IndexOf("... [", StringComparison.Ordinal)]; kept.Should().EndWith("&searchTerm.subject=" + new string('s', 60), "the cut falls on the '&' before a member, so no member and no value is split"); } public sealed class BadGroupOptions : EndpointOptions { [OptionGroup] public string? Text { get; set; } public override void Validate() { } } [Fact] public void A_group_whose_type_is_not_a_class_with_a_constructor_is_a_declaration_error() { var act = () => EndpointOptions.BindableOptions(typeof(BadGroupOptions)); act.Should().Throw().WithMessage("BadGroupOptions.Text is an [OptionGroup]*"); } } Path: redb-route/tests/redb.Route.Tests/Core/PredicateOverloadTests.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/PredicateOverloadTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Definitions; using redb.Route.Expressions; using redb.Route.Extensions; namespace redb.Route.Tests.Core; /// /// The nested-lambda When(predicate, branch) takes the same argument kinds as the one-argument /// When(...): a lambda or method group, an and an . /// OnWhen and RetryWhile of an exception handler take an too. /// public class PredicateOverloadTests { private static bool IsOrder(IExchange e) => e.In.GetHeader("type") == "order"; [Fact] public void NestedWhen_BindsEachArgumentKindToItsOwnOverload() { var choice = new ChoiceDefinition(); choice.When(e => e.In.GetHeader("type") == "lambda", _ => { }); // lambda choice.When(IsOrder, _ => { }); // method group IExpression expression = new HeaderExpression("flag"); choice.When(expression, _ => { }); // IExpression IPredicate predicate = new HeaderExpression("type").isEqualTo("order"); choice.When(predicate, _ => { }); // IPredicate choice.When(new HeaderExpression("type").isEqualTo("payment"), _ => { }); // IPredicate, inline choice.When(RouteBuilder.Method("#rules", "IsGold"), _ => { }); // IPredicateExpression: the IExpression overload var whens = choice.Whens; whens.Should().HaveCount(6); whens[0].SourcePredicate.Should().BeNull(); whens[0].SourceExpression.Should().BeNull(); whens[1].SourcePredicate.Should().BeNull(); whens[1].SourceExpression.Should().BeNull(); whens[2].SourceExpression.Should().BeSameAs(expression); whens[3].SourcePredicate.Should().BeSameAs(predicate); whens[4].SourcePredicate.Should().NotBeNull(); whens[5].SourceExpression.Should().NotBeNull(); whens[5].SourcePredicate.Should().BeNull(); } [Fact] public void NestedWhen_WithAPredicate_ReturnsTheChoiceAndRunsTheBranch() { var choice = new ChoiceDefinition(); WhenDefinition? seen = null; var returned = choice.When(new HeaderExpression("type").isEqualTo("order"), w => seen = w); returned.Should().BeSameAs(choice); seen.Should().BeSameAs(choice.Whens[0]); } [Fact] public void NestedWhen_WithANullBranch_IsRefused() { var choice = new ChoiceDefinition(); var act = () => choice.When(new HeaderExpression("type").isEqualTo("order"), null!); act.Should().Throw(); } [Fact] public async Task ARoute_ThroughTheNestedPredicateWhen_TakesTheMatchingBranch() { var taken = new List(); await using var context = new RouteContext(); context.AddRoutes(r => { r.From("direct://choice-predicate") .Choice(c => c .When(new HeaderExpression("type").isEqualTo("order"), b => b.Process(_ => taken.Add("order"))) .When(new HeaderExpression("type").isEqualTo("payment"), b => b.Process(_ => taken.Add("payment"))) .Otherwise(b => b.Process(_ => taken.Add("other")))) .Process(_ => taken.Add("tail")); }); await context.Start(); var producer = context.GetEndpoint("direct://choice-predicate").CreateProducer(); await producer.Start(); foreach (var type in new[] { "payment", "order", "refund" }) { var message = new Message("x"); message.Headers["type"] = type; await producer.Process(new Exchange(message)); } taken.Should().Equal("payment", "tail", "order", "tail", "other", "tail"); } [Fact] public async Task AnExceptionHandler_WithAPredicateOnWhen_IsPassedOverWhenItDoesNotHold() { var taken = new List(); await using var context = new RouteContext(); context.AddRoutes(r => { r.OnException().OnWhen(new HeaderExpression("urgent").isEqualTo(true)) .Handled().Process(_ => taken.Add("urgent")); r.OnException().Handled().Process(_ => taken.Add("any")); r.From("direct://onwhen-predicate").Process(_ => throw new IOException("io")); }); await context.Start(); var producer = context.GetEndpoint("direct://onwhen-predicate").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("a"))); var urgent = new Message("b"); urgent.Headers["urgent"] = true; await producer.Process(new Exchange(urgent)); taken.Should().Equal("any", "urgent"); } [Fact] public async Task AnExceptionHandler_WithAPredicateRetryWhile_StopsRetryingWhenItNoLongerHolds() { var attempts = 0; await using var context = new RouteContext(); context.AddRoutes(r => { r.OnException() .MaximumRedeliveries(10) .RedeliveryDelay(TimeSpan.Zero) .RetryWhile(new HeaderExpression("retry").isEqualTo(true)) .Handled(); r.From("direct://retrywhile-predicate").Process(e => { attempts++; if (attempts == 3) e.In.Headers["retry"] = false; throw new IOException("io"); }); }); await context.Start(); var producer = context.GetEndpoint("direct://retrywhile-predicate").CreateProducer(); await producer.Start(); var message = new Message("x"); message.Headers["retry"] = true; await producer.Process(new Exchange(message)); attempts.Should().Be(3); } [Fact] public void PredicateOnWhenAndRetryWhile_RefuseNull() { var definition = new OnExceptionDefinition([typeof(IOException)]); ((Action)(() => definition.OnWhen((IPredicate)null!))).Should().Throw(); ((Action)(() => definition.RetryWhile((IPredicate)null!))).Should().Throw(); } } Path: redb-route/tests/redb.Route.Tests/Core/ProcessingTimeoutTests.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/ProcessingTimeoutTests.cs ---- using NSubstitute; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Definitions; using redb.Route.Processors; namespace redb.Route.Tests.Core; /// /// Tests for per-exchange processing timeout (Phase 5). /// public sealed class ProcessingTimeoutTests { [Fact] public async Task TimeoutProcessor_CompletesNormally_WhenWithinTimeout() { var inner = Substitute.For(); inner.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask); var processor = new TimeoutProcessor(inner, TimeSpan.FromSeconds(5), "test-route"); var exchange = new Exchange(new Message("hello")); await processor.Process(exchange, CancellationToken.None); exchange.Exception.Should().BeNull(); await inner.Received(1).Process(exchange, Arg.Any()); } [Fact] public async Task TimeoutProcessor_ThrowsExchangeTimedOut_WhenExceedsTimeout() { var inner = Substitute.For(); inner.Process(Arg.Any(), Arg.Any()) .Returns(async ci => { var ct = ci.Arg(); await Task.Delay(Timeout.Infinite, ct); }); var processor = new TimeoutProcessor(inner, TimeSpan.FromMilliseconds(50), "slow-route"); var exchange = new Exchange(new Message("hello")); var act = () => processor.Process(exchange, CancellationToken.None); await act.Should().ThrowAsync() .Where(e => e.RouteId == "slow-route" && e.Timeout == TimeSpan.FromMilliseconds(50)); exchange.Exception.Should().BeOfType(); exchange.Properties["ExchangeTimedOut"].Should().Be(true); } [Fact] public async Task TimeoutProcessor_PropagatesExternalCancellation() { var inner = Substitute.For(); inner.Process(Arg.Any(), Arg.Any()) .Returns(async ci => { var ct = ci.Arg(); await Task.Delay(Timeout.Infinite, ct); }); var processor = new TimeoutProcessor(inner, TimeSpan.FromSeconds(10), "test-route"); var exchange = new Exchange(new Message("hello")); using var cts = new CancellationTokenSource(); cts.Cancel(); var act = () => processor.Process(exchange, cts.Token); // External cancellation should propagate as OperationCanceledException, NOT ExchangeTimedOutException await act.Should().ThrowAsync(); } [Fact] public async Task TimeoutProcessor_PassesLinkedToken_ToInner() { CancellationToken receivedToken = default; var inner = Substitute.For(); inner.Process(Arg.Any(), Arg.Any()) .Returns(ci => { receivedToken = ci.Arg(); return Task.CompletedTask; }); var processor = new TimeoutProcessor(inner, TimeSpan.FromSeconds(5), "test-route"); var exchange = new Exchange(new Message("hello")); await processor.Process(exchange, CancellationToken.None); receivedToken.CanBeCanceled.Should().BeTrue(); } [Fact] public void ExchangeTimedOutException_ContainsRouteIdAndTimeout() { var ex = new ExchangeTimedOutException("my-route", TimeSpan.FromMinutes(2), TimeSpan.FromMinutes(2)); ex.RouteId.Should().Be("my-route"); ex.Timeout.Should().Be(TimeSpan.FromMinutes(2)); ex.Elapsed.Should().Be(TimeSpan.FromMinutes(2)); ex.Message.Should().Contain("my-route"); ex.Message.Should().Contain("120"); ex.Should().BeAssignableTo(); } [Fact] public async Task Route_WithProcessingTimeout_TimesOut() { var timedOut = false; var ctx = new RouteContext(options: new Configuration.RouteEngineOptions { EnableTelemetry = false, EnableMetrics = false }); ctx.AddRoutes(r => { r.From("direct://timeout-dsl") .RouteId("timeout-dsl") .ProcessingTimeout(TimeSpan.FromMilliseconds(50)) .Process(async (e, ct) => { await Task.Delay(TimeSpan.FromSeconds(10), ct); }); r.OnException() .Process(e => { timedOut = true; e.ExceptionHandled = true; }); }); await ctx.Start(); var producer = ctx.GetEndpoint("direct://timeout-dsl").CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("test")); await producer.Process(exchange, CancellationToken.None); await ctx.Stop(); await ctx.DisposeAsync(); timedOut.Should().BeTrue(); } [Fact] public async Task Route_WithDefaultProcessingTimeout_AppliesGlobally() { var ctx = new RouteContext(options: new Configuration.RouteEngineOptions { EnableTelemetry = false, EnableMetrics = false, DefaultProcessingTimeout = TimeSpan.FromMilliseconds(50) }); ctx.AddRoutes(r => { r.From("direct://global-timeout") .RouteId("global-timeout") .Process(async (e, ct) => { await Task.Delay(TimeSpan.FromSeconds(10), ct); }); r.OnException() .Process(e => e.ExceptionHandled = true); }); await ctx.Start(); var producer = ctx.GetEndpoint("direct://global-timeout").CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("test")); await producer.Process(exchange, CancellationToken.None); exchange.Exception.Should().BeOfType(); await ctx.Stop(); await ctx.DisposeAsync(); } [Fact] public async Task Route_WithoutTimeout_NoTimeoutApplied() { var completed = false; var ctx = new RouteContext(options: new Configuration.RouteEngineOptions { EnableTelemetry = false, EnableMetrics = false }); ctx.AddRoutes(r => { r.From("direct://no-timeout") .RouteId("no-timeout") .Process(e => { completed = true; }); }); await ctx.Start(); var producer = ctx.GetEndpoint("direct://no-timeout").CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("test")); await producer.Process(exchange, CancellationToken.None); completed.Should().BeTrue(); exchange.Exception.Should().BeNull(); await ctx.Stop(); await ctx.DisposeAsync(); } [Fact] public void ProcessingTimeout_ThrowsForInvalidValue() { var def = new RouteDefinition(); var act = () => def.ProcessingTimeout(TimeSpan.Zero); act.Should().Throw(); var act2 = () => def.ProcessingTimeout(TimeSpan.FromMilliseconds(-100)); act2.Should().Throw(); } [Fact] public void ProcessingTimeout_AcceptsInfinite() { var def = new RouteDefinition(); var act = () => def.ProcessingTimeout(System.Threading.Timeout.InfiniteTimeSpan); act.Should().NotThrow(); } } Path: redb-route/tests/redb.Route.Tests/Core/ProducerTemplateLifecycleTests.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/ProducerTemplateLifecycleTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Tests.Core; /// /// A producer the template creates is stopped — flushed and closed — when the template stops or is disposed, and when /// the context stops with the template still open, as in Camel, where stopping a ProducerTemplate stops its /// producer cache. The template used to drop its producers from the cache and nothing more: a Kafka producer behind it /// lost what it had not sent yet when the host stopped. /// public class ProducerTemplateLifecycleTests { private sealed class CountingProducer : IProducer { public int Stops; public Task Start(CancellationToken ct = default) => Task.CompletedTask; public Task Stop(CancellationToken ct = default) { Interlocked.Increment(ref Stops); return Task.CompletedTask; } public Task Process(IExchange exchange, CancellationToken ct = default) => Task.CompletedTask; } private sealed class CountingEndpoint(EndpointUri uri, IComponent component, List created) : IEndpoint { public EndpointUri Uri { get; } = uri; public IComponent Component { get; } = component; public IProducer CreateProducer() { var producer = new CountingProducer(); lock (created) created.Add(producer); return producer; } public IConsumer CreateConsumer(IProcessor processor) => throw new NotSupportedException(); public Task Start(CancellationToken ct = default) => Task.CompletedTask; public Task Stop(CancellationToken ct = default) => Task.CompletedTask; } private sealed class CountingComponent : ComponentBase { public List Created { get; } = []; public override string Scheme => "counting"; public override IEndpoint CreateEndpoint(EndpointUri uri) => new CountingEndpoint(uri, this, Created); } private static (RouteContext Context, CountingComponent Component) Context() { var context = new RouteContext($"pt-lifecycle-{Guid.NewGuid():N}"); var component = new CountingComponent(); context.AddComponent(component); return (context, component); } [Fact] public async Task Disposing_the_template_stops_its_producers() { var (context, component) = Context(); var template = new ProducerTemplate(context); template.Start(); await template.SendAsync("counting:a", "x"); await template.SendAsync("counting:b", "x"); template.Dispose(); component.Created.Should().HaveCount(2).And.OnlyContain(p => p.Stops == 1); await context.DisposeAsync(); } [Fact] public async Task Stopping_the_template_stops_its_producers_and_a_restart_makes_new_ones() { var (context, component) = Context(); var template = new ProducerTemplate(context); template.Start(); await template.SendAsync("counting:a", "x"); template.Stop(); component.Created.Single().Stops.Should().Be(1); template.Start(); await template.SendAsync("counting:a", "x"); component.Created.Should().HaveCount(2, "a stopped producer is not reused"); template.Dispose(); await context.DisposeAsync(); } [Fact] public async Task Stopping_the_context_stops_the_producers_of_a_template_still_open() { var (context, component) = Context(); await context.Start(); var template = new ProducerTemplate(context); template.Start(); await template.SendAsync("counting:a", "x"); await context.Stop(); component.Created.Single().Stops.Should().Be(1, "the host stopping must flush what the template sent"); template.Dispose(); component.Created.Single().Stops.Should().Be(1, "a producer is stopped once"); await context.DisposeAsync(); } [Fact] public async Task A_disposed_template_leaves_nothing_for_the_context_to_stop() { var (context, component) = Context(); await context.Start(); var template = new ProducerTemplate(context); template.Start(); await template.SendAsync("counting:a", "x"); template.Dispose(); await context.Stop(); component.Created.Single().Stops.Should().Be(1); await context.DisposeAsync(); } } Path: redb-route/tests/redb.Route.Tests/Core/ProducerTemplateTests.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/ProducerTemplateTests.cs ---- using AwesomeAssertions; using NSubstitute; using redb.Route.Abstractions; using redb.Route.Components; using redb.Route.Core; using redb.Route.Processors; namespace redb.Route.Tests.Core; /// /// Tests for : lifecycle, sync/async send, /// request/reply, processor-based send, message send. /// Uses DirectComponent for real endpoint integration. /// public class ProducerTemplateTests : IDisposable { private readonly RouteContext _ctx = new("pt-test"); private readonly ProducerTemplate _template; private readonly List _receivedExchanges = []; public ProducerTemplateTests() { _ctx.AddComponent(new DirectComponent()); _template = new ProducerTemplate(_ctx); } public void Dispose() { if (_template.IsStarted) _template.Stop(); _ctx.Dispose(); } // ── Lifecycle ── [Fact] public void IsStarted_FalseByDefault() { _template.IsStarted.Should().BeFalse(); } [Fact] public void Start_SetsIsStarted() { _template.Start(); _template.IsStarted.Should().BeTrue(); } [Fact] public void Start_WhenAlreadyStarted_Throws() { _template.Start(); var act = () => _template.Start(); act.Should().Throw().WithMessage("*already started*"); } [Fact] public void Stop_ClearsIsStarted() { _template.Start(); _template.Stop(); _template.IsStarted.Should().BeFalse(); } [Fact] public void Stop_WhenNotStarted_Throws() { var act = () => _template.Stop(); act.Should().Throw().WithMessage("*not started*"); } [Fact] public void Send_WhenNotStarted_Throws() { var act = () => _template.Send("direct:test", "body"); act.Should().Throw().WithMessage("*not started*"); } [Fact] public void Context_ReturnsRouteContext() { _template.Context.Should().BeSameAs(_ctx); } [Fact] public void Constructor_NullContext_Throws() { var act = () => new ProducerTemplate(null!); act.Should().Throw(); } // ── Sync Send ── [Fact] public async Task Send_ByUri_DeliversBody() { await SetupConsumer("direct:orders"); _template.Start(); _template.Send("direct:orders", "payload"); _receivedExchanges.Should().HaveCount(1); _receivedExchanges[0].In.Body.Should().Be("payload"); } [Fact] public async Task Send_ByEndpoint_DeliversBody() { await SetupConsumer("direct:items"); _template.Start(); var endpoint = _ctx.GetEndpoint("direct:items"); _template.Send(endpoint, "item-data"); _receivedExchanges.Should().HaveCount(1); _receivedExchanges[0].In.Body.Should().Be("item-data"); } [Fact] public async Task Send_Exchange_DeliversExistingExchange() { await SetupConsumer("direct:raw"); _template.Start(); var exchange = new Exchange(new Message("raw-body")); exchange.In.Headers["type"] = "raw"; var endpoint = _ctx.GetEndpoint("direct:raw"); _template.Send(endpoint, exchange); _receivedExchanges.Should().HaveCount(1); _receivedExchanges[0].In.Body.Should().Be("raw-body"); _receivedExchanges[0].In.Headers["type"].Should().Be("raw"); } [Fact] public async Task Send_Message_WrapsInExchange() { await SetupConsumer("direct:msg"); _template.Start(); var message = new Message("msg-body"); message.Headers["h1"] = "v1"; var endpoint = _ctx.GetEndpoint("direct:msg"); _template.Send(endpoint, (IMessage)message); _receivedExchanges.Should().HaveCount(1); _receivedExchanges[0].In.Body.Should().Be("msg-body"); _receivedExchanges[0].In.Headers["h1"].Should().Be("v1"); } [Fact] public async Task Send_MessageByUri_Works() { await SetupConsumer("direct:msg2"); _template.Start(); var message = new Message("uri-msg"); _template.Send("direct:msg2", (IMessage)message); _receivedExchanges.Should().HaveCount(1); _receivedExchanges[0].In.Body.Should().Be("uri-msg"); } [Fact] public async Task Send_WithProcessor_AppliesProcessorBeforeSending() { await SetupConsumer("direct:proc"); _template.Start(); var processor = new DelegateProcessor(async (ex, ct) => { ex.In.Body = "transformed"; ex.In.Headers["processed"] = true; }); var endpoint = _ctx.GetEndpoint("direct:proc"); _template.Send(endpoint, (IProcessor)processor); _receivedExchanges.Should().HaveCount(1); _receivedExchanges[0].In.Body.Should().Be("transformed"); _receivedExchanges[0].In.Headers["processed"].Should().Be(true); } // ── Async Send ── [Fact] public async Task SendAsync_ByEndpoint_DeliversBody() { await SetupConsumer("direct:async1"); _template.Start(); var endpoint = _ctx.GetEndpoint("direct:async1"); await _template.SendAsync(endpoint, "async-body"); _receivedExchanges.Should().HaveCount(1); _receivedExchanges[0].In.Body.Should().Be("async-body"); } [Fact] public async Task SendAsync_ByUri_DeliversBody() { await SetupConsumer("direct:async2"); _template.Start(); await _template.SendAsync("direct:async2", "async-by-uri"); _receivedExchanges.Should().HaveCount(1); _receivedExchanges[0].In.Body.Should().Be("async-by-uri"); } [Fact] public async Task SendAsync_Message_Works() { await SetupConsumer("direct:amsg"); _template.Start(); var endpoint = _ctx.GetEndpoint("direct:amsg"); var msg = new Message("async-msg"); await _template.SendAsync(endpoint, (IMessage)msg); _receivedExchanges.Should().HaveCount(1); _receivedExchanges[0].In.Body.Should().Be("async-msg"); } [Fact] public async Task SendAsync_MessageByUri_Works() { await SetupConsumer("direct:amsg2"); _template.Start(); var msg = new Message("async-msg-uri"); await _template.SendAsync("direct:amsg2", (IMessage)msg); _receivedExchanges.Should().HaveCount(1); _receivedExchanges[0].In.Body.Should().Be("async-msg-uri"); } // ── Request/Reply ── [Fact] public async Task RequestBody_ReturnsResponseFromOut() { await SetupConsumer("direct:echo", exchange => { exchange.Out = new Message($"echo:{exchange.In.Body}"); }); _template.Start(); var result = await _template.RequestBody("direct:echo", "hello"); result.Should().Be("echo:hello"); } [Fact] public async Task RequestBody_NoOut_ReturnsInBody() { await SetupConsumer("direct:passthrough"); _template.Start(); var result = await _template.RequestBody("direct:passthrough", "fallback"); result.Should().Be("fallback"); } [Fact] public async Task RequestBody_Typed_ReturnsConvertedResult() { await SetupConsumer("direct:typed", exchange => { exchange.Out = new Message(42); }); _template.Start(); var result = await _template.RequestBody("direct:typed", "ignored"); result.Should().Be(42); } [Fact] public async Task RequestBody_Typed_ByUri_Works() { await SetupConsumer("direct:tbyuri", exchange => { exchange.Out = new Message("response-value"); }); _template.Start(); var result = await _template.RequestBody("direct:tbyuri", "request"); result.Should().Be("response-value"); } [Fact] public async Task RequestBody_Typed_ReplyThatDoesNotConvert_Throws() { await SetupConsumer("direct:typed-bad", exchange => exchange.Out = new Message("not-a-number")); _template.Start(); var act = () => _template.RequestBody("direct:typed-bad", "request"); await act.Should().ThrowAsync("a reply that is not the asked type is an error, not a zero") .WithMessage("*String*Int32*"); } [Fact] public async Task RequestBody_Typed_NullableTarget_ConvertsTheReply() { await SetupConsumer("direct:typed-nullable", exchange => exchange.Out = new Message("42")); _template.Start(); var result = await _template.RequestBody("direct:typed-nullable", "request"); result.Should().Be(42); } // ── A reply that reads from resources of its exchange ── private sealed class ExchangeBoundStream : IExchangeBoundBody; [Fact] public async Task RequestBody_ExchangeBoundReply_IsRefusedAtTheCall() { await SetupConsumer("direct:bound", exchange => exchange.Out = new Message(new ExchangeBoundStream())); _template.Start(); var act = () => _template.RequestBody("direct:bound", "request"); await act.Should().ThrowAsync( "RequestBody ends the exchange before it returns, and the body could no longer be read") .WithMessage("*RequestAsync*"); } [Fact] public async Task RequestAsync_ExchangeBoundReply_IsReturnedWithItsExchange() { await SetupConsumer("direct:bound-async", exchange => exchange.Out = new Message(new ExchangeBoundStream())); _template.Start(); await using var exchange = await _template.RequestAsync("direct:bound-async", new Exchange(new Message("request"))); exchange.Out!.Body.Should().BeOfType("the caller reads it, then disposes the exchange"); } [Fact] public async Task RequestBody_SetsInOutPattern() { await SetupConsumer("direct:pattern"); _template.Start(); var endpoint = _ctx.GetEndpoint("direct:pattern"); await _template.RequestBody(endpoint, "check-pattern"); _receivedExchanges[0].Pattern.Should().Be(ExchangePattern.InOut); } // ── Producer Caching ── [Fact] public async Task Send_SameEndpointTwice_ReusesProducer() { // DirectComponent.CreateEndpoint caches endpoints, and now ProducerTemplate caches producers. // Sending twice to the same URI should only call CreateProducer once internally. await SetupConsumer("direct:cache-test"); _template.Start(); _template.Send("direct:cache-test", "first"); _template.Send("direct:cache-test", "second"); _receivedExchanges.Should().HaveCount(2); _receivedExchanges[0].In.Body.Should().Be("first"); _receivedExchanges[1].In.Body.Should().Be("second"); } [Fact] public async Task SendAsync_SameEndpointTwice_ReusesProducer() { await SetupConsumer("direct:async-cache"); _template.Start(); var endpoint = _ctx.GetEndpoint("direct:async-cache"); await _template.SendAsync(endpoint, "a"); await _template.SendAsync(endpoint, "b"); _receivedExchanges.Should().HaveCount(2); } // ── IDisposable ── [Fact] public void Dispose_PreventsSubsequentSend() { _template.Start(); _template.Dispose(); var act = () => _template.Send("direct:test", "body"); act.Should().Throw(); } [Fact] public async Task Dispose_PreventsSubsequentSendAsync() { _template.Start(); _template.Dispose(); var act = async () => await _template.SendAsync("direct:test", "body"); await act.Should().ThrowAsync(); } [Fact] public void Dispose_IsIdempotent() { _template.Start(); _template.Dispose(); var act = () => _template.Dispose(); act.Should().NotThrow(); } [Fact] public void Start_AfterDispose_Throws() { _template.Dispose(); var act = () => _template.Start(); act.Should().Throw(); } // ── Helper: captures exchanges for assertion ── private async Task SetupConsumer(string uri, Action? additionalAction = null) { var endpoint = _ctx.GetEndpoint(uri); var processor = new DelegateProcessor(async (exchange, ct) => { _receivedExchanges.Add(exchange); additionalAction?.Invoke(exchange); }); var consumer = endpoint.CreateConsumer(processor); await consumer.Start(); } // ── Pre-built exchange overloads (caller-owned) ── [Fact] public async Task Send_Exchange_ByUri_DeliversSameInstance() { await SetupConsumer("direct:ex-uri"); _template.Start(); var exchange = new Exchange(new Message("prebuilt")); exchange.Properties["carried"] = "yes"; _template.Send("direct:ex-uri", exchange); _receivedExchanges.Should().ContainSingle(); _receivedExchanges[0].Should().BeSameAs(exchange); // direct passes by reference _receivedExchanges[0].Properties["carried"].Should().Be("yes"); } [Fact] public async Task SendAsync_Exchange_ByEndpoint_DeliversSameInstance() { await SetupConsumer("direct:ex-async"); _template.Start(); var exchange = new Exchange(new Message("prebuilt-async")); var endpoint = _ctx.GetEndpoint("direct:ex-async"); await _template.SendAsync(endpoint, exchange); _receivedExchanges.Should().ContainSingle(); _receivedExchanges[0].Should().BeSameAs(exchange); } [Fact] public async Task SendAsync_Exchange_ByUri_Delivers() { await SetupConsumer("direct:ex-async-uri"); _template.Start(); var exchange = new Exchange(new Message("x")); await _template.SendAsync("direct:ex-async-uri", exchange); _receivedExchanges.Should().ContainSingle(); } [Fact] public async Task SendAsync_Exchange_DoesNotDisposeCallerOwnedExchange() { // The caller owns a pre-built exchange (e.g. a checkpoint snapshot): the template must // NOT dispose it, so the caller can reuse/inspect it after the send. await SetupConsumer("direct:ex-nodispose"); _template.Start(); var exchange = new Exchange(new Message("keep-alive")); await _template.SendAsync("direct:ex-nodispose", exchange); // Still usable after send — a disposed exchange would throw here. exchange.Properties["after"] = "still-alive"; exchange.In.Body.Should().Be("keep-alive"); } [Fact] public async Task RequestAsync_Exchange_SetsInOut_AndReturnsSameInstanceWithReply() { await SetupConsumer("direct:ex-req", ex => ex.Out = new Message("reply")); _template.Start(); var exchange = new Exchange(new Message("ask")); var result = await _template.RequestAsync("direct:ex-req", exchange); result.Should().BeSameAs(exchange); result.Pattern.Should().Be(ExchangePattern.InOut); result.Out!.Body.Should().Be("reply"); } [Fact] public void Send_Exchange_ByUri_BeforeStart_Throws() { var act = () => _template.Send("direct:whatever", new Exchange(new Message("x"))); act.Should().Throw().WithMessage("*not started*"); } } Path: redb-route/tests/redb.Route.Tests/Core/PropertyPlaceholderIntegrationTests.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/PropertyPlaceholderIntegrationTests.cs ---- using AwesomeAssertions; using Microsoft.Extensions.Configuration; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Tests.Core; /// /// End-to-end tests for property placeholders through the full DSL → Compiler → Engine pipeline: /// a live route whose From and To URIs carry {{key}} placeholders, started and /// driven with a real message, asserting the message actually reaches the resolved destination. /// Values are drawn from IConfiguration, context properties and inline defaults. /// public class PropertyPlaceholderIntegrationTests : IAsyncLifetime { private readonly RouteContext _context = new(); public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { await _context.DisposeAsync(); GC.SuppressFinalize(this); } private async Task StartAndGetProducer(string fromUri) { await _context.Start(); var producer = _context.GetEndpoint(fromUri).CreateProducer(); await producer.Start(); return producer; } [Fact] public async Task Placeholders_InFromAndTo_FromConfiguration_DeliverEndToEnd() { IConfiguration config = new ConfigurationBuilder() .AddInMemoryCollection(new Dictionary { ["orders.source"] = "direct://cfg-in", ["orders.dest"] = "direct://cfg-out", }) .Build(); _context.AddService(typeof(IConfiguration), config); var received = new List(); _context.AddRoutes(r => { r.From("direct://cfg-out").Process(e => received.Add(e.In.Body?.ToString())); // Both endpoints of the working route are placeholders resolved from IConfiguration. r.From("{{orders.source}}").To("{{orders.dest}}"); }); // The consumer is reachable through the resolved literal URI — proof the placeholder From bound it. var producer = await StartAndGetProducer("direct://cfg-in"); await producer.Process(new Exchange(new Message("order-42"))); received.Should().ContainSingle().Which.Should().Be("order-42"); } [Fact] public async Task Placeholder_DefaultValue_UsedInLiveRoute() { var received = new List(); _context.AddRoutes(r => { r.From("direct://def-out").Process(e => received.Add(e.In.Body?.ToString())); // The key is not configured anywhere → the inline default drives the destination. r.From("direct://def-in").To("direct://{{unset.dest:def-out}}"); }); var producer = await StartAndGetProducer("direct://def-in"); await producer.Process(new Exchange(new Message("payload"))); received.Should().ContainSingle().Which.Should().Be("payload"); } [Fact] public async Task Placeholder_FromContextProperty_DeliversEndToEnd() { // Container-free path: values come from context.SetProperty, no IConfiguration registered. _context.SetProperty("dest.queue", "prop-out"); var received = new List(); _context.AddRoutes(r => { r.From("direct://prop-out").Process(e => received.Add(e.In.Body?.ToString())); r.From("direct://prop-in").To("direct://{{dest.queue}}"); }); var producer = await StartAndGetProducer("direct://prop-in"); await producer.Process(new Exchange(new Message("hi"))); received.Should().ContainSingle().Which.Should().Be("hi"); } } Path: redb-route/tests/redb.Route.Tests/Core/PropertyPlaceholderTests.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/PropertyPlaceholderTests.cs ---- using AwesomeAssertions; using Microsoft.Extensions.Configuration; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Tests.Core; /// /// Tests for the Camel-style property-placeholder feature: {{key}} / {{key:default}} expansion in /// endpoint URIs, resolved from IConfiguration and context properties at compile time. /// public class PropertyPlaceholderTests { // ── Pure resolver ─────────────────────────────────────────────────────────── [Fact] public void Resolve_ReplacesKey_FromLookup() { var result = PropertyPlaceholderResolver.Resolve( "http://{{host}}/api", k => k == "host" ? "prod-host" : null); result.Should().Be("http://prod-host/api"); } [Fact] public void Resolve_UsesDefault_WhenKeyMissing() { var result = PropertyPlaceholderResolver.Resolve( "amqp://broker:{{port:5672}}/orders", _ => null); result.Should().Be("amqp://broker:5672/orders"); } [Fact] public void Resolve_PrefersValue_OverDefault() { var result = PropertyPlaceholderResolver.Resolve( "amqp://broker:{{port:5672}}", k => k == "port" ? "5673" : null); result.Should().Be("amqp://broker:5673"); } [Fact] public void Resolve_DefaultMayContainColon() { // A URL as a default value must survive the ':' key/default separator. var result = PropertyPlaceholderResolver.Resolve( "{{endpoint:http://localhost:8080/x}}", _ => null); result.Should().Be("http://localhost:8080/x"); } [Fact] public void Resolve_ExpandsMultiplePlaceholders() { var result = PropertyPlaceholderResolver.Resolve( "{{scheme}}://{{host}}:{{port}}/{{queue}}", k => k switch { "scheme" => "amqp", "host" => "h", "port" => "5672", "queue" => "orders", _ => null }); result.Should().Be("amqp://h:5672/orders"); } [Fact] public void Resolve_ToleratesWhitespace() { PropertyPlaceholderResolver.Resolve("x/{{ host }}", k => k == "host" ? "h" : null) .Should().Be("x/h"); PropertyPlaceholderResolver.Resolve("x/{{ port : 9 }}", _ => null) .Should().Be("x/9"); } [Fact] public void Resolve_NoPlaceholder_ReturnsUnchanged() { const string uri = "direct://plain"; PropertyPlaceholderResolver.Resolve(uri, _ => throw new InvalidOperationException("lookup must not run")) .Should().BeSameAs(uri); } [Fact] public void Resolve_MissingKeyNoDefault_ThrowsFailFast() { var act = () => PropertyPlaceholderResolver.Resolve("amqp://{{missing}}/x", _ => null); act.Should().Throw() .WithMessage("*missing*"); } [Fact] public void HasPlaceholder_DetectsBraces() { PropertyPlaceholderResolver.HasPlaceholder("a{{b}}c").Should().BeTrue(); PropertyPlaceholderResolver.HasPlaceholder("plain").Should().BeFalse(); PropertyPlaceholderResolver.HasPlaceholder(null).Should().BeFalse(); } // ── Integration through RouteContext.GetEndpoint ───────────────────────────── [Fact] public void GetEndpoint_ResolvesFromContextProperty() { using var context = new RouteContext(); context.SetProperty("queue", "orders"); // The resolved URI must land on the same normalized endpoint as the literal form. var viaPlaceholder = context.GetEndpoint("direct://{{queue}}"); var viaLiteral = context.GetEndpoint("direct://orders"); viaPlaceholder.Should().BeSameAs(viaLiteral); } [Fact] public void GetEndpoint_ResolvesFromConfiguration() { using var context = new RouteContext(); IConfiguration config = new ConfigurationBuilder() .AddInMemoryCollection(new Dictionary { ["queue"] = "invoices" }) .Build(); context.AddService(typeof(IConfiguration), config); context.GetEndpoint("direct://{{queue}}") .Should().BeSameAs(context.GetEndpoint("direct://invoices")); } [Fact] public void GetEndpoint_ConfigurationWinsOverContextProperty() { using var context = new RouteContext(); IConfiguration config = new ConfigurationBuilder() .AddInMemoryCollection(new Dictionary { ["queue"] = "from-config" }) .Build(); context.AddService(typeof(IConfiguration), config); context.SetProperty("queue", "from-property"); context.GetEndpoint("direct://{{queue}}") .Should().BeSameAs(context.GetEndpoint("direct://from-config")); } [Fact] public void GetEndpoint_NoConfiguration_ReadsEnvironment() { var name = "REDB_PLACEHOLDER_TEST_" + Guid.NewGuid().ToString("N"); Environment.SetEnvironmentVariable(name, "from-env"); try { using var context = new RouteContext(); context.GetEndpoint("direct://{{" + name + "}}") .Should().BeSameAs(context.GetEndpoint("direct://from-env")); } finally { Environment.SetEnvironmentVariable(name, null); } } [Fact] public void GetEndpoint_ContextPropertyWinsOverEnvironment() { var name = "REDB_PLACEHOLDER_TEST_" + Guid.NewGuid().ToString("N"); Environment.SetEnvironmentVariable(name, "from-env"); try { using var context = new RouteContext(); context.SetProperty(name, "from-property"); context.GetEndpoint("direct://{{" + name + "}}") .Should().BeSameAs(context.GetEndpoint("direct://from-property")); } finally { Environment.SetEnvironmentVariable(name, null); } } [Fact] public void GetEndpoint_WithConfiguration_DoesNotReadEnvironmentPastIt() { // The host builds IConfiguration and decides whether the environment takes part. var name = "REDB_PLACEHOLDER_TEST_" + Guid.NewGuid().ToString("N"); Environment.SetEnvironmentVariable(name, "from-env"); try { using var context = new RouteContext(); IConfiguration config = new ConfigurationBuilder().AddInMemoryCollection().Build(); context.AddService(typeof(IConfiguration), config); var act = () => context.GetEndpoint("direct://{{" + name + "}}"); act.Should().Throw().WithMessage("*" + name + "*"); } finally { Environment.SetEnvironmentVariable(name, null); } } [Fact] public void GetEndpoint_UnresolvedPlaceholder_Throws() { using var context = new RouteContext(); var act = () => context.GetEndpoint("direct://{{never-set}}"); act.Should().Throw() .WithMessage("*never-set*"); } } Path: redb-route/tests/redb.Route.Tests/Core/PushConsumerTests.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/PushConsumerTests.cs ---- using System.Collections.Concurrent; using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Configuration; using redb.Route.Core; using redb.Route.Processors; using redb.Route.Telemetry; namespace redb.Route.Tests.Core; /// /// with a fake client: the outcome of each message (Accepted, Rejected after the retries, /// Refused once a stop began, Returned when the stop ends it or the work after the route fails), the order of a stop /// (stop accepting, drain, then unsubscribe), the concurrency limit, and a lost subscription brought back by /// on the supervisor's schedule while the endpoint's health follows. /// public sealed class PushConsumerTests : IAsyncLifetime { private static readonly TimeSpan Wait = TimeSpan.FromSeconds(10); private RouteContext _context = null!; private FakeEndpoint _endpoint = null!; public Task InitializeAsync() { _context = new RouteContext(options: new RouteEngineOptions { Reconnect = new ReconnectOptions { Delay = TimeSpan.FromMilliseconds(100), MaxDelay = TimeSpan.FromMilliseconds(400) }, }); _context.AddComponent(new FakeComponent()); _endpoint = (FakeEndpoint)_context.GetEndpoint("fake://queue"); return Task.CompletedTask; } public async Task DisposeAsync() => await _context.DisposeAsync(); private FakeConsumer Consumer(Func route, int? maxConcurrency = null) => new(_endpoint, new DelegateProcessor(route), maxConcurrency); [Fact] public async Task A_route_that_ends_well_is_Accepted_and_a_failing_one_Rejected_after_its_attempts() { var runs = 0; var consumer = Consumer((ex, _) => { Interlocked.Increment(ref runs); if ((string)ex.In.Body! == "bad") ex.Exception = new InvalidOperationException("route failed"); return Task.CompletedTask; }); await consumer.Start(); (await consumer.Deliver("good")).Outcome.Should().Be(PushOutcome.Accepted); var bad = await consumer.Deliver("bad", new PushRetry(3, TimeSpan.Zero)); bad.Outcome.Should().Be(PushOutcome.Rejected); bad.Failure!.Message.Should().Be("route failed"); runs.Should().Be(4, "one run for the good message, three attempts for the bad one"); consumer.CreatedExchanges.Should().Be(4, "each attempt runs on a fresh exchange"); await consumer.Stop(); } [Fact] public async Task A_thrown_failure_and_a_rollback_only_exchange_are_Rejected_too() { var consumer = Consumer((ex, _) => (string)ex.In.Body! == "throw" ? throw new InvalidOperationException("escaped") : MarkRollbackOnly(ex)); await consumer.Start(); (await consumer.Deliver("throw")).Outcome.Should().Be(PushOutcome.Rejected); (await consumer.Deliver("rollback")).Outcome.Should().Be(PushOutcome.Rejected); await consumer.Stop(); } [Fact] public async Task A_message_after_the_stop_began_is_Refused_and_not_run() { var runs = 0; var consumer = Consumer((_, _) => { Interlocked.Increment(ref runs); return Task.CompletedTask; }); await consumer.Start(); await consumer.Stop(); (await consumer.Deliver("late")).Outcome.Should().Be(PushOutcome.Refused); runs.Should().Be(0); } [Fact] public async Task A_message_waiting_for_a_slot_when_the_stop_begins_is_Refused() { var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var runs = 0; var consumer = Consumer(async (_, _) => { Interlocked.Increment(ref runs); await release.Task; }, maxConcurrency: 1); await consumer.Start(); var first = consumer.Deliver("first"); (await Until(() => Volatile.Read(ref runs) == 1)).Should().BeTrue(); var waiting = consumer.Deliver("waiting"); var stop = consumer.Stop(); release.SetResult(); (await first).Outcome.Should().Be(PushOutcome.Accepted, "the message in work drains"); (await waiting).Outcome.Should().Be(PushOutcome.Refused, "the stop began while it waited for its slot"); await stop; runs.Should().Be(1); } [Fact] public async Task A_stop_behind_a_stuck_message_ends_by_the_drain_window_and_Refuses_the_one_waiting_for_its_slot() { // The slot wait takes no token: what bounds the stop is the drain, which cancels the stuck message; its slot // goes to the waiter, which then sees the stop and is refused without running. var runs = 0; var consumer = Consumer(async (_, ct) => { Interlocked.Increment(ref runs); await Task.Delay(Timeout.Infinite, ct); }, maxConcurrency: 1); consumer.SetDrainTimeout(TimeSpan.FromMilliseconds(200)); await consumer.Start(); var stuck = consumer.Deliver("stuck"); (await Until(() => consumer.InWork == 1)).Should().BeTrue(); var waiting = consumer.Deliver("waiting"); await Task.Delay(50); var clock = System.Diagnostics.Stopwatch.StartNew(); await consumer.Stop().WaitAsync(Wait); clock.Stop(); (await stuck.WaitAsync(Wait)).Outcome.Should().Be(PushOutcome.Returned, "the drain window cancelled it"); (await waiting.WaitAsync(Wait)).Outcome.Should().Be(PushOutcome.Refused, "it got its slot only after the stop began"); runs.Should().Be(1, "the waiting message never ran"); clock.Elapsed.Should().BeLessThan(TimeSpan.FromSeconds(3), "the stop is bounded by the 200 ms drain window"); } [Fact] public async Task The_stop_stops_accepting_drains_and_then_unsubscribes() { var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var consumer = Consumer(async (_, _) => await release.Task); await consumer.Start(); var inWork = consumer.Deliver("in work"); (await Until(() => consumer.InWork == 1)).Should().BeTrue(); var stop = consumer.Stop(); (await Until(() => consumer.Steps.Contains("stop accepting"))).Should().BeTrue(); await Task.Delay(200); consumer.Steps.Should().NotContain("unsubscribe", "the drain waits for the message in work"); release.SetResult(); await stop; (await inWork).Outcome.Should().Be(PushOutcome.Accepted); consumer.Steps.Should().Equal("subscribe", "stop accepting", "unsubscribe"); } [Fact] public async Task A_message_whose_drain_window_runs_out_is_Returned() { var consumer = Consumer(async (_, ct) => await Task.Delay(Timeout.Infinite, ct)); consumer.SetDrainTimeout(TimeSpan.FromMilliseconds(200)); await consumer.Start(); var inWork = consumer.Deliver("slow"); (await Until(() => consumer.InWork == 1)).Should().BeTrue(); await consumer.Stop().WaitAsync(Wait); (await inWork).Outcome.Should().Be(PushOutcome.Returned); } [Fact] public async Task A_stop_during_the_pause_before_the_next_attempt_Returns_the_message() { var runs = 0; var consumer = Consumer((ex, _) => { Interlocked.Increment(ref runs); ex.Exception = new InvalidOperationException("route failed"); return Task.CompletedTask; }); await consumer.Start(); var retried = consumer.Deliver("bad", new PushRetry(5, TimeSpan.FromSeconds(30))); (await Until(() => Volatile.Read(ref runs) == 1)).Should().BeTrue(); await consumer.Stop().WaitAsync(Wait); (await retried).Outcome.Should().Be(PushOutcome.Returned); runs.Should().Be(1); } [Fact] public async Task A_failing_follow_up_after_the_route_Returns_the_message_with_its_failure() { var consumer = Consumer((_, _) => Task.CompletedTask); await consumer.Start(); var dispatch = await consumer.Deliver("reply", afterRoute: (_, _) => throw new IOException("reply channel gone")); dispatch.Outcome.Should().Be(PushOutcome.Returned); dispatch.Failure.Should().BeOfType(); await consumer.Stop(); } [Fact] public async Task No_more_messages_run_at_once_than_the_concurrency_limit() { var running = 0; var peak = 0; var consumer = Consumer(async (_, _) => { var now = Interlocked.Increment(ref running); InterlockedMax(ref peak, now); await Task.Delay(50); Interlocked.Decrement(ref running); }, maxConcurrency: 2); await consumer.Start(); var all = await Task.WhenAll(Enumerable.Range(0, 10).Select(i => consumer.Deliver($"m{i}"))); all.Should().AllSatisfy(d => d.Outcome.Should().Be(PushOutcome.Accepted)); peak.Should().Be(2); await consumer.Stop(); } [Fact] public async Task A_lost_subscription_is_brought_back_on_the_schedule_and_health_follows() { var consumer = Consumer((_, _) => Task.CompletedTask); await consumer.Start(); consumer.FailNextSubscribes = 1; var resubscribe = consumer.LoseSubscription(); _endpoint.HealthStatus.Should().NotBe(EndpointHealthStatus.Healthy, "the subscription is lost"); consumer.LoseSubscription().Should().BeSameAs(resubscribe, "one loop at a time"); (await resubscribe.WaitAsync(Wait)).Should().BeTrue(); consumer.Steps.Should().Equal("subscribe", "subscribe failed", "subscribe"); _endpoint.Reconnects.Should().Be(1); _endpoint.HealthStatus.Should().Be(EndpointHealthStatus.Healthy); await consumer.Stop(); _endpoint.HealthReason.Should().NotContain("fake channel", "the stopped consumer's supervisor is removed"); } [Fact] public async Task A_stop_during_a_resubscribe_ends_it_and_nothing_subscribes_after_the_stop() { var consumer = Consumer((_, _) => Task.CompletedTask); await consumer.Start(); consumer.FailNextSubscribes = int.MaxValue; var resubscribe = consumer.LoseSubscription(); (await Until(() => consumer.Steps.Count(s => s == "subscribe failed") >= 1)).Should().BeTrue(); await consumer.Stop().WaitAsync(Wait); (await resubscribe.WaitAsync(Wait)).Should().BeFalse("the stop ended the loop"); var steps = consumer.Steps.Length; await Task.Delay(600); consumer.Steps.Length.Should().Be(steps, "no attempt after the stop"); consumer.Steps.Last().Should().Be("unsubscribe"); } private static Task MarkRollbackOnly(IExchange exchange) { exchange.MarkRollbackOnly(); return Task.CompletedTask; } private static void InterlockedMax(ref int target, int value) { int current; while ((current = Volatile.Read(ref target)) < value && Interlocked.CompareExchange(ref target, value, current) != current) { } } private static async Task Until(Func done) { var deadline = DateTime.UtcNow + Wait; while (DateTime.UtcNow < deadline) { if (done()) return true; await Task.Delay(20); } return done(); } private sealed class FakeConsumer(FakeEndpoint endpoint, IProcessor processor, int? maxConcurrency) : PushConsumer(processor, maxConcurrency) { private readonly ConcurrentQueue _steps = new(); private ConnectionSupervisor? _channel; private int _created; public string[] Steps => _steps.ToArray(); public int CreatedExchanges => Volatile.Read(ref _created); public int InWork => InflightCount; public int FailNextSubscribes; protected override IEndpoint ConsumerEndpoint => endpoint; protected override string ConsumerName => "fake:queue"; public void SetDrainTimeout(TimeSpan timeout) => DrainTimeout = timeout; protected override Task SubscribeAsync(CancellationToken ct) { _channel ??= SuperviseConnection("fake channel"); return Subscribe(); } private Task Subscribe() { if (Interlocked.Decrement(ref FailNextSubscribes) >= 0) { _steps.Enqueue("subscribe failed"); throw new IOException("channel refused"); } Interlocked.Exchange(ref FailNextSubscribes, 0); _steps.Enqueue("subscribe"); return Task.CompletedTask; } protected override Task StopAcceptingAsync(CancellationToken ct) { _steps.Enqueue("stop accepting"); return Task.CompletedTask; } protected override Task UnsubscribeAsync(CancellationToken ct) { _steps.Enqueue("unsubscribe"); _channel = null; return Task.CompletedTask; } /// The broker closed the channel: report it and resubscribe, as a connector's shutdown handler does. public Task LoseSubscription() { _channel!.Lost(new IOException("channel closed by the broker")); return ResubscribeAsync(_channel, _ => Subscribe()); } public Task Deliver(string body, PushRetry? retry = null, Func? afterRoute = null) => Task.Run(() => DispatchAsync(() => { Interlocked.Increment(ref _created); return new Exchange(new Message(body)); }, default(TransportSpan), retry, afterRoute)); } private sealed class FakeComponent : ComponentBase { public override string Scheme => "fake"; public override IEndpoint CreateEndpoint(EndpointUri uri) => new FakeEndpoint(uri, this); } private sealed class FakeOptions : EndpointOptions { public override void Validate() { } } private sealed class FakeEndpoint(EndpointUri uri, IComponent component) : EndpointBase(uri, component, new FakeOptions()) { public override IProducer CreateProducer() => throw new NotSupportedException(); public override IConsumer CreateConsumer(IProcessor processor) => throw new NotSupportedException(); } } Path: redb-route/tests/redb.Route.Tests/Core/ReplayCheckpointTests.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/ReplayCheckpointTests.cs ---- using AwesomeAssertions; using Microsoft.Extensions.DependencyInjection; using redb.Route.Abstractions; using redb.Route.Components; using redb.Route.Core; namespace redb.Route.Tests.Core; /// /// End-to-end tests for replay checkpoints (.Replayable save-points): snapshot capture on /// pass, tail replay from a snapshot via , prefix is NOT /// re-run, marker registry, duplicate detection, graceful degrade for a non-snapshot-able body. /// public class ReplayCheckpointTests : IAsyncLifetime { private readonly RouteContext _ctx = new("replay-test"); public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { await _ctx.DisposeAsync(); GC.SuppressFinalize(this); } private static string Body(IExchange ex) => (string)ex.In.Body!; private async Task Send(string uri, object body) { var pt = new ProducerTemplate(_ctx); pt.Start(); await pt.SendAsync(uri, body); } [Fact] public async Task Marker_CapturesSnapshotIntoRouteCheckpoint_OnPass() { IExchange? seen = null; _ctx.AddRoutes(r => r .From("direct:cap").RouteId("cap") .Replayable("m1") .Process(ex => seen = ex)); await _ctx.Start(); await Send("direct:cap", "hello"); seen.Should().NotBeNull(); var cp = seen!.Properties[RouteCheckpoint.PropertyKey].Should().BeOfType().Subject; cp.RouteId.Should().Be("cap"); cp.MarkerName.Should().Be("m1"); Body(cp.Snapshot).Should().Be("hello"); } [Fact] public async Task Replay_RunsTailFromSnapshot_WithoutRerunningPrefix() { var trail = new List(); _ctx.AddRoutes(r => r .From("direct:pay").RouteId("pay") .Process(_ => trail.Add("charge")) // prefix (a side effect we must NOT repeat) .Replayable("after-charge") .Process(_ => trail.Add("receipt"))); // tail (the part replay re-runs) await _ctx.Start(); await Send("direct:pay", "order-1"); trail.Should().Equal("charge", "receipt"); // Replay from a fresh snapshot: only the tail should run again. var snapshot = new Exchange(new Message("order-1")); await _ctx.ReplayAsync("pay", "after-charge", snapshot); trail.Should().Equal("charge", "receipt", "receipt"); // charge NOT repeated } [Fact] public async Task Replay_FromCapturedCheckpointSnapshot_Works() { var tailRuns = 0; IExchange? captured = null; _ctx.AddRoutes(r => r .From("direct:cap2").RouteId("cap2") .Process(ex => captured = ex) .Replayable("mk") .Process(_ => tailRuns++)); await _ctx.Start(); await Send("direct:cap2", "x"); tailRuns.Should().Be(1); var cp = (RouteCheckpoint)captured!.Properties[RouteCheckpoint.PropertyKey]; await _ctx.ReplayAsync(cp.RouteId, cp.MarkerName, cp.Snapshot); tailRuns.Should().Be(2); } [Fact] public async Task ImplicitMarker_AtRouteStart_BodyIsWholePipeline_NoEndNeeded() { var runs = 0; _ctx.AddRoutes(r => r .From("direct:impl").RouteId("impl") .Replayable("start") // no End — body = whole pipeline .Process(_ => runs++)); await _ctx.Start(); _ctx.GetReplayMarkers().Should().Contain(("impl", "start")); await _ctx.ReplayAsync("impl", "start", new Exchange(new Message("y"))); runs.Should().Be(1); } [Fact] public async Task LastMarkerWins_WhenSeveralArePassed() { IExchange? seen = null; _ctx.AddRoutes(r => r .From("direct:multi").RouteId("multi") .Replayable("m1").Process(_ => { }).EndReplayable() .Replayable("m2").Process(ex => seen = ex)); await _ctx.Start(); await Send("direct:multi", "z"); ((RouteCheckpoint)seen!.Properties[RouteCheckpoint.PropertyKey]).MarkerName.Should().Be("m2"); _ctx.GetReplayMarkers().Select(m => m.MarkerName).Should().Contain(new[] { "m1", "m2" }); } [Fact] public async Task LambdaBody_Works() { var runs = 0; _ctx.AddRoutes(r => r .From("direct:lam").RouteId("lam") .Process(_ => { }) .Replayable("mk", b => b.Process(_ => runs++))); await _ctx.Start(); await _ctx.ReplayAsync("lam", "mk", new Exchange(new Message("q"))); runs.Should().Be(1); } [Fact] public async Task ReplayAsync_UnknownMarker_Throws() { _ctx.AddRoutes(r => r.From("direct:u").RouteId("u").Replayable("known").Process(_ => { })); await _ctx.Start(); var act = () => _ctx.ReplayAsync("u", "nope", new Exchange(new Message("x"))); await act.Should().ThrowAsync().WithMessage("*No replay checkpoint*"); } [Fact] public async Task DuplicateMarkerName_InRoute_FailsCompilation() { _ctx.AddRoutes(r => r .From("direct:dup").RouteId("dup") .Replayable("same").Process(_ => { }).EndReplayable() .Replayable("same").Process(_ => { })); var act = () => _ctx.Start(); await act.Should().ThrowAsync().WithMessage("*Duplicate replay marker*"); } [Fact] public async Task NonSnapshotableBody_DoesNotBreakRoute_DegradesGracefully() { var reached = false; _ctx.AddRoutes(r => r .From("direct:poco").RouteId("poco") .Replayable("m") .Process(_ => reached = true)); await _ctx.Start(); // a plain POCO body is not snapshot-able → capture is skipped, route still runs await Send("direct:poco", new { Name = "x" }); reached.Should().BeTrue(); } [Fact] public async Task ExposedMarker_IsAddressableAsDirectEndpoint() { var runs = 0; _ctx.AddRoutes(r => r .From("direct:exp").RouteId("exp") .Process(_ => { }) .Replayable("mk", exposed: true) .Process(_ => runs++)); await _ctx.Start(); await Send(RouteCheckpoint.EndpointUri("exp", "mk"), "payload"); runs.Should().Be(1); } [Fact] public async Task ExposedMarker_ReachableViaTo_FromAnotherRoute() { var runs = 0; _ctx.AddRoutes(r => r .From("direct:host").RouteId("host") .Replayable("mk", exposed: true) .Process(_ => runs++)); _ctx.AddRoutes(r => r .From("direct:caller").RouteId("caller") .To(RouteCheckpoint.EndpointUri("host", "mk"))); await _ctx.Start(); await Send("direct:caller", "x"); runs.Should().Be(1); } [Fact] public async Task NonExposedMarker_IsNotAddressable() { _ctx.AddRoutes(r => r .From("direct:intl").RouteId("intl") .Replayable("mk") // default: internal only .Process(_ => { })); await _ctx.Start(); var act = () => Send(RouteCheckpoint.EndpointUri("intl", "mk"), "x"); await act.Should().ThrowAsync().WithMessage("*No consumer registered*"); } private sealed class TrackedConnection(Action onDispose) : IDisposable { public void Dispose() => onDispose(); } [Fact] public async Task Replay_DisposesScopedConnectionsTheTailCreated_NoLeak() { // The tail resolves its own scoped SQL/redb service (a fresh connection) from the context // provider and caches its scope on the exchange (as GetRedbService does under __redb_scope:*). // Replaying via ReplayAsync must dispose that scope — else every replay leaks a connection. var disposals = 0; var services = new ServiceCollection(); services.AddScoped(_ => new TrackedConnection(() => Interlocked.Increment(ref disposals))); await using var provider = services.BuildServiceProvider(); await using var ctx = new RouteContext(provider, "leak-test"); ctx.AddComponent(new DirectComponent()); var factory = provider.GetRequiredService(); ctx.AddRoutes(r => r .From("direct:leak").RouteId("leak") .Replayable("m") .Process(ex => { var scope = factory.CreateScope(); _ = scope.ServiceProvider.GetRequiredService(); // "open a connection" ex.Properties["__redb_scope:test"] = scope; // cached as the redb ext does })); await ctx.Start(); await ctx.ReplayAsync("leak", "m", new Exchange(new Message("x"))); disposals.Should().Be(1, "the scoped connection the tail created must be released after replay"); } [Fact] public async Task NoMarkers_NoCheckpointCaptured() { IExchange? seen = null; _ctx.AddRoutes(r => r.From("direct:plain").RouteId("plain").Process(ex => seen = ex)); await _ctx.Start(); await Send("direct:plain", "hi"); seen!.Properties.ContainsKey(RouteCheckpoint.PropertyKey).Should().BeFalse(); _ctx.GetReplayMarkers().Should().BeEmpty(); } } Path: redb-route/tests/redb.Route.Tests/Core/ResolveOptionTests.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/ResolveOptionTests.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Expressions; using AwesomeAssertions; namespace redb.Route.Tests.Core; public class ResolveOptionTests { // --- ResolveOption --- [Fact] public void ResolveOption_Null_ReturnsNull() { var opts = new TestEndpointOptions { Host = "any" }; opts.ResolveOption(null, new Exchange()).Should().BeNull(); } [Fact] public void ResolveOption_StaticString_ReturnsAsIs() { var opts = new TestEndpointOptions { Host = "any" }; opts.ResolveOption("plain-value", new Exchange()).Should().Be("plain-value"); } [Fact] public void ResolveOption_EmptyString_ReturnsEmpty() { var opts = new TestEndpointOptions { Host = "any" }; opts.ResolveOption("", new Exchange()).Should().BeEmpty(); } [Fact] public void ResolveOption_DollarWithoutBrace_ReturnsAsIs() { var opts = new TestEndpointOptions { Host = "any" }; opts.ResolveOption("price$100", new Exchange()).Should().Be("price$100"); } [Fact] public void ResolveOption_HeaderExpression_ResolvesFromExchange() { var opts = new TestEndpointOptions { Host = "any" }; var msg = new Message("body"); msg.Headers["region"] = "us-east"; var exchange = new Exchange(msg); opts.ResolveOption("${header.region}", exchange).Should().Be("us-east"); } [Fact] public void ResolveOption_MixedTemplate_ResolvesExpressionParts() { var opts = new TestEndpointOptions { Host = "any" }; var msg = new Message(); msg.Headers["env"] = "prod"; msg.Headers["id"] = "42"; var exchange = new Exchange(msg); opts.ResolveOption("server-${header.env}-node-${header.id}", exchange) .Should().Be("server-prod-node-42"); } [Fact] public void ResolveOption_PropertyExpression_ResolvesFromProperties() { var opts = new TestEndpointOptions { Host = "any" }; var exchange = new Exchange(new Message()); exchange.Properties["token"] = "abc123"; opts.ResolveOption("Bearer ${property.token}", exchange) .Should().Be("Bearer abc123"); } [Fact] public void ResolveOption_CachesCompiledTemplate() { var opts = new TestEndpointOptions { Host = "any" }; var template = "${header.x}"; var msg1 = new Message(); msg1.Headers["x"] = "first"; var e1 = new Exchange(msg1); var msg2 = new Message(); msg2.Headers["x"] = "second"; var e2 = new Exchange(msg2); // Same template, different exchanges → different results (but compiled once) opts.ResolveOption(template, e1).Should().Be("first"); opts.ResolveOption(template, e2).Should().Be("second"); } [Fact] public void ResolveOption_DifferentTemplates_CachedIndependently() { var opts = new TestEndpointOptions { Host = "any" }; var msg = new Message(); msg.Headers["a"] = "alpha"; msg.Headers["b"] = "beta"; var exchange = new Exchange(msg); opts.ResolveOption("${header.a}", exchange).Should().Be("alpha"); opts.ResolveOption("${header.b}", exchange).Should().Be("beta"); } // --- BindDynamicValue with ${...} expressions --- [Fact] public void BindFromUri_DynamicValueWithExpression_CreatesDynamic() { var opts = new TestEndpointOptions(); opts.BindFromUri(new Dictionary { ["key"] = "${header.orderId}" }); opts.Key.Should().NotBeNull(); opts.Key!.Value.IsDynamic.Should().BeTrue(); var msg = new Message(); msg.Headers["orderId"] = "ORD-999"; var exchange = new Exchange(msg); opts.Key!.Value.Resolve(exchange).Should().Be("ORD-999"); } [Fact] public void BindFromUri_DynamicValueWithMixedExpression_CreatesDynamic() { var opts = new TestEndpointOptions(); opts.BindFromUri(new Dictionary { ["key"] = "prefix-${header.id}-suffix" }); opts.Key.Should().NotBeNull(); opts.Key!.Value.IsDynamic.Should().BeTrue(); var msg = new Message(); msg.Headers["id"] = "42"; var exchange = new Exchange(msg); opts.Key!.Value.Resolve(exchange).Should().Be("prefix-42-suffix"); } [Fact] public void BindFromUri_DynamicValueStaticString_CreatesStatic() { var opts = new TestEndpointOptions(); opts.BindFromUri(new Dictionary { ["key"] = "static-key" }); opts.Key.Should().NotBeNull(); opts.Key!.Value.IsDynamic.Should().BeFalse(); opts.Key!.Value.Resolve(new Exchange()).Should().Be("static-key"); } [Fact] public void BindFromUri_DynamicValueInt_ExpressionGoesToUnmapped() { // int properties can't hold ${...} expressions — ConvertValue fails → unmapped var opts = new TestEndpointOptions(); opts.BindFromUri(new Dictionary { ["ttl"] = "${header.ttl}" }); // DynamicValue with ${...} → BindDynamicValue detects expression, creates dynamic // Actually, StringExpression wrapped in DynamicValue — it tries Evaluate opts.Ttl.Should().NotBeNull(); opts.Ttl!.Value.IsDynamic.Should().BeTrue(); } [Fact] public void BindFromUri_IntPropertyWithExpression_IsRefused() { // Plain int property (not DynamicValue) can't hold ${...}. It used to land among the // unmapped parameters and leave the port at its default without a word. var opts = new TestEndpointOptions(); var act = () => opts.BindFromUri(new Dictionary { ["port"] = "${header.port}" }); act.Should().Throw().WithMessage("*'port=${header.port}'*does not accept ${...} expressions*"); } // --- DynamicValue.FromExpression(IExpression) --- [Fact] public void FromExpression_IExpression_ResolvesPerMessage() { var expr = new StringExpression("${header.key}"); var dv = DynamicValue.FromExpression(expr); dv.IsDynamic.Should().BeTrue(); var msg = new Message(); msg.Headers["key"] = "resolved-value"; dv.Resolve(new Exchange(msg)).Should().Be("resolved-value"); } [Fact] public void FromExpression_IExpression_NullThrows() { var act = () => DynamicValue.FromExpression((IExpression)null!); act.Should().Throw(); } [Fact] public void FromExpression_IExpression_DifferentMessages_DifferentResults() { var expr = new StringExpression("user-${header.userId}"); var dv = DynamicValue.FromExpression(expr); var msg1 = new Message(); msg1.Headers["userId"] = "alice"; var msg2 = new Message(); msg2.Headers["userId"] = "bob"; dv.Resolve(new Exchange(msg1)).Should().Be("user-alice"); dv.Resolve(new Exchange(msg2)).Should().Be("user-bob"); } // --- End-to-end: URI → BindFromUri → ResolveOption flow --- [Fact] public void EndToEnd_ExpressionInStringProperty_ResolvedViaResolveOption() { // Simulate: kafka:topic?host=${header.target} var opts = new TestEndpointOptions(); opts.BindFromUri(new Dictionary { ["host"] = "${header.target}" }); // Host is a plain string property, stores "${header.target}" as-is opts.Host.Should().Be("${header.target}"); // Producer calls ResolveOption to resolve per message var msg = new Message(); msg.Headers["target"] = "prod-server-1"; var exchange = new Exchange(msg); opts.ResolveOption(opts.Host, exchange).Should().Be("prod-server-1"); } [Fact] public void EndToEnd_StaticStringProperty_PassesThroughResolveOption() { var opts = new TestEndpointOptions(); opts.BindFromUri(new Dictionary { ["host"] = "static-server" }); opts.Host.Should().Be("static-server"); // No ${...} → passes through without compilation opts.ResolveOption(opts.Host, new Exchange()).Should().Be("static-server"); } [Fact] public void EndToEnd_DynamicValueProperty_ResolvedViaResolve() { // DynamicValue with ${...} → dynamic resolve var opts = new TestEndpointOptions(); opts.BindFromUri(new Dictionary { ["key"] = "${header.partitionKey}" }); var msg = new Message(); msg.Headers["partitionKey"] = "region-eu"; var exchange = new Exchange(msg); opts.Key!.Value.Resolve(exchange).Should().Be("region-eu"); } [Fact] public void EndToEnd_MultipleExpressionProperties_IndependentResolution() { var opts = new TestEndpointOptions(); opts.BindFromUri(new Dictionary { ["host"] = "${header.target}", ["key"] = "${property.routingKey}" }); var msg = new Message(); msg.Headers["target"] = "broker-3"; var exchange = new Exchange(msg); exchange.Properties["routingKey"] = "orders.eu"; opts.ResolveOption(opts.Host, exchange).Should().Be("broker-3"); opts.Key!.Value.Resolve(exchange).Should().Be("orders.eu"); } } Path: redb-route/tests/redb.Route.Tests/Core/RouteBuilderDiscoveryTests.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/RouteBuilderDiscoveryTests.cs ---- using System.Reflection; using Microsoft.Extensions.DependencyInjection; using redb.Route.Core; using redb.Route.Extensions; using redb.Route.TestKit; using redb.Route.Tests.Core.DiscoveryFixtures; using redb.Route.Tests.Core.DiscoveryFixtures.Injected; using redb.Route.Tests.Core.DiscoveryFixtures.NoDefaultConstructor; using redb.Route.Tests.Core.DiscoveryFixtures.Throwing; namespace redb.Route.Tests.Core { /// /// AddRoutes(Assembly[]) on the context and AddRouteBuilders(Assembly[]) in the host: which types are /// taken, in what order, and that nothing is skipped or duplicated silently. The fixtures live in their own /// namespaces so the filter can take exactly them from this assembly, which holds many other builders. /// public class RouteBuilderDiscoveryTests { private static readonly Assembly ThisAssembly = typeof(RouteBuilderDiscoveryTests).Assembly; private static readonly TimeSpan Wait = TimeSpan.FromSeconds(2); private static Func InNamespace(string ns) => t => t.Namespace == ns; private const string Plain = "redb.Route.Tests.Core.DiscoveryFixtures"; [Fact] public void Find_TakesPublicConcreteClosedBuilders_ByFullName() { var types = RouteBuilderDiscovery.FindBuilderTypes([ThisAssembly], InNamespace(Plain)); types.Should().Equal( [typeof(AlphaRoutes), typeof(BetaRoutes), typeof(Holder.NestedRoutes)], "abstract, open generic and non-public builders are not candidates; the order is by full name"); } [Fact] public void Find_TheCoreAssembly_HasNoCandidate() { // RouteBuilder is abstract and InlineRouteBuilder is excluded: scanning the engine adds nothing. RouteBuilderDiscovery.FindBuilderTypes([typeof(RouteContext).Assembly], null).Should().BeEmpty(); } [Fact] public void Find_WithoutAnAssembly_Throws() { var act = () => RouteBuilderDiscovery.FindBuilderTypes([], null); act.Should().Throw(); } [Fact] public async Task AddRoutes_StartsTheDiscoveredRoutes() { await using var ctx = new RouteContext(); ctx.AddRoutes([ThisAssembly], InNamespace(Plain)); await ctx.Start(); await ctx.SendBody("direct://discovery-alpha", "a"); await ctx.SendBody("direct://discovery-nested", "n"); await ctx.Mock("mock://discovery-alpha").ExpectBodies("a").AssertIsSatisfiedAsync(Wait); await ctx.Mock("mock://discovery-nested").ExpectBodies("n").AssertIsSatisfiedAsync(Wait); } [Fact] public void AddRoutes_FilterLeavesABuilderOut() { using var ctx = new RouteContext(); ctx.AddRoutes([ThisAssembly], t => InNamespace(Plain)(t) && t != typeof(BetaRoutes)); ctx.RouteBuilders.Select(b => b.GetType()).Should().Equal(typeof(AlphaRoutes), typeof(Holder.NestedRoutes)); } [Fact] public void AddRoutes_WithoutAParameterlessConstructor_ThrowsAndAddsNothing() { using var ctx = new RouteContext(); var act = () => ctx.AddRoutes([ThisAssembly], t => InNamespace(Plain)(t) || InNamespace(Plain + ".NoDefaultConstructor")(t)); act.Should().Throw().WithMessage($"*{typeof(NeedsAnArgumentRoutes).FullName}*"); ctx.RouteBuilders.Should().BeEmpty("every builder is created before any is added"); } [Fact] public void AddRoutes_AConstructorThatThrows_ThrowsWithTheTypeAndTheCause() { using var ctx = new RouteContext(); var act = () => ctx.AddRoutes([ThisAssembly], InNamespace(Plain + ".Throwing")); act.Should().Throw() .WithMessage($"*{typeof(ThrowingRoutes).FullName}*") .WithInnerException(); ctx.RouteBuilders.Should().BeEmpty(); } [Fact] public void AddRoutes_ATypeAlreadyAddedExplicitly_Throws() { using var ctx = new RouteContext(); ctx.AddRoutes(new AlphaRoutes()); var act = () => ctx.AddRoutes([ThisAssembly], InNamespace(Plain)); act.Should().Throw().WithMessage($"*{typeof(AlphaRoutes).FullName}*"); ctx.RouteBuilders.Should().ContainSingle("the discovery added nothing"); } [Fact] public void AddRoutes_ADiscoveredTypeAddedExplicitly_Throws() { using var ctx = new RouteContext(); ctx.AddRoutes([ThisAssembly], InNamespace(Plain)); var act = () => ctx.AddRoutes(new AlphaRoutes()); act.Should().Throw().WithMessage($"*{typeof(AlphaRoutes).FullName}*"); } [Fact] public void AddRoutes_TheSameAssemblyTwice_Throws() { using var ctx = new RouteContext(); ctx.AddRoutes([ThisAssembly], InNamespace(Plain)); var act = () => ctx.AddRoutes([ThisAssembly], InNamespace(Plain)); act.Should().Throw(); } [Fact] public void AddRoutes_TwoInstancesOfAnExplicitType_StillAllowed() { // A builder with constructor arguments is legitimately added twice with different ones; only discovery // claims a type for itself. using var ctx = new RouteContext(); ctx.AddRoutes(new NeedsAnArgumentRoutes("one")); ctx.AddRoutes(new NeedsAnArgumentRoutes("two")); ctx.RouteBuilders.Should().HaveCount(2); } [Fact] public void AddRouteBuilders_InjectsTheConstructor() { var services = new ServiceCollection(); services.AddLogging(); services.AddSingleton(new DiscoveryGreeting("hello")); services.AddRedbRoute(route => route.AddRouteBuilders([ThisAssembly], InNamespace(Plain + ".Injected"))); using var sp = services.BuildServiceProvider(); var ctx = sp.GetRequiredService(); foreach (var configurator in sp.GetServices()) configurator.Configure(ctx); ctx.RouteBuilders.Should().ContainSingle() .Which.Should().BeOfType() .Which.Greeting.Text.Should().Be("hello"); sp.GetRequiredService().Should().BeSameAs(sp.GetRequiredService()); } [Fact] public void AddRouteBuilders_ATypeAlreadyRegistered_Throws() { var services = new ServiceCollection(); var act = () => services.AddRedbRoute(route => route .AddRouteBuilder() .AddRouteBuilders([ThisAssembly], InNamespace(Plain))); act.Should().Throw().WithMessage($"*{typeof(AlphaRoutes).FullName}*"); } [Fact] public void AddRouteBuilder_ADiscoveredType_Throws() { var services = new ServiceCollection(); var act = () => services.AddRedbRoute(route => route .AddRouteBuilders([ThisAssembly], InNamespace(Plain)) .AddRouteBuilder()); act.Should().Throw().WithMessage($"*{typeof(AlphaRoutes).FullName}*"); } } } namespace redb.Route.Tests.Core.DiscoveryFixtures { public sealed class AlphaRoutes : RouteBuilder { protected override void Configure() => From("direct://discovery-alpha").To("mock://discovery-alpha"); } public sealed class BetaRoutes : RouteBuilder { protected override void Configure() => From("direct://discovery-beta").To("mock://discovery-beta"); } public static class Holder { public sealed class NestedRoutes : RouteBuilder { protected override void Configure() => From("direct://discovery-nested").To("mock://discovery-nested"); } } public abstract class AbstractRoutes : RouteBuilder; public sealed class OpenGenericRoutes : RouteBuilder { protected override void Configure() => From($"direct://discovery-{typeof(T).Name}").To("mock://discovery-generic"); } internal sealed class InternalRoutes : RouteBuilder { protected override void Configure() => From("direct://discovery-internal").To("mock://discovery-internal"); } public sealed record DiscoveryGreeting(string Text); } namespace redb.Route.Tests.Core.DiscoveryFixtures.NoDefaultConstructor { public sealed class NeedsAnArgumentRoutes(string name) : RouteBuilder { protected override void Configure() => From($"direct://discovery-arg-{name}").To("mock://discovery-arg"); } } namespace redb.Route.Tests.Core.DiscoveryFixtures.Throwing { public sealed class ThrowingRoutes : RouteBuilder { public ThrowingRoutes() => throw new NotSupportedException("not here"); protected override void Configure() { } } } namespace redb.Route.Tests.Core.DiscoveryFixtures.Injected { public sealed class InjectedRoutes(DiscoveryGreeting greeting) : RouteBuilder { public DiscoveryGreeting Greeting { get; } = greeting; protected override void Configure() => From("direct://discovery-injected").To("mock://discovery-injected"); } } Path: redb-route/tests/redb.Route.Tests/Core/RouteBuilderHelpersTests.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/RouteBuilderHelpersTests.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Expressions; using AwesomeAssertions; namespace redb.Route.Tests.Core; public class RouteBuilderHelpersTests { /// Exposes protected helpers for testing. private sealed class TestableBuilder : RouteBuilder { protected override void Configure() { } // Expose helpers public static BodyExpression CallBody() => Body(); public static HeaderExpression CallHeader(string name) => Header(name); public static PropertyExpression CallProperty(string name) => Property(name); public static ConstantExpression CallConstant(object value) => Constant(value); public static ExchangeExpression CallExchange(Func func) => Exchange(func); public static JsonPathExpression CallJPath(string path) => JPath(path); public static redb.Route.Expressions.XPathExpression CallXPath(string path) => XPath(path); } // ── Body() ── [Fact] public void Body_ReturnsBodyExpression() { var expr = TestableBuilder.CallBody(); expr.Should().BeOfType(); } [Fact] public void Body_EvaluatesExchangeBody() { var expr = TestableBuilder.CallBody(); var exchange = new Exchange(new Message("test-body")); expr.Evaluate(exchange).Should().Be("test-body"); } // ── Header(name) ── [Fact] public void Header_ReturnsHeaderExpression() { var expr = TestableBuilder.CallHeader("X-Custom"); expr.Should().BeOfType(); } [Fact] public void Header_EvaluatesHeaderValue() { var expr = TestableBuilder.CallHeader("status"); var exchange = new Exchange(new Message("body")); exchange.In.Headers["status"] = "active"; expr.Evaluate(exchange).Should().Be("active"); } // ── Property(name) ── [Fact] public void Property_ReturnsPropertyExpression() { var expr = TestableBuilder.CallProperty("retry"); expr.Should().BeOfType(); } [Fact] public void Property_EvaluatesPropertyValue() { var expr = TestableBuilder.CallProperty("count"); var exchange = new Exchange(new Message("body")); exchange.Properties["count"] = 42; expr.Evaluate(exchange).Should().Be(42); } // ── Constant(value) ── [Fact] public void Constant_ReturnsConstantExpression() { var expr = TestableBuilder.CallConstant(99); expr.Should().BeOfType(); } [Fact] public void Constant_AlwaysReturnsSameValue() { var expr = TestableBuilder.CallConstant("fixed"); var exchange = new Exchange(new Message("anything")); expr.Evaluate(exchange).Should().Be("fixed"); } // ── Exchange(func) ── [Fact] public void Exchange_ReturnsExchangeExpression() { var expr = TestableBuilder.CallExchange(e => e.In.Body); expr.Should().BeOfType(); } [Fact] public void Exchange_EvaluatesDelegateAgainstExchange() { var expr = TestableBuilder.CallExchange(e => $"{e.In.Headers["a"]}-{e.In.Headers["b"]}"); var exchange = new Exchange(new Message("body")); exchange.In.Headers["a"] = "hello"; exchange.In.Headers["b"] = "world"; expr.Evaluate(exchange).Should().Be("hello-world"); } // ── Predicate chaining from helpers ── [Fact] public void Body_IsEqualTo_CreatesPredicate() { var predicate = TestableBuilder.CallBody().isEqualTo("expected"); predicate.Should().NotBeNull(); var exchange = new Exchange(new Message("expected")); predicate.Matches(exchange).Should().BeTrue(); } [Fact] public void Header_IsGreaterThan_CreatesPredicate() { var predicate = TestableBuilder.CallHeader("age").isGreaterThan(18); predicate.Should().NotBeNull(); var exchange = new Exchange(new Message("body")); exchange.In.Headers["age"] = 25; predicate.Matches(exchange).Should().BeTrue(); } [Fact] public void Property_IsNotNull_CreatesPredicate() { var predicate = TestableBuilder.CallProperty("data").isNotNull(); predicate.Should().NotBeNull(); var exchange = new Exchange(new Message("body")); exchange.Properties["data"] = "something"; predicate.Matches(exchange).Should().BeTrue(); } // ── Fluent DSL integration: helpers inside route definition ── [Fact] public async Task Helpers_WorkInRouteDefinition() { object? captured = null; var context = new RouteContext(); context.AddRoutes(r => { r.From("direct://helpers-test") .SetBody(TestableBuilder.CallConstant("hello")) .SetHeader("src", TestableBuilder.CallBody()) .Filter(TestableBuilder.CallHeader("src").isEqualTo("hello")) .Process(e => captured = e.In.Body); }); await context.Start(); try { var producer = context.GetEndpoint("direct://helpers-test").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("ignored"))); captured.Should().Be("hello"); } finally { await context.Stop(); } } } Path: redb-route/tests/redb.Route.Tests/Core/RouteConfigurationTests.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/RouteConfigurationTests.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Tests.Core; /// /// Route configurations (Apache Camel's Route Configuration): OnException declared once, apart from the routes, /// for the routes of any builder of the context. The default configuration (no id) is for the routes that have no /// configurations assigned; a configuration with an id is for the routes that name it. A configuration's handler has /// everything a builder's has — redeliveries, OnWhen, the handler's steps. /// public class RouteConfigurationTests { private static readonly TimeSpan Wait = TimeSpan.FromSeconds(5); // ── The default configuration ── [Fact] public async Task TheDefaultConfiguration_HandlesTheFailuresOfEveryBuildersRoutes() { // The layout this is for: handlers in a class of their own, routes in others. var handled = new List(); await using var ctx = new RouteContext(); ctx.AddRoutes(new Handlers(handled)); ctx.AddRoutes(a => a.From("direct://cfg-a").RouteId("cfg-a").Process(_ => throw new InvalidOperationException("a"))); ctx.AddRoutes(b => b.From("direct://cfg-b").RouteId("cfg-b").Process(_ => throw new InvalidOperationException("b"))); await ctx.Start(); var a = await Send(ctx, "direct://cfg-a"); var b = await Send(ctx, "direct://cfg-b"); handled.Should().Equal("cfg-a", "cfg-b"); a.Exception.Should().BeNull("the configuration's handler handled the failure"); b.Exception.Should().BeNull(); } [Fact] public async Task AConfigurationHandler_Redelivers() { var attempts = 0; await using var ctx = new RouteContext(); ctx.AddRouteConfiguration(c => c.OnException() .MaximumRedeliveries(2).RedeliveryDelay(TimeSpan.FromMilliseconds(1)).Handled()); ctx.AddRoutes(r => r.From("direct://cfg-retry").Process(_ => { if (Interlocked.Increment(ref attempts) < 3) throw new InvalidOperationException("not yet"); })); await ctx.Start(); var exchange = await Send(ctx, "direct://cfg-retry"); attempts.Should().Be(3, "the first attempt and two redeliveries"); exchange.Exception.Should().BeNull(); } [Fact] public async Task AConfigurationHandler_HonoursOnWhen() { var hits = 0; await using var ctx = new RouteContext(); ctx.AddRouteConfiguration(c => c.OnException() .OnWhen(e => e.RouteId == "cfg-when-yes").Handled().Process(_ => Interlocked.Increment(ref hits))); ctx.AddRoutes(r => { r.From("direct://cfg-when-yes").RouteId("cfg-when-yes").Process(_ => throw new InvalidOperationException("x")); r.From("direct://cfg-when-no").RouteId("cfg-when-no").Process(_ => throw new InvalidOperationException("x")); }); await ctx.Start(); var yes = await Send(ctx, "direct://cfg-when-yes"); var no = await Send(ctx, "direct://cfg-when-no"); hits.Should().Be(1); yes.Exception.Should().BeNull(); no.Exception.Should().BeOfType("the guard did not pass for this route"); } [Fact] public async Task AFailureInADetachedBody_ReachesTheConfiguration() { var handled = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); await using var ctx = new RouteContext(); ctx.AddRouteConfiguration(c => c.OnException() .Handled().Process(_ => handled.TrySetResult())); ctx.AddRoutes(r => r.From("direct://cfg-threads").Threads(1) .Process(_ => throw new InvalidOperationException("after the caller returned"))); await ctx.Start(); await Send(ctx, "direct://cfg-threads"); await handled.Task.WaitAsync(Wait); } [Fact] public async Task ARestart_KeepsTheConfiguration() { var hits = 0; await using var ctx = new RouteContext(); ctx.AddRouteConfiguration(c => c.OnException() .Handled().Process(_ => Interlocked.Increment(ref hits))); ctx.AddRoutes(r => r.From("direct://cfg-restart").Process(_ => throw new InvalidOperationException("x"))); await ctx.Start(); await ctx.Stop(); await ctx.Start(); await Send(ctx, "direct://cfg-restart"); hits.Should().Be(1); } // ── Configurations with an id ── [Fact] public async Task AConfigurationWithAnId_IsForTheRoutesThatNameIt() { var hits = new List(); await using var ctx = new RouteContext(); ctx.AddRouteConfiguration("audit", c => c.OnException() .Handled().Process(e => { lock (hits) hits.Add(e.RouteId); })); ctx.AddRoutes(r => { r.From("direct://cfg-named").RouteId("cfg-named").RouteConfigurationId("audit") .Process(_ => throw new InvalidOperationException("x")); r.From("direct://cfg-unnamed").RouteId("cfg-unnamed") .Process(_ => throw new InvalidOperationException("x")); }); await ctx.Start(); var named = await Send(ctx, "direct://cfg-named"); var unnamed = await Send(ctx, "direct://cfg-unnamed"); hits.Should().Equal("cfg-named"); named.Exception.Should().BeNull(); unnamed.Exception.Should().BeOfType("the route did not ask for the configuration"); } [Fact] public async Task ARouteWithAssignedConfigurations_DoesNotGetTheDefaultOne() { // Camel: the nameless configuration is the default for routes which have NOT been assigned configurations. var byDefault = 0; var byAudit = 0; await using var ctx = new RouteContext(); ctx.AddRouteConfiguration(c => c.OnException().Handled().Process(_ => Interlocked.Increment(ref byDefault))); ctx.AddRouteConfiguration("audit", c => c.OnException().Handled().Process(_ => Interlocked.Increment(ref byAudit))); ctx.AddRoutes(r => r.From("direct://cfg-assigned").RouteConfigurationId("audit") .Process(_ => throw new InvalidOperationException("not an IOException"))); await ctx.Start(); var exchange = await Send(ctx, "direct://cfg-assigned"); byDefault.Should().Be(0); byAudit.Should().Be(0); exchange.Exception.Should().BeOfType(); } [Theory] [InlineData("audit,retry", 2)] [InlineData("au*", 1)] [InlineData("(audit|retry)", 2)] [InlineData("*", 2)] public async Task Ids_SeveralAWildcardOrARegularExpression(string ids, int expectedHandlers) { var hits = new List(); await using var ctx = new RouteContext(); ctx.AddRouteConfiguration("audit", c => c.OnException() .Handled().Process(_ => { lock (hits) hits.Add("audit"); })); ctx.AddRouteConfiguration("retry", c => c.OnException() .Handled().Process(_ => { lock (hits) hits.Add("retry"); })); ctx.AddRoutes(r => r.From("direct://cfg-ids").RouteConfigurationId(ids) .Process(e => throw (e.In.Body is "io" ? new IOException("io") : new InvalidOperationException("op")))); await ctx.Start(); await Send(ctx, "direct://cfg-ids", "io"); await Send(ctx, "direct://cfg-ids", "op"); hits.Should().HaveCount(expectedHandlers); hits.Should().Contain("audit"); } [Fact] public async Task AnExactIdNoConfigurationHas_FailsStart_NamingTheRoute() { await using var ctx = new RouteContext(); ctx.AddRouteConfiguration("audit", c => c.OnException().Handled()); ctx.AddRoutes(r => r.From("direct://cfg-missing").RouteId("cfg-missing").RouteConfigurationId("audti")); var start = () => ctx.Start(); (await start.Should().ThrowAsync()) .WithMessage("*cfg-missing*").WithMessage("*'audti'*"); } [Fact] public async Task ADuplicateId_FailsStart() { await using var ctx = new RouteContext(); ctx.AddRouteConfiguration("audit", c => c.OnException().Handled()); ctx.AddRouteConfiguration("audit", c => c.OnException().Handled()); ctx.AddRoutes(r => r.From("direct://cfg-duplicate")); var start = () => ctx.Start(); (await start.Should().ThrowAsync()).WithMessage("*Duplicate route configuration id 'audit'*"); } // ── A handlers-only builder that is not a configuration ── [Fact] public async Task ABuilderWithHandlersAndNoRoutes_IsAWarningAtStart() { // What a class of shared handlers becomes when it stays a plain RouteBuilder: it applies to nothing, silently. var log = new Cluster.CapturingLoggerProvider(); using var loggerFactory = LoggerFactory.Create(b => b.AddProvider(log)); await using var ctx = new RouteContext(loggerFactory: loggerFactory); ctx.AddRoutes(new PlainHandlers()); ctx.AddRoutes(new Handlers([])); ctx.AddRoutes(r => { r.OnException().Handled(); r.From("direct://cfg-warning").Process(_ => { }); }); await ctx.Start(); var warnings = log.Entries .Where(e => e.Level == LogLevel.Warning && e.Message.Contains("declares no routes")) .Select(e => e.Message).ToList(); warnings.Should().ContainSingle("only the plain builder: a configuration is meant to have no routes") .Which.Should().Contain(nameof(PlainHandlers)).And.Contain("RouteConfiguration"); } private sealed class PlainHandlers : RouteBuilder { protected override void Configure() => OnException().Handled(); } // ── With the builder's and the route's own handlers ── [Fact] public async Task AConfigurationsHandler_IsUsedInsteadOfTheBuildersHandlerOfTheSameType() { // Camel: "The onException from route configurations are added after the ones in the RouteBuilder, and are // therefore used instead." var taken = new List(); await using var ctx = new RouteContext(); ctx.AddRouteConfiguration(c => c.OnException() .Handled().Process(_ => { lock (taken) taken.Add("configuration"); })); ctx.AddRoutes(r => { r.OnException().Handled().Process(_ => { lock (taken) taken.Add("builder"); }); r.OnException().Handled().Process(_ => { lock (taken) taken.Add("builder-io"); }); r.From("direct://cfg-over-builder") .Process(e => throw (e.In.Body is "io" ? new IOException("io") : new InvalidOperationException("op"))); }); await ctx.Start(); await Send(ctx, "direct://cfg-over-builder", "op"); await Send(ctx, "direct://cfg-over-builder", "io"); taken.Should().Equal("configuration", "builder-io"); } [Fact] public async Task TheRoutesOwnHandler_WinsATieWithTheConfiguration() { var taken = new List(); await using var ctx = new RouteContext(); ctx.AddRouteConfiguration(c => c.OnException() .Handled().Process(_ => { lock (taken) taken.Add("configuration"); })); ctx.AddRoutes(r => r.From("direct://cfg-route-tie") .OnException().Handled().Process(_ => { lock (taken) taken.Add("route"); }).End() .Process(_ => throw new InvalidOperationException("x"))); await ctx.Start(); await Send(ctx, "direct://cfg-route-tie"); taken.Should().Equal("route"); } [Fact] public async Task ANearerHandlerOfTheConfiguration_WinsOverTheRoutesWiderOne() { var taken = new List(); await using var ctx = new RouteContext(); ctx.AddRouteConfiguration(c => c.OnException() .Handled().Process(_ => { lock (taken) taken.Add("configuration"); })); ctx.AddRoutes(r => r.From("direct://cfg-nearer") .OnException().Handled().Process(_ => { lock (taken) taken.Add("route"); }).End() .Process(e => throw (e.In.Body is "file" ? new FileNotFoundException("f") : new InvalidOperationException("op")))); await ctx.Start(); await Send(ctx, "direct://cfg-nearer", "file"); await Send(ctx, "direct://cfg-nearer", "op"); taken.Should().Equal("configuration", "route"); } private sealed class Handlers(List handled) : RouteConfigurationBuilder { protected override void Configuration() => RouteConfiguration().OnException() .Handled().Process(e => { lock (handled) handled.Add(e.RouteId); }); } private static async Task Send(IRouteContext ctx, string uri, object? body = null) { var producer = ctx.GetEndpoint(uri).CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message { Body = body ?? "x" }); try { await producer.Process(exchange); } catch (Exception ex) { exchange.Exception ??= ex; } return exchange; } } Path: redb-route/tests/redb.Route.Tests/Core/RouteContextEnrichedTests.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/RouteContextEnrichedTests.cs ---- using AwesomeAssertions; using NSubstitute; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Tests.Core; /// /// Tests for the enriched : /// properties, registry, service locator, component management, /// three-tier exception handling, degraded-mode start, and dispose. /// public class RouteContextEnrichedTests : IDisposable { private readonly RouteContext _ctx = new("test-ctx-001"); public void Dispose() => _ctx.Dispose(); // ── Identity ── [Fact] public void ContextId_ReturnsProvidedId() { _ctx.ContextId.Should().Be("test-ctx-001"); } [Fact] public void ContextId_GeneratesGuid_WhenNull() { using var ctx = new RouteContext(); ctx.ContextId.Should().NotBeNullOrEmpty(); ctx.ContextId.Should().HaveLength(32); // GUID "N" format } [Fact] public void IsStarted_IsFalseByDefault() { _ctx.IsStarted.Should().BeFalse(); } // ── Properties ── [Fact] public void Indexer_GetSet_Works() { _ctx["key1"] = "value1"; _ctx["key1"].Should().Be("value1"); } [Fact] public void Indexer_MissingKey_ReturnsNull() { _ctx["nonexistent"].Should().BeNull(); } [Fact] public void GetProperty_TypedConversion() { _ctx["count"] = 42; _ctx.GetProperty("count").Should().Be(42); } [Fact] public void GetProperty_MissingKey_ReturnsDefault() { _ctx.GetProperty("missing").Should().Be(0); } [Fact] public void SetProperty_ReturnsSelf_ForChaining() { var result = _ctx.SetProperty("x", 10); result.Should().BeSameAs(_ctx); _ctx.GetProperty("x").Should().Be(10); } // ── Registry ── [Fact] public void AddToRegistry_GetFromRegistry_Works() { var factory = new object(); _ctx.AddToRegistry("myFactory", factory); _ctx.GetFromRegistry("myFactory").Should().BeSameAs(factory); } [Fact] public void GetFromRegistry_MissingKey_ReturnsDefault() { _ctx.GetFromRegistry("missing").Should().BeNull(); } [Fact] public void AddToRegistry_ReturnsSelf_ForChaining() { _ctx.AddToRegistry("a", "b").Should().BeSameAs(_ctx); } [Fact] public void AddToRegistry_ThrowsOnNullKey() { var act = () => _ctx.AddToRegistry("", "val"); act.Should().Throw(); } // ── Service Locator ── [Fact] public void AddService_GetService_Works() { var svc = Substitute.For(); _ctx.AddService(typeof(IDisposable), svc); _ctx.GetService().Should().BeSameAs(svc); } [Fact] public void GetService_NotRegistered_ReturnsDefault() { _ctx.GetService().Should().BeNull(); } // ── Component Management ── [Fact] public void HasComponent_ReturnsFalse_WhenNotRegistered() { _ctx.HasComponent("kafka").Should().BeFalse(); } [Fact] public void HasComponent_ReturnsTrue_AfterRegistration() { var component = CreateMockComponent("test"); _ctx.AddComponent(component); _ctx.HasComponent("test").Should().BeTrue(); } [Fact] public void GetComponentNames_ReturnsRegisteredSchemes() { _ctx.AddComponent(CreateMockComponent("alpha")); _ctx.AddComponent(CreateMockComponent("beta")); _ctx.GetComponentNames().Should().Contain("alpha").And.Contain("beta"); } [Fact] public void GetComponent_ByScheme_ReturnsCorrectComponent() { var comp = CreateMockComponent("direct"); _ctx.AddComponent(comp); _ctx.GetComponent("direct").Should().BeSameAs(comp); } [Fact] public void GetComponent_ByType_ReturnsFirstMatch() { var comp = CreateMockComponent("custom-typed"); _ctx.AddComponent(comp); _ctx.GetComponent("custom-typed").Should().BeSameAs(comp); } [Fact] public void GetComponent_NotFound_ReturnsNull() { _ctx.GetComponent("missing").Should().BeNull(); } // ── Exception Handling ── [Fact] public async Task HandleException_GlobalHandler_IsCalled() { var processor = Substitute.For(); _ctx.AddGlobalExceptionHandler(processor); var exchange = new Exchange(); await _ctx.HandleException(exchange, new InvalidOperationException("test")); await processor.Received(1).Process(Arg.Is(ex => ex.Exception is InvalidOperationException)); } [Fact] public async Task HandleException_LocalHandler_HasPriorityOverGlobal() { var globalProcessor = Substitute.For(); var localProcessor = Substitute.For(); _ctx.AddGlobalExceptionHandler(globalProcessor); _ctx.AddLocalExceptionHandler("route1", typeof(InvalidOperationException), localProcessor); var exchange = new Exchange { RouteId = "route1" }; await _ctx.HandleException(exchange, new InvalidOperationException("test")); await localProcessor.Received(1).Process(Arg.Any()); await globalProcessor.DidNotReceive().Process(Arg.Any()); } [Fact] public async Task HandleException_WalksTypeHierarchy() { var processor = Substitute.For(); _ctx.AddGlobalExceptionHandler(processor); var exchange = new Exchange(); await _ctx.HandleException(exchange, new ArgumentNullException("param")); await processor.Received(1).Process(Arg.Any()); } [Fact] public async Task HandleException_NoHandler_Throws() { var exchange = new Exchange(); var act = () => _ctx.HandleException(exchange, new InvalidOperationException("unhandled")); await act.Should().ThrowAsync().WithMessage("No exception handler*"); } [Fact] public async Task HandleException_SetsExceptionCaughtProperty() { var processor = Substitute.For(); _ctx.AddGlobalExceptionHandler(processor); var exchange = new Exchange(); var ex = new InvalidOperationException("caught"); await _ctx.HandleException(exchange, ex); exchange.Properties["ExceptionCaught"].Should().BeSameAs(ex); } [Fact] public void AddGlobalExceptionHandler_DuplicateType_Throws() { var proc = Substitute.For(); _ctx.AddGlobalExceptionHandler(proc); var act = () => _ctx.AddGlobalExceptionHandler(proc); act.Should().Throw().WithMessage("*already registered*"); } // ── Lifecycle ── [Fact] public async Task Start_SetsIsStarted() { await _ctx.Start(); _ctx.IsStarted.Should().BeTrue(); } [Fact] public async Task Stop_ClearsIsStarted() { await _ctx.Start(); await _ctx.Stop(); _ctx.IsStarted.Should().BeFalse(); } [Fact] public void Dispose_ClearsAllStorage() { _ctx["key"] = "val"; _ctx.AddToRegistry("r", "v"); _ctx.AddService(typeof(IDisposable), Substitute.For()); _ctx.AddComponent(CreateMockComponent("test")); _ctx.Dispose(); _ctx["key"].Should().BeNull(); _ctx.GetFromRegistry("r").Should().BeNull(); _ctx.GetService().Should().BeNull(); _ctx.HasComponent("test").Should().BeFalse(); } [Fact] public async Task DisposeAsync_ClearsAllStorage() { _ctx["key"] = "val"; _ctx.AddToRegistry("r", "v"); _ctx.AddService(typeof(IDisposable), Substitute.For()); _ctx.AddComponent(CreateMockComponent("test")); await ((IAsyncDisposable)_ctx).DisposeAsync(); _ctx["key"].Should().BeNull(); _ctx.GetFromRegistry("r").Should().BeNull(); _ctx.GetService().Should().BeNull(); _ctx.HasComponent("test").Should().BeFalse(); } [Fact] public async Task DisposeAsync_StopsContextIfStarted() { await _ctx.Start(); _ctx.IsStarted.Should().BeTrue(); await ((IAsyncDisposable)_ctx).DisposeAsync(); _ctx.IsStarted.Should().BeFalse(); } [Fact] public void RouteContext_ImplementsIAsyncDisposable() { _ctx.Should().BeAssignableTo(); } // ── Helpers ── private static IComponent CreateMockComponent(string scheme) { var comp = Substitute.For(); comp.Scheme.Returns(scheme); return comp; } // ── DI: ServiceProvider ── [Fact] public void GetServiceProvider_ReturnsNull_WhenNotSet() { _ctx.GetServiceProvider().Should().BeNull(); } [Fact] public void SetServiceProvider_StoresAndReturnsProvider() { var sp = Substitute.For(); var result = _ctx.SetServiceProvider(sp); result.Should().BeSameAs(_ctx); _ctx.GetServiceProvider().Should().BeSameAs(sp); } [Fact] public void SetServiceProvider_ThrowsOnNull() { var act = () => _ctx.SetServiceProvider(null!); act.Should().Throw(); } // ── ErrorHandler ── [Fact] public void ErrorHandler_IsNull_ByDefault() { _ctx.ErrorHandler.Should().BeNull(); } [Fact] public async Task HandleException_UsesErrorHandler_WhenNoRouteHandlerMatches() { var handler = Substitute.For(); _ctx.ErrorHandler = handler; var exchange = Substitute.For(); exchange.Properties.Returns(new Dictionary()); var exception = new InvalidOperationException("boom"); await _ctx.HandleException(exchange, exception); await handler.Received(1).HandleError(exchange, exception, Arg.Any()); } [Fact] public async Task HandleException_PrefersLocalHandler_OverErrorHandler() { // Set up local handler var localProcessor = Substitute.For(); _ctx.AddLocalExceptionHandler("route1", typeof(InvalidOperationException), localProcessor); // Set up error handler var errorHandler = Substitute.For(); _ctx.ErrorHandler = errorHandler; var exchange = Substitute.For(); exchange.RouteId.Returns("route1"); exchange.Properties.Returns(new Dictionary()); var exception = new InvalidOperationException("handled locally"); await _ctx.HandleException(exchange, exception); await localProcessor.Received(1).Process(exchange, Arg.Any()); await errorHandler.DidNotReceiveWithAnyArgs().HandleError(default!, default!, default); } [Fact] public async Task HandleException_PrefersGlobalHandler_OverErrorHandler() { var globalProcessor = Substitute.For(); _ctx.AddGlobalExceptionHandler(globalProcessor); var errorHandler = Substitute.For(); _ctx.ErrorHandler = errorHandler; var exchange = Substitute.For(); exchange.Properties.Returns(new Dictionary()); var exception = new InvalidOperationException("handled globally"); await _ctx.HandleException(exchange, exception); await globalProcessor.Received(1).Process(exchange, Arg.Any()); await errorHandler.DidNotReceiveWithAnyArgs().HandleError(default!, default!, default); } [Fact] public async Task HandleException_Throws_WhenNoHandlerAndNoErrorHandler() { var exchange = Substitute.For(); exchange.Properties.Returns(new Dictionary()); var exception = new InvalidOperationException("unhandled"); var act = () => _ctx.HandleException(exchange, exception); await act.Should().ThrowAsync() .WithMessage("No exception handler found*"); } // ── HasExceptionRoute ── [Fact] public void HasExceptionRoute_ReturnsFalse_WhenNoHandlers() { _ctx.HasExceptionRoute().Should().BeFalse(); } [Fact] public void HasExceptionRoute_ReturnsTrue_ForGlobalHandler() { var processor = Substitute.For(); _ctx.AddGlobalExceptionHandler(processor); _ctx.HasExceptionRoute().Should().BeTrue(); } [Fact] public void HasExceptionRoute_ReturnsTrue_ForLocalHandler() { var processor = Substitute.For(); _ctx.AddLocalExceptionHandler("route1", typeof(TimeoutException), processor); _ctx.HasExceptionRoute().Should().BeTrue(); } [Fact] public void HasExceptionRoute_ReturnsTrue_ForDerivedType_ViaBaseHandler() { var processor = Substitute.For(); _ctx.AddGlobalExceptionHandler(processor); // ArgumentException derives from Exception _ctx.HasExceptionRoute().Should().BeTrue(); } // ── RemoveComponent ── [Fact] public void RemoveComponent_ReturnsTrue_WhenRemoved() { var comp = CreateMockComponent("test-scheme"); _ctx.AddComponent(comp); _ctx.RemoveComponent("test-scheme").Should().BeTrue(); _ctx.HasComponent("test-scheme").Should().BeFalse(); } [Fact] public void RemoveComponent_ReturnsFalse_WhenNotPresent() { _ctx.RemoveComponent("nonexistent").Should().BeFalse(); } [Fact] public void RemoveComponent_ThrowsOnEmpty() { var act = () => _ctx.RemoveComponent(""); act.Should().Throw(); } } Path: redb-route/tests/redb.Route.Tests/Core/RouteContextLoggerFactoryTests.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/RouteContextLoggerFactoryTests.cs ---- using AwesomeAssertions; using Microsoft.Extensions.Logging; using redb.Route.Components; using redb.Route.Core; using Xunit; namespace redb.Route.Tests.Core; /// /// A logger factory registered after the context is constructed must actually reach components — otherwise /// consumer failures pass with no log line. Covers back-fill onto already-registered components and /// forward-fill onto components added later. /// public class RouteContextLoggerFactoryTests { [Fact] public void AddService_LoggerFactoryAfterConstruction_BackfillsExistingComponentLoggers() { var ctx = new RouteContext(); // constructed with no logger factory ctx.GetComponent("direct")!.Logger.Should().BeNull("no factory at construction"); using var factory = LoggerFactory.Create(_ => { }); ctx.AddService(typeof(ILoggerFactory), factory); ctx.GetComponent("direct")!.Logger .Should().NotBeNull("a factory registered after construction must reach built-in components"); ctx.GetService().Should().NotBeNull("the context adopts the late-registered factory"); } [Fact] public void AddComponent_AfterLoggerFactoryRegistered_GetsLogger() { var ctx = new RouteContext(); using var factory = LoggerFactory.Create(_ => { }); ctx.AddService(typeof(ILoggerFactory), factory); var comp = new DirectComponent(); ctx.AddComponent(comp); comp.Logger.Should().NotBeNull("components added after the factory is registered get a logger"); } } Path: redb-route/tests/redb.Route.Tests/Core/RouteContextPropagationTests.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/RouteContextPropagationTests.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Definitions; namespace redb.Route.Tests.Core; /// /// Tests that IRouteContext is properly propagated from RouteBuilder → RouteDefinition → scopes → extensions. /// public class RouteContextPropagationTests : IAsyncLifetime { private readonly RouteContext _context = new(); public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { await _context.Stop(); } // ── Basic propagation ── [Fact] public void GetContext_ReturnsNull_BeforeEngineStart() { var rd = new RouteDefinition(); rd.GetContext().Should().BeNull(); } // ── Propagation through RouteBuilder → RouteDefinition ── [Fact] public async Task Context_IsAvailable_InRouteDefinition_AfterStart() { IRouteContext? captured = null; _context.AddRoutes(r => { var rd = r.From("direct://ctx-test-in"); captured = rd.GetContext(); rd.To("direct://ctx-test-out"); }); await _context.Start(); captured.Should().NotBeNull(); captured.Should().BeSameAs(_context); } // ── Propagation into extension methods ── [Fact] public async Task Context_IsAvailable_InExtensionMethod() { IRouteContext? captured = null; _context.AddRoutes(r => { r.From("direct://ext-test-in") .CaptureContext(ctx => captured = ctx) .To("direct://ext-test-out"); }); await _context.Start(); captured.Should().NotBeNull(); captured.Should().BeSameAs(_context); } // ── Propagation into scopes ── [Fact] public async Task Context_IsAvailable_InChoiceScope() { IRouteContext? captured = null; _context.AddRoutes(r => { r.From("direct://choice-ctx-in") .Choice() .When(e => true) .CaptureContext(ctx => captured = ctx) .End() .To("direct://choice-ctx-out"); }); await _context.Start(); captured.Should().NotBeNull(); captured.Should().BeSameAs(_context); } [Fact] public async Task Context_IsAvailable_InLoopScope() { IRouteContext? captured = null; _context.AddRoutes(r => { r.From("direct://loop-ctx-in") .Loop(1) .CaptureContext(ctx => captured = ctx) .End() .To("direct://loop-ctx-out"); }); await _context.Start(); captured.Should().NotBeNull(); captured.Should().BeSameAs(_context); } [Fact] public async Task Context_IsAvailable_InTracedScope() { IRouteContext? captured = null; _context.AddRoutes(r => { r.From("direct://traced-ctx-in") .Traced("test-span") .CaptureContext(ctx => captured = ctx) .EndTraced() .To("direct://traced-ctx-out"); }); await _context.Start(); captured.Should().NotBeNull(); captured.Should().BeSameAs(_context); } [Fact] public async Task Context_IsAvailable_InLogScope() { IRouteContext? captured = null; _context.AddRoutes(r => { r.From("direct://log-ctx-in") .Log(Microsoft.Extensions.Logging.LogLevel.Information) .CaptureContext(ctx => captured = ctx) .End() .To("direct://log-ctx-out"); }); await _context.Start(); captured.Should().NotBeNull(); captured.Should().BeSameAs(_context); } [Fact] public async Task Context_IsAvailable_InDoTryScope() { IRouteContext? captured = null; _context.AddRoutes(r => { r.From("direct://try-ctx-in") .DoTry() .CaptureContext(ctx => captured = ctx) .DoCatch() .Process(e => { }) .End() .To("direct://try-ctx-out"); }); await _context.Start(); captured.Should().NotBeNull(); captured.Should().BeSameAs(_context); } // ── Extension method can use context for DI ── [Fact] public async Task ExtensionMethod_CanAccessServices_ViaContext() { var processed = false; _context.AddToRegistry("testFlag", true); _context.AddRoutes(r => { r.From("direct://svc-test-in") .UseRegistryFlag("testFlag", flag => processed = (bool)flag!) .To("direct://svc-test-out"); }); IExchange? received = null; _context.AddRoutes(r => { r.From("direct://svc-test-out") .Process(e => received = e); }); await _context.Start(); var producer = _context.GetEndpoint("direct://svc-test-in").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("test"))); processed.Should().BeTrue(); received.Should().NotBeNull(); } // ── RouteBuilder subclass gets Context ── [Fact] public async Task RouteBuilder_Subclass_HasContext() { IRouteContext? builderContext = null; var builder = new ContextCapturingBuilder(ctx => builderContext = ctx); _context.AddRoutes(builder); await _context.Start(); builderContext.Should().NotBeNull(); builderContext.Should().BeSameAs(_context); } private sealed class ContextCapturingBuilder : RouteBuilder { private readonly Action _capture; public ContextCapturingBuilder(Action capture) => _capture = capture; protected override void Configure() { _capture(Context); From("direct://builder-ctx-test") .Process(e => { }); } } } // ── Extension method helpers for testing ── internal static class RouteContextTestExtensions { /// Captures GetContext() at DSL build time. public static IRouteDefinition CaptureContext(this IRouteDefinition rd, Action capture) { capture(rd.GetContext()); return rd.Process(e => { }); // no-op } /// RichLogScope overload: captures context while keeping the scope open for chaining. public static redb.Route.Definitions.RichLogScopeDefinition CaptureContext( this redb.Route.Definitions.RichLogScopeDefinition scope, Action capture) { IProcessorDefinition? cur = scope.Parent; while (cur is not null and not IRouteDefinition) cur = cur.Parent; capture((cur as IRouteDefinition)?.GetContext()); return scope; } /// Extension that reads from registry at build-time, uses value at run-time. public static IRouteDefinition UseRegistryFlag(this IRouteDefinition rd, string key, Action onFlag) { var ctx = rd.GetContext()!; var flag = ctx.GetFromRegistry(key); return rd.Process(e => onFlag(flag)); } } Path: redb-route/tests/redb.Route.Tests/Core/RouteDecimalTests.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/RouteDecimalTests.cs ---- using System.Text.Json.Nodes; using redb.Route.Core; using redb.Route.Expressions; namespace redb.Route.Tests.Core; /// /// A double or a float that becomes a decimal is the number that was written, on every runtime: the explicit /// conversion rounded to 15 digits up to .NET 10 (12345678901234.56 became 12345678901234.6) and gives the exact /// binary value from .NET 11 on (19.95 became 19.949999999999999289457264240). /// public class RouteDecimalTests { [Theory] [InlineData(19.95, "19.95")] [InlineData(2.57, "2.57")] [InlineData(0.1, "0.1")] [InlineData(12345678901234.56, "12345678901234.56")] [InlineData(-1e-5, "-0.00001")] [InlineData(123456789.0, "123456789")] public void ADouble_BecomesTheDecimalItWasWrittenAs(double value, string expected) { RouteDecimal.FromDouble(value).Should().Be(decimal.Parse(expected, System.Globalization.CultureInfo.InvariantCulture)); RouteDecimal.From(value).Should().Be(decimal.Parse(expected, System.Globalization.CultureInfo.InvariantCulture)); RouteDecimal.ChangeType(value, typeof(decimal)).Should().Be(decimal.Parse(expected, System.Globalization.CultureInfo.InvariantCulture)); } [Fact] public void AFloat_BecomesItsOwnShortestText_NotThatOfItsWideningToDouble() { RouteDecimal.FromSingle(19.95f).Should().Be(19.95m); RouteDecimal.From(0.1f).Should().Be(0.1m); } [Theory] [InlineData(double.NaN)] [InlineData(double.PositiveInfinity)] [InlineData(1e30)] public void NoDecimalValue_Throws_AsTheExplicitConversionDoes(double value) { var act = () => RouteDecimal.FromDouble(value); act.Should().Throw(); } [Fact] public void EveryOtherPair_ConvertsAsConvertChangeTypeDoes() { RouteDecimal.ChangeType(42, typeof(decimal)).Should().Be(42m); RouteDecimal.ChangeType("19.95", typeof(decimal), System.Globalization.CultureInfo.InvariantCulture).Should().Be(19.95m); RouteDecimal.ChangeType(19.95m, typeof(double)).Should().Be(19.95); RouteDecimal.ChangeType(7L, typeof(int)).Should().Be(7); } [Theory] [InlineData("19.95", "19.95")] [InlineData("12345678901234.56", "12345678901234.56")] public void AJsonPathNumberReadAsDecimal_IsTheNumberInTheDocument(string number, string expected) { var exchange = new Exchange(new Message(JsonNode.Parse($$"""{ "price": {{number}} }"""))); new JsonPathExpression("$.price").Evaluate(exchange) .Should().Be(decimal.Parse(expected, System.Globalization.CultureInfo.InvariantCulture)); } [Fact] public void AnExpressionDoubleConvertedToDecimal_IsTheNumberItPrints() { new StringExpression("round(2.567, 2)").Evaluate(new Exchange()).Should().Be(2.57m); } } Path: redb-route/tests/redb.Route.Tests/Core/RouteErrorScopeTests.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/RouteErrorScopeTests.cs ---- using System.Collections.Concurrent; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Processors; namespace redb.Route.Tests.Core; /// /// One error scope per route, as in Apache Camel: the route's OnException, its builder's, then the context's /// error handling (AddLocalExceptionHandler → AddGlobalExceptionHandler → ErrorHandler) for a /// failure no OnException took. The same scope wraps the detached body of .Threads(), so a failure there /// gets the full handler configuration. A context handler that does not mark the exchange handled lets the failure go /// on to the caller, as Camel's DefaultErrorHandler does. /// public class RouteErrorScopeTests { private static readonly TimeSpan Wait = TimeSpan.FromSeconds(5); // ── The detached .Threads() body gets the full OnException configuration ── [Fact] public async Task Threads_OnWhenFalse_DoesNotTakeTheFailure() { var hits = 0; var errors = new RecordingErrorHandler(); await using var ctx = new RouteContext { ErrorHandler = errors }; ctx.AddRoutes(r => r .From("direct://scope-threads-onwhen") .OnException() .OnWhen(_ => false) .Handled() .Process(_ => Interlocked.Increment(ref hits)) .End() .Threads(2) .Process((IExchange _, CancellationToken _) => throw new InvalidOperationException("boom")) .End()); await ctx.Start(); await Send(ctx, "direct://scope-threads-onwhen"); await WaitFor(() => errors.Count == 1); Volatile.Read(ref hits).Should().Be(0, "OnWhen is false, so the handler does not take the failure"); } [Fact] public async Task Threads_Redeliveries_RerunTheThreadsBody() { var runs = 0; var handled = 0; await using var ctx = new RouteContext(); ctx.AddRoutes(r => r .From("direct://scope-threads-redelivery") .OnException() .MaximumRedeliveries(2) .RedeliveryDelay(TimeSpan.FromMilliseconds(1)) .Handled() .Process(_ => Interlocked.Increment(ref handled)) .End() .Threads(2) .Process((IExchange _, CancellationToken _) => { Interlocked.Increment(ref runs); throw new InvalidOperationException("boom"); }) .End()); await ctx.Start(); await Send(ctx, "direct://scope-threads-redelivery"); await WaitFor(() => Volatile.Read(ref handled) == 1); Volatile.Read(ref runs).Should().Be(3, "the first run and two redeliveries of the Threads body"); } [Fact] public async Task Threads_OnRedeliveryAndUseOriginalBody_Apply() { var redeliveries = 0; var bodies = new ConcurrentQueue(); await using var ctx = new RouteContext(); ctx.AddRoutes(r => r .From("direct://scope-threads-original") .OnException() .MaximumRedeliveries(1) .RedeliveryDelay(TimeSpan.FromMilliseconds(1)) .UseOriginalBody() .OnRedelivery(_ => Interlocked.Increment(ref redeliveries)) .Handled() .Process(e => bodies.Enqueue(e.In.Body)) .End() .Threads(2) .Process((IExchange e, CancellationToken _) => { e.In.Body = "changed"; throw new InvalidOperationException("boom"); }) .End()); await ctx.Start(); await Send(ctx, "direct://scope-threads-original", "original"); await WaitFor(() => !bodies.IsEmpty); Volatile.Read(ref redeliveries).Should().Be(1); bodies.Should().ContainSingle().Which.Should().Be("original"); } // ── The context layer on an ordinary route ── [Fact] public async Task ErrorHandler_TakesAFailureNoOnExceptionTook() { var errors = new RecordingErrorHandler(); await using var ctx = new RouteContext { ErrorHandler = errors }; ctx.AddRoutes(r => r .From("direct://scope-errorhandler") .Process(_ => throw new InvalidOperationException("boom"))); await ctx.Start(); var exchange = await Send(ctx, "direct://scope-errorhandler"); errors.Count.Should().Be(1); errors.Exceptions.Single().Should().BeOfType(); exchange.Exception.Should().BeOfType( "a handler that does not mark the exchange handled lets the failure go on, as Camel's DefaultErrorHandler"); } [Fact] public async Task ErrorHandler_ThatMarksTheExchangeHandled_EndsTheFailure() { var errors = new RecordingErrorHandler { MarkHandled = true }; await using var ctx = new RouteContext { ErrorHandler = errors }; ctx.AddRoutes(r => r .From("direct://scope-errorhandler-handled") .Process(_ => throw new InvalidOperationException("boom"))); await ctx.Start(); var exchange = await Send(ctx, "direct://scope-errorhandler-handled"); errors.Count.Should().Be(1); exchange.ExceptionHandled.Should().BeTrue("a dead letter channel takes the failure, as in Camel"); } [Fact] public async Task ErrorHandler_IsNotCalled_WhenAnOnExceptionTookTheFailure_EvenUnhandled() { var errors = new RecordingErrorHandler(); var hits = 0; await using var ctx = new RouteContext { ErrorHandler = errors }; ctx.AddRoutes(r => r .From("direct://scope-errorhandler-taken") .OnException() .Process(_ => Interlocked.Increment(ref hits)) .End() .Process(_ => throw new InvalidOperationException("boom"))); await ctx.Start(); await Send(ctx, "direct://scope-errorhandler-taken"); Volatile.Read(ref hits).Should().Be(1); errors.Count.Should().Be(0, "an OnException took it — Handled(false) included, as in Camel"); } [Fact] public async Task ErrorHandler_OnATimerRoute() { var errors = new RecordingErrorHandler(); await using var ctx = new RouteContext { ErrorHandler = errors }; ctx.AddRoutes(r => r .From("timer://scope-timer?period=50&repeatCount=1") .Process(_ => throw new InvalidOperationException("boom"))); await ctx.Start(); await WaitFor(() => errors.Count == 1); } [Fact] public async Task ErrorHandler_SeesTheReplayCheckpoint() { var errors = new RecordingErrorHandler(); await using var ctx = new RouteContext { ErrorHandler = errors }; ctx.AddRoutes(r => r .From("direct://scope-checkpoint") .RouteId("scope-checkpoint") .Replayable("after-load", m => m.Process(_ => throw new InvalidOperationException("boom")))); await ctx.Start(); await Send(ctx, "direct://scope-checkpoint"); errors.Count.Should().Be(1); errors.Exchanges.Single().Properties.Should().ContainKey(RouteCheckpoint.PropertyKey, "the checkpoint a dead letter queue replays from is on the exchange the error handler gets"); } [Fact] public async Task GlobalExceptionHandler_RunsOnAnOrdinaryRoute() { var hits = 0; await using var ctx = new RouteContext(); ctx.AddGlobalExceptionHandler( new DelegateProcessor(_ => Interlocked.Increment(ref hits))); ctx.AddRoutes(r => r .From("direct://scope-global") .Process(_ => throw new InvalidOperationException("boom"))); await ctx.Start(); await Send(ctx, "direct://scope-global"); Volatile.Read(ref hits).Should().Be(1); } [Fact] public async Task LocalExceptionHandler_RunsForItsOwnRouteOnly() { var hits = 0; await using var ctx = new RouteContext(); ctx.AddLocalExceptionHandler("scope-local-a", typeof(InvalidOperationException), new DelegateProcessor(_ => Interlocked.Increment(ref hits))); ctx.AddRoutes(r => { r.From("direct://scope-local-a").RouteId("scope-local-a") .Process(_ => throw new InvalidOperationException("a")); r.From("direct://scope-local-b").RouteId("scope-local-b") .Process(_ => throw new InvalidOperationException("b")); }); await ctx.Start(); await Send(ctx, "direct://scope-local-b"); await Send(ctx, "direct://scope-local-a"); Volatile.Read(ref hits).Should().Be(1); } [Fact] public async Task Threads_AFailureNoOnExceptionTook_ReachesTheErrorHandlerOnce() { var errors = new RecordingErrorHandler(); await using var ctx = new RouteContext { ErrorHandler = errors }; ctx.AddRoutes(r => r .From("direct://scope-threads-errorhandler") .Threads(2) .Process((IExchange _, CancellationToken _) => throw new InvalidOperationException("boom")) .End()); await ctx.Start(); await Send(ctx, "direct://scope-threads-errorhandler"); await WaitFor(() => errors.Count >= 1); await Task.Delay(200); errors.Count.Should().Be(1); } // ── Helpers ── private static async Task Send(IRouteContext ctx, string uri, object? body = null) { var producer = ctx.GetEndpoint(uri).CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message { Body = 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); } } private sealed class RecordingErrorHandler : IErrorHandler { private readonly ConcurrentQueue<(IExchange Exchange, Exception Exception)> _calls = new(); public bool MarkHandled { get; init; } public int Count => _calls.Count; public IEnumerable Exceptions => _calls.Select(c => c.Exception); public IEnumerable Exchanges => _calls.Select(c => c.Exchange); public Task HandleError(IExchange exchange, Exception exception, CancellationToken ct = default) { _calls.Enqueue((exchange, exception)); if (MarkHandled) exchange.ExceptionHandled = true; return Task.CompletedTask; } } } Path: redb-route/tests/redb.Route.Tests/Core/RoutePolicyStartFailureTests.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/RoutePolicyStartFailureTests.cs ---- using NSubstitute; using redb.Route.Abstractions; using redb.Route.Configuration; using redb.Route.Core; using redb.Route.Definitions; using redb.Route.Processors; namespace redb.Route.Tests.Core; /// /// At context start a route's consumer starts before its policy is asked. A policy that refuses marks the route /// Errored, and the consumer that already started is stopped: an Errored route does not go on taking messages. /// public sealed class RoutePolicyStartFailureTests { private sealed class RefusingPolicy : IRoutePolicy { public Task OnStart(IRouteContext context, CompiledRoute route, CancellationToken ct) => throw new InvalidOperationException("policy refuses"); } [Fact] public async Task A_policy_that_refuses_at_context_start_stops_the_consumer_it_follows() { await using var context = new RouteContext(options: new RouteEngineOptions { ShutdownTimeout = TimeSpan.FromMilliseconds(500), }); var consumer = Substitute.For(); consumer.Start(Arg.Any()).Returns(Task.CompletedTask); consumer.Stop(Arg.Any()).Returns(Task.CompletedTask); context.AddConsumer(consumer); context.AddRoute(new CompiledRoute("refused-at-start", "direct://refused-at-start", new RouteDefinition(), new PipelineProcessor(), consumer, Substitute.For()) { Policy = new RefusingPolicy() }); await context.Start(); context.GetRoute("refused-at-start")!.Status.Should().Be(RouteStatus.Errored); consumer.ReceivedCalls().Count(c => c.GetMethodInfo().Name == nameof(IConsumer.Stop)) .Should().Be(1, "an Errored route must not go on taking messages"); } } Path: redb-route/tests/redb.Route.Tests/Core/RoutePolicyTests.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/RoutePolicyTests.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Definitions; namespace redb.Route.Tests.Core; /// /// Tests for IRoutePolicy lifecycle, RoutePolicyFactory, and DSL integration. /// public sealed class RoutePolicyTests { /// Records all lifecycle method calls in order. private sealed class RecordingPolicy : IRoutePolicy { public List Calls { get; } = []; public Task OnInit(IRouteContext context, CompiledRoute route, CancellationToken ct) { Calls.Add("OnInit"); return Task.CompletedTask; } public Task OnStart(IRouteContext context, CompiledRoute route, CancellationToken ct) { Calls.Add("OnStart"); return Task.CompletedTask; } public Task OnStop(IRouteContext context, CompiledRoute route, CancellationToken ct) { Calls.Add("OnStop"); return Task.CompletedTask; } public Task OnRemove(IRouteContext context, CompiledRoute route, CancellationToken ct) { Calls.Add("OnRemove"); return Task.CompletedTask; } public Task OnSuspend(IRouteContext context, CompiledRoute route, CancellationToken ct) { Calls.Add("OnSuspend"); return Task.CompletedTask; } public Task OnResume(IRouteContext context, CompiledRoute route, CancellationToken ct) { Calls.Add("OnResume"); return Task.CompletedTask; } public Task OnExchangeBegin(IRouteContext context, IExchange exchange, CancellationToken ct) { Calls.Add("OnExchangeBegin"); return Task.CompletedTask; } public Task OnExchangeDone(IRouteContext context, IExchange exchange, CancellationToken ct) { Calls.Add("OnExchangeDone"); return Task.CompletedTask; } } private sealed class ThrowingOnStartPolicy : IRoutePolicy { public Task OnInit(IRouteContext context, CompiledRoute route, CancellationToken ct) => Task.CompletedTask; public Task OnStart(IRouteContext context, CompiledRoute route, CancellationToken ct) => throw new InvalidOperationException("OnStart failure"); public Task OnStop(IRouteContext context, CompiledRoute route, CancellationToken ct) => Task.CompletedTask; public Task OnRemove(IRouteContext context, CompiledRoute route, CancellationToken ct) => Task.CompletedTask; public Task OnSuspend(IRouteContext context, CompiledRoute route, CancellationToken ct) => Task.CompletedTask; public Task OnResume(IRouteContext context, CompiledRoute route, CancellationToken ct) => Task.CompletedTask; public Task OnExchangeBegin(IRouteContext context, IExchange exchange, CancellationToken ct) => Task.CompletedTask; public Task OnExchangeDone(IRouteContext context, IExchange exchange, CancellationToken ct) => Task.CompletedTask; } private sealed class TestFactory : IRoutePolicyFactory { private readonly Func _creator; public int CallCount { get; private set; } public TestFactory(Func creator) => _creator = creator; public IRoutePolicy? CreateRoutePolicy(IRouteContext context, string routeId, RouteDefinition definition) { CallCount++; return _creator(context, routeId, definition); } } private static RouteContext CreateContext() => new( options: new Configuration.RouteEngineOptions { EnableTelemetry = false, EnableMetrics = false }); // ── Lifecycle order ── [Fact] public async Task Policy_FullLifecycle_CallsInCorrectOrder() { var policy = new RecordingPolicy(); var ctx = CreateContext(); ctx.AddRoutes(r => { r.From("direct://policy-lifecycle") .RouteId("pol-lc") .RoutePolicy(policy) .Process(e => { }); }); await ctx.Start(); // Send one exchange to trigger OnExchangeBegin/OnExchangeDone var producer = ctx.GetEndpoint("direct://policy-lifecycle").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("test")), CancellationToken.None); await ctx.Stop(); policy.Calls.Should().ContainInOrder( "OnInit", "OnStart", "OnExchangeBegin", "OnExchangeDone", "OnSuspend", "OnStop", "OnRemove"); } [Fact] public async Task Policy_NoExchange_SkipsExchangeHooks() { var policy = new RecordingPolicy(); var ctx = CreateContext(); ctx.AddRoutes(r => { r.From("direct://no-exchange") .RouteId("no-ex") .RoutePolicy(policy) .Process(e => { }); }); await ctx.Start(); await ctx.Stop(); policy.Calls.Should().ContainInOrder("OnInit", "OnStart", "OnSuspend", "OnStop", "OnRemove"); policy.Calls.Should().NotContain("OnExchangeBegin"); policy.Calls.Should().NotContain("OnExchangeDone"); } // ── OnStart failure ── [Fact] public async Task Policy_OnStartThrows_RouteStaysStoppedOnManualStart() { var policy = new ThrowingOnStartPolicy(); var ctx = CreateContext(); ctx.AddRoutes(r => { r.From("direct://start-fail") .RouteId("sf-route") .RoutePolicy(policy) .AutoStart(false) // don't auto-start .Process(e => { }); }); await ctx.Start(); // Manual start should throw because OnStart throws var act = () => ctx.StartRoute("sf-route"); await act.Should().ThrowAsync() .WithMessage("OnStart failure"); var route = ctx.GetRoute("sf-route"); route.Should().NotBeNull(); route!.Status.Should().Be(RouteStatus.Errored); await ctx.Stop(); } // ── DSL ── [Fact] public void DSL_Cluster_SetsFlag() { var def = new RouteDefinition(); def.GetCluster().Should().BeFalse(); def.Cluster(); def.GetCluster().Should().BeTrue(); def.Cluster(false); def.GetCluster().Should().BeFalse(); } [Fact] public void DSL_RoutePolicy_SetsPolicy() { var policy = new RecordingPolicy(); var def = new RouteDefinition(); def.GetRoutePolicy().Should().BeNull(); def.RoutePolicy(policy); def.GetRoutePolicy().Should().BeSameAs(policy); } [Fact] public void DSL_ExplicitPolicy_OverridesCluster() { var policy = new RecordingPolicy(); var def = new RouteDefinition(); def.Cluster(true); def.RoutePolicy(policy); // Explicit policy should be used even if Cluster(true) is set def.GetRoutePolicy().Should().BeSameAs(policy); def.GetCluster().Should().BeTrue(); } // ── Factory chain ── [Fact] public async Task Factory_FirstNonNullWins() { var policy = new RecordingPolicy(); var factory1 = new TestFactory((_, _, _) => null); // returns null var factory2 = new TestFactory((_, _, _) => policy); // returns policy var factory3 = new TestFactory((_, _, _) => new RecordingPolicy()); // should not be called var ctx = CreateContext(); ctx.AddRoutePolicyFactory(factory1); ctx.AddRoutePolicyFactory(factory2); ctx.AddRoutePolicyFactory(factory3); ctx.AddRoutes(r => { r.From("direct://factory-chain") .RouteId("fc-route") .Process(e => { }); }); await ctx.Start(); await ctx.Stop(); factory1.CallCount.Should().Be(1); factory2.CallCount.Should().Be(1); factory3.CallCount.Should().Be(0, "third factory should not be called when second returned non-null"); // Verify the winning policy received lifecycle calls policy.Calls.Should().Contain("OnInit"); } [Fact] public async Task ExplicitPolicy_SkipsFactory() { var explicitPolicy = new RecordingPolicy(); var factory = new TestFactory((_, _, _) => new RecordingPolicy()); var ctx = CreateContext(); ctx.AddRoutePolicyFactory(factory); ctx.AddRoutes(r => { r.From("direct://explicit-policy") .RouteId("ep-route") .RoutePolicy(explicitPolicy) .Process(e => { }); }); await ctx.Start(); await ctx.Stop(); factory.CallCount.Should().Be(0, "factory should not be called when explicit policy is set"); explicitPolicy.Calls.Should().Contain("OnInit"); } [Fact] public async Task NoPolicy_NoFactory_RouteStartsNormally() { var ctx = CreateContext(); ctx.AddRoutes(r => { r.From("direct://no-policy") .RouteId("np-route") .Process(e => { }); }); await ctx.Start(); var route = ctx.GetRoute("np-route"); route.Should().NotBeNull(); route!.Status.Should().Be(RouteStatus.Started); await ctx.Stop(); } // ── Per-exchange hooks with exception ── [Fact] public async Task Policy_OnExchangeDone_CalledEvenOnException() { var policy = new RecordingPolicy(); var ctx = CreateContext(); ctx.AddRoutes(r => { r.From("direct://exception-exchange") .RouteId("ex-exc") .RoutePolicy(policy) .Process(e => throw new InvalidOperationException("boom")); r.OnException() .Process(e => e.ExceptionHandled = true); }); await ctx.Start(); var producer = ctx.GetEndpoint("direct://exception-exchange").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("test")), CancellationToken.None); await ctx.Stop(); // OnExchangeBegin and OnExchangeDone should both be called policy.Calls.Should().Contain("OnExchangeBegin"); policy.Calls.Should().Contain("OnExchangeDone"); // OnExchangeBegin should come before OnExchangeDone var beginIdx = policy.Calls.IndexOf("OnExchangeBegin"); var doneIdx = policy.Calls.IndexOf("OnExchangeDone"); beginIdx.Should().BeLessThan(doneIdx); } } Path: redb-route/tests/redb.Route.Tests/Core/RouteStatusTests.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/RouteStatusTests.cs ---- using NSubstitute; using redb.Route.Abstractions; using redb.Route.Configuration; using redb.Route.Core; using redb.Route.Definitions; using redb.Route.Processors; namespace redb.Route.Tests.Core; /// /// Tests for expanded RouteStatus transitions (Phase 4). /// public class RouteStatusTests : IAsyncLifetime { private readonly RouteContext _context; public RouteStatusTests() { _context = new RouteContext(options: new RouteEngineOptions { ShutdownTimeout = TimeSpan.FromMilliseconds(500) }); } public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { await _context.DisposeAsync(); GC.SuppressFinalize(this); } private static CompiledRoute MakeRoute(string id, IConsumer consumer, bool autoStart = true) => new(id, $"direct://{id}", new RouteDefinition(), new PipelineProcessor(), consumer, Substitute.For()) { AutoStart = autoStart }; [Fact] public void NewRoute_HasStoppedStatus() { var route = MakeRoute("test", Substitute.For()); route.Status.Should().Be(RouteStatus.Stopped); } [Fact] public async Task StartRoute_SetsStartedOnSuccess() { var consumer = Substitute.For(); consumer.Start(Arg.Any()).Returns(Task.CompletedTask); _context.AddConsumer(consumer); _context.AddRoute(MakeRoute("start-ok", consumer)); await _context.StartRoute("start-ok"); _context.GetRoute("start-ok")!.Status.Should().Be(RouteStatus.Started); } [Fact] public async Task StartRoute_SetsErroredOnFailure() { var consumer = Substitute.For(); consumer.Start(Arg.Any()) .Returns(Task.FromException(new InvalidOperationException("connection failed"))); _context.AddConsumer(consumer); _context.AddRoute(MakeRoute("start-fail", consumer)); var act = () => _context.StartRoute("start-fail"); await act.Should().ThrowAsync(); _context.GetRoute("start-fail")!.Status.Should().Be(RouteStatus.Errored); } [Fact] public async Task StopRoute_SetsSuspendingThenStopped() { var consumer = Substitute.For(); RouteStatus? statusDuringStop = null; consumer.Start(Arg.Any()).Returns(Task.CompletedTask); consumer.Stop(Arg.Any()) .Returns(ci => { statusDuringStop = _context.GetRoute("suspend-test")!.Status; return Task.CompletedTask; }); _context.AddConsumer(consumer); _context.AddRoute(MakeRoute("suspend-test", consumer)); await _context.StartRoute("suspend-test"); await _context.StopRoute("suspend-test"); statusDuringStop.Should().Be(RouteStatus.Suspended); _context.GetRoute("suspend-test")!.Status.Should().Be(RouteStatus.Stopped); } [Fact] public async Task StopRoute_SetsStoppingOnTimeout() { var consumer = Substitute.For(); consumer.Start(Arg.Any()).Returns(Task.CompletedTask); consumer.Stop(Arg.Any()) .Returns(async ci => { var token = ci.Arg(); await Task.Delay(Timeout.Infinite, token); }); _context.AddConsumer(consumer); _context.AddRoute(MakeRoute("timeout-test", consumer)); await _context.StartRoute("timeout-test"); await _context.StopRoute("timeout-test", TimeSpan.FromMilliseconds(100)); _context.GetRoute("timeout-test")!.Status.Should().Be(RouteStatus.Stopped); } [Fact] public async Task Stop_MarksRoutesSuspendingDuringShutdown() { var consumer = Substitute.For(); RouteStatus? capturedStatus = null; consumer.Start(Arg.Any()).Returns(Task.CompletedTask); consumer.Stop(Arg.Any()) .Returns(ci => { capturedStatus = _context.Routes[0].Status; return Task.CompletedTask; }); _context.AddConsumer(consumer); _context.AddRoute(MakeRoute("bulk-suspend", consumer)); await _context.Start(); _context.Routes[0].Status.Should().Be(RouteStatus.Started); await _context.Stop(); capturedStatus.Should().Be(RouteStatus.Suspended); } [Fact] public async Task Start_MarksFailedRoutesAsErrored() { var goodConsumer = Substitute.For(); var badConsumer = Substitute.For(); goodConsumer.Start(Arg.Any()).Returns(Task.CompletedTask); badConsumer.Start(Arg.Any()) .Returns(Task.FromException(new InvalidOperationException("boom"))); _context.AddConsumer(goodConsumer); _context.AddConsumer(badConsumer); _context.AddRoute(MakeRoute("good-route", goodConsumer)); _context.AddRoute(MakeRoute("bad-route", badConsumer)); await _context.Start(); _context.GetRoute("good-route")!.Status.Should().Be(RouteStatus.Started); _context.GetRoute("bad-route")!.Status.Should().Be(RouteStatus.Errored); } [Fact] public void RouteStatus_AllValuesExist() { var values = Enum.GetValues(); values.Should().HaveCount(7); values.Should().Contain(RouteStatus.Stopped); values.Should().Contain(RouteStatus.Started); values.Should().Contain(RouteStatus.Starting); values.Should().Contain(RouteStatus.Suspending); values.Should().Contain(RouteStatus.Suspended); values.Should().Contain(RouteStatus.Stopping); values.Should().Contain(RouteStatus.Errored); } } Path: redb-route/tests/redb.Route.Tests/Core/SafeXmlTests.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/SafeXmlTests.cs ---- using System.Text; using System.Xml; using System.Xml.Linq; using AwesomeAssertions; using redb.Route.Core; namespace redb.Route.Tests.Core; /// /// XML that came from somewhere else is read through , which refuses a document /// type declaration. The direct loaders expand one: measured on .NET 10, the 452-byte document below /// becomes 300 000 characters through XmlDocument.Load, XDocument.Load and /// XDocument.Parse alike, and XmlResolver = null changes nothing, because the expansion /// runs on internal entities. Scaled up, one small message costs the worker gigabytes and takes every /// route in the process down with it. /// public class SafeXmlTests { /// Nested internal entities — the "billion laughs" shape, kept small enough to be a test. private static string BillionLaughs(int levels = 5, int fanOut = 10) { var sb = new StringBuilder(""); for (var i = 1; i <= levels; i++) { sb.Append($""); } return sb.Append($"]>&lol{levels};").ToString(); } private static byte[] Bytes(string xml) => Encoding.UTF8.GetBytes(xml); [Fact] public void The_direct_loaders_do_expand_entities_which_is_why_this_type_exists() { var xml = BillionLaughs(); // Not a test of our code: a guard on the premise. If a future runtime starts refusing a DTD // here, this fails and the next reader of SafeXml learns the reason it was written is gone. XDocument.Parse(xml).Root!.Value.Length.Should().BeGreaterThan(100_000); var dom = new XmlDocument { XmlResolver = null }; dom.Load(new MemoryStream(Bytes(xml))); dom.DocumentElement!.InnerText.Length.Should().BeGreaterThan(100_000); } [Fact] public void Every_loader_refuses_a_document_type_declaration() { var xml = BillionLaughs(); var bytes = Bytes(xml); var loaders = new List<(string Name, Action Act)> { ("Load(byte[])", () => SafeXml.Load(bytes)), ("Load(Stream)", () => SafeXml.Load(new MemoryStream(bytes))), ("Parse(string)", () => SafeXml.Parse(xml)), ("ParseElement(string)", () => SafeXml.ParseElement(xml)), ("LoadDocument(byte[])", () => SafeXml.LoadDocument(bytes)), }; foreach (var (name, act) in loaders) act.Should().Throw($"{name} must refuse a DTD instead of expanding it"); } [Fact] public void A_dtd_without_entities_is_refused_just_the_same() { // The refusal is of the declaration, not of what it happens to contain: a DTD that looks // harmless today is still an entity expansion away from not being one. const string xml = ""; var act = () => SafeXml.Parse(xml); act.Should().Throw(); } [Fact] public void Ordinary_documents_read_exactly_as_before() { const string xml = """ Ящик """; var doc = SafeXml.Parse(xml); var ns = XNamespace.Get("urn:acme"); doc.Root!.Name.Should().Be(ns + "order"); doc.Root.Attribute("id")!.Value.Should().Be("7"); doc.Root.Element(ns + "item")!.Value.Should().Be("Ящик"); doc.Root.Element(ns + "note")!.Value.Should().Be("a < b & c"); SafeXml.Load(Bytes(xml)).Root!.Name.Should().Be(ns + "order"); SafeXml.LoadDocument(Bytes(xml)).DocumentElement!.LocalName.Should().Be("order"); SafeXml.ParseElement("").Name.LocalName.Should().Be("a"); } [Fact] public void Line_info_and_whitespace_survive_the_reader() { // Two properties other call sites depend on: markup errors are reported by position, and a // signed document must keep its whitespace or canonicalization fails. var doc = SafeXml.Parse("\n \n", LoadOptions.SetLineInfo | LoadOptions.PreserveWhitespace); ((IXmlLineInfo)doc.Root!.Element("b")!).LineNumber.Should().Be(2); doc.Root.ToString(SaveOptions.DisableFormatting).Should().Contain("\n "); SafeXml.LoadDocument(Bytes(" ")).PreserveWhitespace.Should().BeTrue(); } [Fact] public void A_document_over_the_size_bound_is_refused() { var big = "" + new string('x', 5_000) + ""; var act = () => SafeXml.Parse(big, maxCharacters: 1_000); act.Should().Throw("a caller that knows a sane size can cap it"); } // ── Structure limits ───────────────────────────────────────────────────── private static string Nested(int levels) => string.Concat(Enumerable.Repeat("", levels)) + string.Concat(Enumerable.Repeat("", levels)); private static string Attributes(int count, string prefix = "a") => " prefix == "xmlns" ? $"xmlns:p{i}=\"urn:{i}\"" : $"a{i}=\"v\"")) + "/>"; public static TheoryData OverALimit() => new() { { nameof(XmlLimits.MaxDepth), Nested(XmlLimits.DefaultMaxDepth + 1), XmlLimits.Default }, { nameof(XmlLimits.MaxAttributesPerElement), Attributes(XmlLimits.DefaultMaxAttributesPerElement + 1), XmlLimits.Default }, { nameof(XmlLimits.MaxNamespaceDeclarationsPerElement), Attributes(XmlLimits.DefaultMaxNamespaceDeclarationsPerElement + 1, "xmlns"), XmlLimits.Default }, { nameof(XmlLimits.MaxNamespaceDeclarations), "" + string.Concat(Enumerable.Range(0, 11).Select(i => $"")) + "", XmlLimits.Default with { MaxNamespaceDeclarations = 10 } }, { nameof(XmlLimits.MaxElements), "" + string.Concat(Enumerable.Repeat("", 10)) + "", XmlLimits.Default with { MaxElements = 10 } }, }; [Theory] [MemberData(nameof(OverALimit))] public void Every_loader_refuses_a_document_over_a_limit_and_names_it(string limit, string xml, XmlLimits limits) { var bytes = Bytes(xml); var loaders = new List<(string Name, Action Act)> { ("Load(byte[])", () => SafeXml.Load(bytes, limits)), ("Load(Stream)", () => SafeXml.Load(new MemoryStream(bytes), limits)), ("Parse(string)", () => SafeXml.Parse(xml, limits)), ("ParseElement(string)", () => SafeXml.ParseElement(xml, limits)), ("LoadDocument(byte[])", () => SafeXml.LoadDocument(bytes, limits)), ("Check(byte[])", () => SafeXml.Check(bytes, limits)), }; foreach (var (name, act) in loaders) act.Should().Throw(name).Which.Limit.Should().Be(limit, name); } [Fact] public void The_loaders_without_limits_apply_the_default_ones() { // Existing call sites (XPath over a message body, SOAP, route markup) get the structure limits without a change. var deep = Nested(XmlLimits.DefaultMaxDepth + 1); ((Action)(() => SafeXml.Parse(deep))).Should().Throw().Which.Limit.Should().Be(nameof(XmlLimits.MaxDepth)); ((Action)(() => SafeXml.LoadDocument(Bytes(deep)))).Should().Throw(); ((Action)(() => SafeXml.Load(Bytes(deep), maxCharacters: 10_000_000))).Should().Throw(); } [Fact] public void A_document_at_every_limit_reads() { SafeXml.Parse(Nested(XmlLimits.DefaultMaxDepth)).Descendants("x").Should().HaveCount(XmlLimits.DefaultMaxDepth); SafeXml.Parse(Attributes(XmlLimits.DefaultMaxAttributesPerElement)).Root!.Attributes().Should().HaveCount(XmlLimits.DefaultMaxAttributesPerElement); SafeXml.Parse(Attributes(XmlLimits.DefaultMaxNamespaceDeclarationsPerElement, "xmlns")).Root.Should().NotBeNull(); SafeXml.Parse("", XmlLimits.Default with { MaxElements = 3, MaxNamespaceDeclarations = 1 }).Root!.Elements().Should().HaveCount(2); } [Fact] public void A_limit_violation_is_an_xml_exception_with_its_position() { // Callers that answer malformed XML as the sender's fault (SOAP, AS4) answer this the same way, with the place. var act = () => SafeXml.Parse("\n \n \n", XmlLimits.Default with { MaxElements = 2 }); var thrown = act.Should().Throw().Which; thrown.Should().BeAssignableTo(); thrown.LineNumber.Should().Be(3); thrown.Maximum.Should().Be(2); thrown.Message.Should().Contain("MaxElements"); } [Fact] public void A_deep_document_is_refused_at_the_limit_not_after_reading_it_all() { // 200 000 levels: refused at level 257, so the time does not grow with the document. var watch = System.Diagnostics.Stopwatch.StartNew(); ((Action)(() => SafeXml.Parse(Nested(200_000)))).Should().Throw(); watch.Elapsed.Should().BeLessThan(TimeSpan.FromSeconds(2)); } [Fact] public void Line_info_and_whitespace_survive_the_limited_reader() { var doc = SafeXml.Parse("\n \n", XmlLimits.Default, LoadOptions.SetLineInfo | LoadOptions.PreserveWhitespace); ((IXmlLineInfo)doc.Root!.Element("b")!).LineNumber.Should().Be(2); doc.Root.ToString(SaveOptions.DisableFormatting).Should().Contain("\n "); } [Fact] public void A_limit_of_zero_is_refused_as_a_setting() { var act = () => SafeXml.Parse("", XmlLimits.Default with { MaxDepth = 0 }); act.Should().Throw().Which.ParamName.Should().Be(nameof(XmlLimits.MaxDepth)); } } Path: redb-route/tests/redb.Route.Tests/Core/ScopeNestingValidationTests.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/ScopeNestingValidationTests.cs ---- using AwesomeAssertions; using Microsoft.Extensions.Logging; using redb.Route.Core; namespace redb.Route.Tests.Core; /// /// Tests for the generic scope-nesting validation mechanism (ICompositeScope / IDurableScope / /// IScopeNestingRule), exercised through the replay checkpoint constraint: a checkpoint may not /// cross a branching composite (build error, §6) and warns inside a durable transaction (§10). /// public class ScopeNestingValidationTests { private static RouteContext New() => new("nesting-test"); [Fact] public async Task Checkpoint_InsideFilter_FailsBuild() { var ctx = New(); ctx.AddRoutes(r => r .From("direct:f").RouteId("f") .Filter(_ => true) .Replayable("m", b => b.Process(_ => { })) .EndFilter() .To("direct:sink")); var act = () => ctx.Start(); (await act.Should().ThrowAsync()).Which.Message .Should().Contain("cannot cross").And.Contain("FilterDefinition"); await ctx.DisposeAsync(); } [Fact] public async Task Checkpoint_InsideChoiceBranch_FailsBuild() { var ctx = New(); ctx.AddRoutes(r => r .From("direct:c").RouteId("c") .Choice() .When(_ => true) .Replayable("m", b => b.Process(_ => { })) .EndChoice() .To("direct:sink")); var act = () => ctx.Start(); (await act.Should().ThrowAsync()).Which.Message.Should().Contain("cannot cross"); await ctx.DisposeAsync(); } [Fact] public async Task Checkpoint_InsideSplit_FailsBuild() { var ctx = New(); ctx.AddRoutes(r => r .From("direct:s").RouteId("s") .Split(ex => new object?[] { 1, 2 }) .Replayable("m", b => b.Process(_ => { })) .EndSplit()); var act = () => ctx.Start(); (await act.Should().ThrowAsync()).Which.Message .Should().Contain("cannot cross").And.Contain("SplitDefinition"); await ctx.DisposeAsync(); } [Fact] public async Task Checkpoint_InsideTransaction_Warns_ButBuilds() { var warnings = new List(); var loggerFactory = LoggerFactory.Create(b => b.AddProvider(new CapturingLoggerProvider(warnings))); var ctx = new RouteContext("tx", loggerFactory); ctx.AddRoutes(r => r .From("direct:tx").RouteId("tx") .Transaction() .Replayable("m", b => b.Process(_ => { })) .EndTransaction()); await ctx.Start(); // must NOT throw ctx.GetReplayMarkers().Should().Contain(("tx", "m")); warnings.Should().Contain(w => w.Contains("runs") && w.Contains("OUTSIDE that transaction")); await ctx.DisposeAsync(); } [Fact] public async Task Checkpoint_TopLevel_IsAllowed() { var ctx = New(); ctx.AddRoutes(r => r .From("direct:ok").RouteId("ok") .Replayable("m").Process(_ => { })); var act = () => ctx.Start(); await act.Should().NotThrowAsync(); await ctx.DisposeAsync(); } [Fact] public async Task NestedCheckpoints_AreAllowed() { var ctx = New(); ctx.AddRoutes(r => r .From("direct:nest").RouteId("nest") .Replayable("outer") .Process(_ => { }) .Replayable("inner", b => b.Process(_ => { }))); var act = () => ctx.Start(); await act.Should().NotThrowAsync(); ctx.GetReplayMarkers().Select(m => m.MarkerName).Should().Contain(new[] { "outer", "inner" }); 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/SecretNeverLeavesTheProcessTests.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/SecretNeverLeavesTheProcessTests.cs ---- using System.Diagnostics; using System.Diagnostics.Metrics; using System.Text.Json; using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Configuration; using redb.Route.Core; using redb.Route.Extensions; using redb.Route.Telemetry; using redb.Route.TestKit; namespace redb.Route.Tests.Core; /// /// The end-to-end regression for URI secret redaction: a route whose consumer URI carries secrets /// in every shape (query parameter, connector-specific name, userinfo password) is compiled, started /// and stopped, and **no** secret may appear on any surface that leaves the process — log lines, span /// tags, metric labels, the route DTO the dashboard reads, or the health-check payload. /// /// Each secret is unique to this run, so the assertions are immune to what other tests do in parallel: /// nobody else can emit this string, and a leak cannot be masked by someone else's silence. /// /// public class SecretNeverLeavesTheProcessTests { private static readonly string Nonce = Guid.NewGuid().ToString("N")[..8]; private static readonly string QuerySecret = $"pw-query-{Nonce}"; private static readonly string LdapSecret = $"pw-ldap-{Nonce}"; // bindPassword: the LDAP leak of the audit private static readonly string AwsSecret = $"tok-aws-{Nonce}"; // sessionToken: the S3/SQS leak of the audit private static readonly string UserInfoSecret = $"pw-userinfo-{Nonce}"; private static string[] AllSecrets => [QuerySecret, LdapSecret, AwsSecret, UserInfoSecret]; private static string RouteUri => $"direct://user:{UserInfoSecret}@orders-{Nonce}" + $"?password={QuerySecret}&bindPassword={LdapSecret}&sessionToken={AwsSecret}&acks=all"; [Fact] public async Task NoSurfaceThatLeavesTheProcessCarriesASecret() { var log = new CapturingLogs(); using var loggerFactory = LoggerFactory.Create(b => { b.SetMinimumLevel(LogLevel.Trace); b.AddProvider(log); }); var spanTags = new List(); using var listener = new ActivityListener { ShouldListenTo = s => s.Name == RouteActivitySource.SourceName, Sample = (ref ActivityCreationOptions _) => ActivitySamplingResult.AllDataAndRecorded, ActivityStopped = a => { lock (spanTags) spanTags.AddRange(a.Tags.Select(t => $"{t.Key}={t.Value}")); }, }; ActivitySource.AddActivityListener(listener); var metricTags = new List(); using var meterListener = new MeterListener { InstrumentPublished = (instrument, l) => { if (instrument.Meter.Name == RouteMetrics.MeterName) l.EnableMeasurementEvents(instrument); }, }; meterListener.SetMeasurementEventCallback((_, _, tags, _) => Record(tags)); meterListener.SetMeasurementEventCallback((_, _, tags, _) => Record(tags)); meterListener.Start(); string dtoFromUri; string healthPayload; // Telemetry and metrics on: without them a plain route emits no span and no measurement, and the // two surfaces would be asserted against an empty collection — a guard that cannot fail. var options = new RouteEngineOptions { EnableTelemetry = true, EnableMetrics = true }; await using (var ctx = new RouteContext(loggerFactory: loggerFactory, options: options)) { // Two routes on purpose: one that succeeds and one that fails. A failing route is the case // where the span carries an error status and an exception event, and where the endpoint URI // is most likely to be rendered into a diagnostic. ctx.AddRoutes(b => { b.From(RouteUri).To("mock://out"); b.From($"direct://failing-{Nonce}?password={QuerySecret}") .Process(_ => throw new InvalidOperationException("route failed on purpose")); }); await ctx.Start(); await ctx.SendBody(RouteUri, "payload"); var failing = () => ctx.SendBody($"direct://failing-{Nonce}?password={QuerySecret}", "payload"); await failing.Should().ThrowAsync(); dtoFromUri = ctx.Routes.Should().HaveCount(2).And.Subject .Single(r => r.FromUri.Contains($"orders-{Nonce}")).FromUri; var health = await new RouteHealthCheck(ctx).CheckHealthAsync(new HealthCheckContext()); healthPayload = JsonSerializer.Serialize(health.Data); await ctx.Stop(); } meterListener.Dispose(); // Positive controls first. Every surface below is asserted with a negative ("no secret"), and a // negative alone is satisfied by a surface that says nothing at all — which would be a useless // guard. So each one is first shown to actually carry this route, redacted. dtoFromUri.Should().Contain($"orders-{Nonce}", "the route must stay recognisable after redaction"); dtoFromUri.Should().Contain(EndpointUri.Redacted); string.Join("\n", log.Lines).Should().Contain($"orders-{Nonce}", "the log does mention this route"); string.Join("\n", spanTags).Should().Contain(Nonce, "spans do carry this route's endpoint"); string.Join("\n", metricTags).Should().Contain(Nonce, "metric labels do carry this route"); healthPayload.Should().Contain($"orders-{Nonce}", "the health payload does list this route"); // The failing route ran, so the error path of the span (status + exception event) was exercised. string.Join("\n", spanTags).Should().Contain($"failing-{Nonce}"); foreach (var secret in AllSecrets) { string.Join("\n", log.Lines).Should().NotContain(secret, "a log line must never carry a secret"); string.Join("\n", spanTags).Should().NotContain(secret, "a span tag must never carry a secret"); string.Join("\n", metricTags).Should().NotContain(secret, "a metric label must never carry a secret"); dtoFromUri.Should().NotContain(secret, "the route DTO is what the dashboard renders"); healthPayload.Should().NotContain(secret, "the health payload is served over HTTP"); } void Record(ReadOnlySpan> tags) { var rendered = new List(); foreach (var tag in tags) rendered.Add($"{tag.Key}={tag.Value}"); lock (metricTags) metricTags.AddRange(rendered); } } private sealed class CapturingLogs : ILoggerProvider { private readonly List _lines = []; public IReadOnlyList Lines { get { lock (_lines) return [.. _lines]; } } public ILogger CreateLogger(string categoryName) => new Sink(this); public void Dispose() { } private sealed class Sink(CapturingLogs owner) : ILogger { public IDisposable? BeginScope(TState state) where TState : notnull => null; public bool IsEnabled(LogLevel logLevel) => true; public void Log(LogLevel level, EventId id, TState state, Exception? ex, Func formatter) { var line = formatter(state, ex) + (ex is null ? "" : " | " + ex); lock (owner._lines) owner._lines.Add(line); } } } } Path: redb-route/tests/redb.Route.Tests/Core/SedaConsumerResilienceTests.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/SedaConsumerResilienceTests.cs ---- using AwesomeAssertions; using redb.Route.Core; namespace redb.Route.Tests.Core; /// /// Regression for GitHub issue #6: an unhandled exception in a SEDA consumer used to terminate the worker /// loop permanently and silently (the loop caught only cancellation / channel-closed). One failing exchange /// must not stop the consumer from draining the rest of the queue. /// public class SedaConsumerResilienceTests { [Fact] public async Task Seda_keeps_consuming_after_one_exchange_fails() { await using var ctx = new RouteContext("test"); var seen = new List(); ctx.AddRoutes(r => r.From("seda://work?concurrentConsumers=1") .RouteId("worker") .Process((ex, _) => { var body = ex.In.Body?.ToString()!; if (body == "bad") throw new InvalidOperationException("boom"); lock (seen) seen.Add(body); return Task.CompletedTask; })); await ctx.Start(); using var producer = new ProducerTemplate(ctx); producer.Start(); await producer.SendAsync("seda://work?concurrentConsumers=1", "first"); await producer.SendAsync("seda://work?concurrentConsumers=1", "bad"); await producer.SendAsync("seda://work?concurrentConsumers=1", "second"); // The failing "bad" exchange must not stop the worker from reaching "second". await WaitUntil(() => { lock (seen) return seen.Count >= 2; }, TimeSpan.FromSeconds(5)); lock (seen) seen.Should().Equal("first", "second"); } private static async Task WaitUntil(Func condition, TimeSpan timeout) { var deadline = DateTime.UtcNow + timeout; while (DateTime.UtcNow < deadline) { if (condition()) return; await Task.Delay(25); } } } Path: redb-route/tests/redb.Route.Tests/Core/ShutdownTimeoutTests.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/ShutdownTimeoutTests.cs ---- using AwesomeAssertions; using NSubstitute; using redb.Route.Abstractions; using redb.Route.Configuration; using redb.Route.Core; namespace redb.Route.Tests.Core; /// /// Tests for and /// shutdown timeout enforcement (Phase 3). /// public sealed class ShutdownTimeoutTests : IDisposable { private readonly RouteContext _ctx; public ShutdownTimeoutTests() { _ctx = new RouteContext("shutdown-test", options: new RouteEngineOptions { ShutdownTimeout = TimeSpan.FromSeconds(2) }); } public void Dispose() => _ctx.Dispose(); [Fact] public async Task Stop_CompletesGracefully_WhenConsumersStopWithinTimeout() { // Arrange — consumer that stops fast var consumer = Substitute.For(); consumer.Start(Arg.Any()).Returns(Task.CompletedTask); consumer.Stop(Arg.Any()).Returns(Task.CompletedTask); _ctx.AddConsumer(consumer); await _ctx.Start(); // Act await _ctx.Stop(); // Assert — Stop was called await consumer.Received(1).Stop(Arg.Any()); } [Fact] public async Task Stop_ForcesShutdown_WhenConsumerExceedsTimeout() { // Arrange — consumer that blocks forever until CT fires var consumer = Substitute.For(); consumer.Start(Arg.Any()).Returns(Task.CompletedTask); consumer.Stop(Arg.Any()) .Returns(ci => { var ct = ci.Arg(); return Task.Delay(Timeout.Infinite, ct); }); var options = new RouteEngineOptions { ShutdownTimeout = TimeSpan.FromMilliseconds(200) }; using var ctx = new RouteContext("timeout-ctx", options: options); ctx.AddConsumer(consumer); await ctx.Start(); // Act — should not hang, ShutdownTimeout kicks in var stopTask = ctx.Stop(); var completed = await Task.WhenAny(stopTask, Task.Delay(TimeSpan.FromSeconds(5))); // Assert completed.Should().BeSameAs(stopTask, "Stop() should complete after ShutdownTimeout, not hang"); } [Fact] public async Task Stop_PassesCancellationToken_LinkedToShutdownTimeout() { // Arrange — consumer that captures the CT CancellationToken capturedCt = default; var consumer = Substitute.For(); consumer.Start(Arg.Any()).Returns(Task.CompletedTask); consumer.Stop(Arg.Any()) .Returns(ci => { capturedCt = ci.Arg(); return Task.CompletedTask; }); var options = new RouteEngineOptions { ShutdownTimeout = TimeSpan.FromSeconds(5) }; using var ctx = new RouteContext("ct-test", options: options); ctx.AddConsumer(consumer); await ctx.Start(); // Act await ctx.Stop(); // Assert — the CT passed to consumer should be cancellable (linked to timeout) capturedCt.CanBeCanceled.Should().BeTrue("CT should be linked to ShutdownTimeout"); } [Fact] public async Task StopRoute_ThrowsForUnknownRouteId() { await _ctx.Start(); var act = () => _ctx.StopRoute("nonexistent-route"); await act.Should().ThrowAsync() .WithMessage("*not found*"); } [Fact] public async Task StopRoute_Overload_AcceptsNullTimeout() { await _ctx.Start(); // null timeout should fall back to ShutdownTimeout — but route doesn't exist var act = () => _ctx.StopRoute("no-such-route", null); await act.Should().ThrowAsync() .WithMessage("*not found*"); } [Fact] public async Task Stop_MultipleConsumers_AllReceiveLinkedCt() { // Arrange — two consumers, both capture CT var cts = new List(); IConsumer MakeConsumer() { var c = Substitute.For(); c.Start(Arg.Any()).Returns(Task.CompletedTask); c.Stop(Arg.Any()).Returns(ci => { cts.Add(ci.Arg()); return Task.CompletedTask; }); return c; } var options = new RouteEngineOptions { ShutdownTimeout = TimeSpan.FromSeconds(5) }; using var ctx = new RouteContext("multi-consumer", options: options); ctx.AddConsumer(MakeConsumer()); ctx.AddConsumer(MakeConsumer()); await ctx.Start(); // Act await ctx.Stop(); // Assert — both got cancellable tokens cts.Should().HaveCount(2); cts.Should().AllSatisfy(ct => ct.CanBeCanceled.Should().BeTrue()); } [Fact] public async Task Stop_Idempotent_WhenCalledTwice() { var consumer = Substitute.For(); consumer.Start(Arg.Any()).Returns(Task.CompletedTask); consumer.Stop(Arg.Any()).Returns(Task.CompletedTask); _ctx.AddConsumer(consumer); await _ctx.Start(); // Act await _ctx.Stop(); await _ctx.Stop(); // second call // Assert — Stop() was only called once on consumer (second Stop() exits early) await consumer.Received(1).Stop(Arg.Any()); } } Path: redb-route/tests/redb.Route.Tests/Core/StaticEndpointWarmupTests.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/StaticEndpointWarmupTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Components; using redb.Route.Core; using redb.Route.Processors.LoadBalancer; namespace redb.Route.Tests.Core; /// /// The endpoint of a static target — To, WireTap, a load balancer's targets — is created when the route /// starts, as Camel resolves a static to(...) at route startup: an unknown scheme, an unknown URI parameter or a /// missing {{key}} stops the start instead of failing the first message hours later. A dynamic target /// (ToD, a recipient list) stays lazy, and no producer is created or started before a message needs it — unlike /// Camel, which starts its producers too: that would open a connection to every broker at startup. /// public class StaticEndpointWarmupTests { private sealed class CountingComponent : ComponentBase { public int Producers; public override string Scheme => "counting"; public override IEndpoint CreateEndpoint(EndpointUri uri) => new CountingEndpoint(uri, this); private sealed class CountingEndpoint(EndpointUri uri, CountingComponent owner) : IEndpoint { public EndpointUri Uri { get; } = uri; public IComponent Component => owner; public IProducer CreateProducer() { Interlocked.Increment(ref owner.Producers); throw new InvalidOperationException("no producer is created at startup"); } public IConsumer CreateConsumer(IProcessor processor) => throw new NotSupportedException(); public Task Start(CancellationToken ct = default) => Task.CompletedTask; public Task Stop(CancellationToken ct = default) => Task.CompletedTask; } } private static RouteContext Context(out CountingComponent counting) { var context = new RouteContext($"warmup-{Guid.NewGuid():N}"); context.AddComponent(new DirectComponent()); context.AddComponent(counting = new CountingComponent()); return context; } private static bool Created(RouteContext context, string fragment) => context.GetEndpoints().Any(e => e.Uri.NormalizedKey.Contains(fragment, StringComparison.Ordinal)); [Fact] public async Task A_To_with_an_unknown_scheme_stops_the_start() { await using var context = Context(out _); context.AddRoutes(r => r.From("direct://warm-unknown").To("nosuchscheme://target")); var act = () => context.Start(); await act.Should().ThrowAsync().WithMessage("*nosuchscheme*"); } [Fact] public async Task A_To_with_an_unknown_URI_parameter_stops_the_start() { await using var context = Context(out _); context.AddComponent(new LogComponent()); context.AddRoutes(r => r.From("direct://warm-param").To("log:warm-target?noSuchOption=1")); var act = () => context.Start(); await act.Should().ThrowAsync().WithMessage("*noSuchOption*"); } [Fact] public async Task A_To_with_a_missing_configuration_placeholder_stops_the_start() { await using var context = Context(out _); context.AddRoutes(r => r.From("direct://warm-placeholder").To("direct://{{warmup.missing.key}}")); var act = () => context.Start(); await act.Should().ThrowAsync().WithMessage("*warmup.missing.key*"); } [Fact] public async Task Static_targets_exist_after_the_start_without_a_message_and_no_producer_was_made() { await using var context = Context(out var counting); context.AddRoutes(r => r.From("direct://warm-static") .To("counting://to-target") .WireTap("counting://tap-target") .LoadBalance(new RoundRobinStrategy(), "counting://lb-a", "counting://lb-b")); await context.Start(); Created(context, "to-target").Should().BeTrue(); Created(context, "tap-target").Should().BeTrue(); Created(context, "lb-a").Should().BeTrue(); Created(context, "lb-b").Should().BeTrue(); counting.Producers.Should().Be(0, "a producer is created when a message needs it"); } [Fact] public async Task Static_enrich_poll_enrich_and_scatter_gather_targets_exist_after_the_start() { await using var context = Context(out var counting); context.AddRoutes(r => r.From("direct://warm-enrich") .Enrich("counting://enrich-target") .PollEnrich("counting://poll-target") .ScatterGather(static (acc, next) => next, "counting://sg-a", "counting://sg-b")); await context.Start(); Created(context, "enrich-target").Should().BeTrue(); Created(context, "poll-target").Should().BeTrue(); Created(context, "sg-a").Should().BeTrue(); Created(context, "sg-b").Should().BeTrue(); counting.Producers.Should().Be(0); } [Fact] public async Task Dynamic_enrich_and_poll_enrich_stay_lazy() { await using var context = Context(out _); context.AddRoutes(r => r.From("direct://warm-lazy-enrichers") .Enrich(_ => "counting://enrich-dynamic") .PollEnrich(_ => "counting://poll-dynamic")); await context.Start(); Created(context, "enrich-dynamic").Should().BeFalse(); Created(context, "poll-dynamic").Should().BeFalse(); } [Fact] public async Task Dynamic_targets_stay_lazy() { await using var context = Context(out _); context.AddRoutes(r => r.From("direct://warm-dynamic") .ToD("counting://tod-${header.name}") .RecipientList(_ => ["counting://recipient-target"])); await context.Start(); Created(context, "tod-").Should().BeFalse(); Created(context, "recipient-target").Should().BeFalse(); } } Path: redb-route/tests/redb.Route.Tests/Core/StreamCachePublicApiTests.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/StreamCachePublicApiTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Configuration; using redb.Route.Core; using redb.Route.Processors; namespace redb.Route.Tests.Core; /// /// as connectors use it (AS4 spools a decrypted attachment before the route may see it): /// written through, then completed and read from the start. Plus the caching step's ownership of the stream it /// replaces, the engine-wide switch, and the byte count of a stream body. /// public class StreamCachePublicApiTests : IDisposable { private readonly string _temp = Directory.CreateTempSubdirectory("redb-streamcache-").FullName; public void Dispose() { try { Directory.Delete(_temp, recursive: true); } catch (IOException) { } GC.SuppressFinalize(this); } private sealed class TrackingStream(byte[] data) : MemoryStream(data) { public bool Disposed { get; private set; } protected override void Dispose(bool disposing) { Disposed = true; base.Dispose(disposing); } public override ValueTask DisposeAsync() { Disposed = true; return base.DisposeAsync(); } } /// Forward-only, as a network or decrypting stream is. private sealed class ForwardOnlyStream(byte[] data) : MemoryStream(data) { public override bool CanSeek => false; public override long Length => throw new NotSupportedException(); } [Fact] public async Task Written_through_then_completed_it_reads_from_the_start_and_spools_past_the_threshold() { var data = Enumerable.Range(0, 5000).Select(i => (byte)i).ToArray(); await using var cache = new StreamCache(new StreamCacheOptions { SpoolThreshold = 1024, TempDirectory = _temp }); await cache.WriteAsync(data.AsMemory(0, 3000)); cache.Write(data, 3000, 2000); cache.IsSpooled.Should().BeTrue(); Directory.GetFiles(_temp).Should().ContainSingle("the content above the threshold went to a temporary file"); cache.CompleteWriting(); cache.CanWrite.Should().BeFalse(); cache.CanSeek.Should().BeTrue(); var read = new MemoryStream(); await cache.CopyToAsync(read); read.ToArray().Should().Equal(data); } [Fact] public async Task It_refuses_to_be_read_before_writing_completed_and_written_after() { await using var cache = new StreamCache(new StreamCacheOptions { TempDirectory = _temp }); cache.Write([1, 2, 3], 0, 3); var readEarly = () => cache.ReadByte(); readEarly.Should().Throw().WithMessage("*CompleteWriting*"); cache.CompleteWriting(); var writeLate = () => cache.Write([4], 0, 1); writeLate.Should().Throw(); } [Fact] public async Task Disposing_it_removes_the_temporary_file() { var cache = new StreamCache(new StreamCacheOptions { SpoolThreshold = 16, TempDirectory = _temp }); await cache.WriteAsync(new byte[100]); Directory.GetFiles(_temp).Should().HaveCount(1); await cache.DisposeAsync(); Directory.GetFiles(_temp).Should().BeEmpty(); } [Fact] public async Task The_caching_step_closes_the_stream_it_replaces() { var source = new TrackingStream("payload"u8.ToArray()); var exchange = new Exchange(new Message(source)); await new StreamCachingTransformer(new StreamCacheOptions { TempDirectory = _temp }).Process(exchange); exchange.In.Body.Should().BeOfType(); source.Disposed.Should().BeTrue("the exchange now owns the cache; nobody else would ever close the source"); } [Fact] public async Task The_engine_switch_caches_every_routes_stream_body() { var options = new RouteEngineOptions(); options.StreamCaching.Enabled = true; options.StreamCaching.TempDirectory = _temp; await using var context = new RouteContext(options: options); object? seen = null; context.AddRoutes(r => r.From("direct://cached").Process(e => seen = e.In.Body)); await context.Start(); var producer = context.GetEndpoint("direct://cached").CreateProducer(); await producer.Process(new Exchange(new Message(new ForwardOnlyStream("abc"u8.ToArray())))); seen.Should().BeOfType("StreamCacheOptions.Enabled turns caching on for all routes"); } [Theory] [InlineData(true)] [InlineData(false)] public void The_byte_count_of_a_stream_body_is_its_length_or_nothing(bool seekable) { Stream body = seekable ? new MemoryStream(new byte[42]) : new ForwardOnlyStream(new byte[42]); var size = EndpointBase.EstimateBodySize(body); size.Should().Be(seekable ? 42 : 0, "a forward-only stream cannot be measured without reading it"); if (!seekable) body.Position.Should().Be(0, "measuring must not consume the body"); } } /// /// The stream cache options a connector spools with come from the same chain the .StreamCaching() step uses: /// a registered , then the engine's , /// then the defaults. /// public class StreamCacheOptionsResolutionTests { [Fact] public async Task The_engine_options_reach_a_connector() { var engine = new RouteEngineOptions(); engine.StreamCaching.SpoolThreshold = 4096; engine.StreamCaching.TempDirectory = "/spool"; await using var context = new RouteContext(options: engine); var options = redb.Route.Extensions.RouteContextExtensions.GetStreamCacheOptions(context); options.SpoolThreshold.Should().Be(4096); options.TempDirectory.Should().Be("/spool"); } [Fact] public async Task A_registered_service_wins_over_the_engine_options() { var engine = new RouteEngineOptions(); engine.StreamCaching.SpoolThreshold = 4096; await using var context = new RouteContext(options: engine); context.AddService(typeof(StreamCacheOptions), new StreamCacheOptions { SpoolThreshold = 99 }); redb.Route.Extensions.RouteContextExtensions.GetStreamCacheOptions(context).SpoolThreshold.Should().Be(99); } [Fact] public void Without_a_context_the_defaults_apply() => redb.Route.Extensions.RouteContextExtensions.GetStreamCacheOptions(null).SpoolThreshold .Should().Be(StreamCache.DefaultSpoolThreshold); } Path: redb-route/tests/redb.Route.Tests/Core/StreamCacheTests.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/StreamCacheTests.cs ---- using redb.Route.Core; using AwesomeAssertions; namespace redb.Route.Tests.Core; public class StreamCacheTests { [Fact] public async Task SmallStream_CachesInMemory_SeekableAndRereadable() { var data = "hello world"u8.ToArray(); var source = new MemoryStream(data); var cache = new StreamCache(spoolThreshold: 1024); await cache.CacheFromSourceAsync(source).ConfigureAwait(false); cache.CanSeek.Should().BeTrue(); cache.CanRead.Should().BeTrue(); cache.Length.Should().Be(data.Length); cache.Position.Should().Be(0); // First read using var reader1 = new StreamReader(cache, leaveOpen: true); var text1 = await reader1.ReadToEndAsync().ConfigureAwait(false); text1.Should().Be("hello world"); // Rewind and re-read cache.Position = 0; using var reader2 = new StreamReader(cache, leaveOpen: true); var text2 = await reader2.ReadToEndAsync().ConfigureAwait(false); text2.Should().Be("hello world"); } [Fact] public async Task LargeStream_SpoolsToDisk_StillSeekable() { // Create data that exceeds the spool threshold var data = new byte[256]; Random.Shared.NextBytes(data); var source = new MemoryStream(data); var cache = new StreamCache(spoolThreshold: 64); // Low threshold to trigger spool await cache.CacheFromSourceAsync(source).ConfigureAwait(false); cache.CanSeek.Should().BeTrue(); cache.Length.Should().Be(256); cache.Position.Should().Be(0); // Read all var result = new byte[256]; var totalRead = 0; int bytesRead; while ((bytesRead = await cache.ReadAsync(result.AsMemory(totalRead)).ConfigureAwait(false)) > 0) totalRead += bytesRead; totalRead.Should().Be(256); result.Should().Equal(data); // Rewind and verify cache.Position = 0; totalRead = 0; while ((bytesRead = await cache.ReadAsync(result.AsMemory(totalRead)).ConfigureAwait(false)) > 0) totalRead += bytesRead; result.Should().Equal(data); } [Fact] public async Task Dispose_CleansUpResources() { var data = new byte[256]; Random.Shared.NextBytes(data); var source = new MemoryStream(data); var cache = new StreamCache(spoolThreshold: 64); await cache.CacheFromSourceAsync(source).ConfigureAwait(false); await cache.DisposeAsync().ConfigureAwait(false); cache.CanRead.Should().BeFalse(); cache.CanSeek.Should().BeFalse(); } [Fact] public async Task EmptySource_CreatesEmptyCache() { var source = new MemoryStream(); var cache = new StreamCache(); await cache.CacheFromSourceAsync(source).ConfigureAwait(false); cache.Length.Should().Be(0); cache.Position.Should().Be(0); var buffer = new byte[10]; var read = await cache.ReadAsync(buffer).ConfigureAwait(false); read.Should().Be(0); } [Fact] public async Task Write_ThrowsNotSupported() { var cache = new StreamCache(); await cache.CacheFromSourceAsync(new MemoryStream()).ConfigureAwait(false); var act = () => cache.Write(new byte[1], 0, 1); act.Should().Throw(); } [Fact] public async Task SetLength_ThrowsNotSupported() { var cache = new StreamCache(); await cache.CacheFromSourceAsync(new MemoryStream()).ConfigureAwait(false); var act = () => cache.SetLength(100); act.Should().Throw(); } [Fact] public async Task Seek_WorksCorrectly() { var data = "abcdefghij"u8.ToArray(); var source = new MemoryStream(data); var cache = new StreamCache(); await cache.CacheFromSourceAsync(source).ConfigureAwait(false); cache.Seek(5, SeekOrigin.Begin); cache.Position.Should().Be(5); var buffer = new byte[5]; var read = cache.Read(buffer, 0, 5); read.Should().Be(5); buffer.Should().Equal("fghij"u8.ToArray()); } } Path: redb-route/tests/redb.Route.Tests/Core/TypedReadConversionTests.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/TypedReadConversionTests.cs ---- using AwesomeAssertions; using redb.Route.Core; namespace redb.Route.Tests.Core; /// /// A typed read of a header, a property or a received body converts as Camel does: a missing value, or one with no /// conversion to the type at all, reads as default; a value the conversion exists for but cannot parse ("abc" as an /// int) is an error naming the key and the type, never its value. It used to read as default too, so a typo in the /// data sent the route down its "no value" branch without a word. A nullable target converts like its underlying type. /// public class TypedReadConversionTests { private sealed class Customer; private static Message Headers(params (string Key, object? Value)[] headers) { var message = new Message("body"); foreach (var (key, value) in headers) message.Headers[key] = value; return message; } [Fact] public void A_header_that_cannot_be_parsed_as_the_type_is_an_error_naming_it() { var message = Headers(("count", "abc")); var act = () => message.GetHeader("count"); act.Should().Throw() .WithMessage("*'count'*Int32*") .Which.Message.Should().NotContain("abc"); } [Fact] public void A_missing_header_reads_as_default() => Headers().GetHeader("count").Should().Be(0); [Fact] public void A_header_with_no_conversion_to_the_type_reads_as_default() => Headers(("customer", "acme")).GetHeader("customer").Should().BeNull(); [Fact] public void A_nullable_target_converts_like_its_underlying_type() => Headers(("count", "5")).GetHeader("count").Should().Be(5); [Fact] public void Numbers_are_read_in_the_invariant_culture() => Headers(("price", "1.5")).GetHeader("price").Should().Be(1.5m); [Fact] public void A_property_follows_the_same_rule() { var exchange = new Exchange(new Message("body")); exchange.Properties["retries"] = "many"; var act = () => exchange.GetProperty("retries"); act.Should().Throw().WithMessage("*'retries'*"); exchange.GetProperty("missing").Should().Be(0); } } Path: redb-route/tests/redb.Route.Tests/Core/UriLogFormTests.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/UriLogFormTests.cs ---- using AwesomeAssertions; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Tests.Cluster; using Xunit.Abstractions; namespace redb.Route.Tests.Core; /// /// The short log form of a long endpoint URI (): a SQL statement or a long query string /// no longer fills the "Compiled route" and "Endpoint started" lines, the form still tells endpoints apart, never shows /// part of a masked secret, and the whole masked URI is on the same line when Debug is on. /// public class UriLogFormTests(ITestOutputHelper output) { private const string LongSql = "sql:SELECT o.id, o.number, o.created_at, c.name, c.email, SUM(l.amount) AS total FROM orders o " + "JOIN customers c ON c.id = o.customer_id JOIN order_lines l ON l.order_id = o.id " + "WHERE o.status = :#status AND o.created_at > :#since GROUP BY o.id, o.number, o.created_at, c.name, c.email" + "?dataSource=main&outputType=SelectList&useIterator=true"; private const string LongHttp = "https://api.partner.example/v2/orders/export?format=csv&fields=id,number,customer,total,status,created,updated" + "&since=2026-01-01&until=2026-12-31&page_size=500&apiKey=k-123456789&inboundAuth=basic&inboundPassword=s3cret"; private const string As4 = "as4://0.0.0.0:8443/as4?connectionFactory=node&partner=acme&timeout=15000"; [Fact] public void ShortUri_IsLoggedWhole() { EndpointUri.ForLog(As4).Should().Be(As4); EndpointUri.ForLog("kafka://orders?brokers=localhost:9092&password=x").Should().Be("kafka://orders?brokers=localhost:9092&password=****"); } [Fact] public void LongSql_IsCutAtAParameterBoundaryOrTheLength_WithWhatIsLeftAndAHash() { var form = EndpointUri.ForLog(LongSql); form.Should().MatchRegex(@"^sql:SELECT o\.id, .*\.\.\. \[\+\d+ chars #[0-9a-f]{8}\]$"); form.Length.Should().BeLessThan(EndpointUri.LogLength + 30); var shown = form[..form.IndexOf("... [", StringComparison.Ordinal)]; var left = int.Parse(form[(form.IndexOf("[+", StringComparison.Ordinal) + 2)..form.IndexOf(" chars", StringComparison.Ordinal)]); (shown.Length + left).Should().Be(LongSql.Length); } [Fact] public void LongQueryString_IsCutBeforeAParameter_AndKeepsSecretsMasked() { var form = EndpointUri.ForLog(LongHttp); form.Should().NotContain("s3cret").And.NotContain("k-123456789"); var shown = form[..form.IndexOf("... [", StringComparison.Ordinal)]; EndpointUri.Sanitize(LongHttp).Should().StartWith(shown); "?&".Should().Contain(EndpointUri.Sanitize(LongHttp)[shown.Length].ToString(), "the cut falls before a parameter"); } [Fact] public void ACutThatWouldFallInsideAMask_KeepsTheMaskWhole() { // "x://h?" then a long secret parameter name: the only boundary is the '?' at 5 (below half the length), so the // cut falls at the length, which is inside the mask that starts at 7 + 111 = 118. var key = new string('p', 103) + "password"; var uri = $"x://h?{key}=secretvalue&more=1"; var full = EndpointUri.Sanitize(uri); var maskAt = full.IndexOf(EndpointUri.Redacted, StringComparison.Ordinal); maskAt.Should().BeLessThan(EndpointUri.LogLength); (maskAt + EndpointUri.Redacted.Length).Should().BeGreaterThan(EndpointUri.LogLength, "the plain cut would fall inside the mask"); var form = EndpointUri.ForLog(uri); form.Should().StartWith(full[..(maskAt + EndpointUri.Redacted.Length)] + "... [", "the mask is kept whole"); form.Should().NotContain("secretvalue"); } [Fact] public void TwoLongUrisWithTheSamePrefix_ReadApart() { var a = EndpointUri.ForLog(LongSql); var b = EndpointUri.ForLog(LongSql.Replace("useIterator=true", "useIterator=false")); a.Should().NotBe(b); a[..a.IndexOf("... [", StringComparison.Ordinal)].Should().Be(b[..b.IndexOf("... [", StringComparison.Ordinal)], "they differ only after the cut"); a[(a.IndexOf('#') + 1)..].Should().NotBe(b[(b.IndexOf('#') + 1)..], "the hash of the whole URI tells them apart"); } [Fact] public void BeforeAndAfter_ForTheReport() { foreach (var uri in new[] { LongSql, LongHttp, As4 }) { output.WriteLine("before: " + EndpointUri.Sanitize(uri)); output.WriteLine("after: " + EndpointUri.ForLog(uri)); output.WriteLine(""); } } [Theory] [InlineData(LogLevel.Information, false)] [InlineData(LogLevel.Debug, true)] public async Task CompiledRouteAndEndpointStartedLines_AreShort_AndWholeAtDebug(LogLevel level, bool whole) { var capture = new CapturingLoggerProvider(); using var loggerFactory = LoggerFactory.Create(b => b.AddProvider(capture).SetMinimumLevel(level)); var longDirect = "direct://" + new string('q', 200) + "?timeout=5000"; await using var context = new RouteContext(loggerFactory: loggerFactory); context.AddRoutes(r => r.From(longDirect).RouteId("long-route").To("mock:out")); await context.Start(); var lines = capture.Entries.Where(e => e.Level == LogLevel.Information && (e.Message.StartsWith("Compiled route 'long-route'", StringComparison.Ordinal) || e.Message.StartsWith("Endpoint direct://", StringComparison.Ordinal))) .Select(e => e.Message).ToList(); lines.Should().HaveCountGreaterThanOrEqualTo(2); foreach (var line in lines) { if (whole) line.Should().Contain(longDirect).And.NotContain("chars #"); else line.Should().NotContain(longDirect).And.MatchRegex(@"\.\.\. \[\+\d+ chars #[0-9a-f]{8}\]"); } } [Theory] [InlineData(LogLevel.Information, false)] [InlineData(LogLevel.Debug, true)] public async Task ConnectorStartAndStopLines_AreShort_AndWholeAtDebug(LogLevel level, bool whole) { var capture = new CapturingLoggerProvider(); using var loggerFactory = LoggerFactory.Create(b => b.AddProvider(capture).SetMinimumLevel(level)); var longDirect = "direct://" + new string('d', 200); var longSeda = "seda://" + new string('s', 200); await using (var context = new RouteContext(loggerFactory: loggerFactory)) { context.AddRoutes(r => { r.From(longDirect).RouteId("to-seda").To(longSeda); r.From(longSeda).RouteId("from-seda").To("mock:out"); }); await context.Start(); await context.Stop(); } // The Direct consumer (its own lines) and the SEDA consumer (the shared DrainableConsumer line), each started and // stopped. var lines = capture.Entries.Where(e => e.Level == LogLevel.Information && (e.Message.Contains("dddd", StringComparison.Ordinal) || e.Message.Contains("ssss", StringComparison.Ordinal)) && (e.Message.Contains(" started", StringComparison.Ordinal) || e.Message.Contains(" stopped", StringComparison.Ordinal))) .Select(e => e.Message).ToList(); lines.Should().Contain(l => l.StartsWith("Direct consumer started: ", StringComparison.Ordinal)); lines.Should().Contain(l => l.StartsWith("seda://", StringComparison.Ordinal) && l.EndsWith(" started.", StringComparison.Ordinal)); foreach (var line in lines) { if (whole) line.Should().Match(l => l.Contains(longDirect) || l.Contains(longSeda)).And.NotContain("chars #"); else line.Should().NotContain(longDirect).And.NotContain(longSeda).And.MatchRegex(@"\.\.\. \[\+\d+ chars #[0-9a-f]{8}\]"); } } } Path: redb-route/tests/redb.Route.Tests/Core/UriMaskReviewTests.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/UriMaskReviewTests.cs ---- using redb.Route.Core; namespace redb.Route.Tests.Core; /// /// Code review 2026-09-01 (the UriMask query item): a mask without a query string ignores the /// candidate's query; a mask that carries one matches only that query. Before, both sides were /// query-stripped, so kafka://orders?acks=all matched ?acks=none too. /// public class UriMaskReviewTests { [Theory] [InlineData("kafka://orders", "kafka://orders?acks=all", true)] [InlineData("kafka://orders?acks=all", "kafka://orders?acks=all", true)] [InlineData("kafka://orders?acks=all", "kafka://orders?acks=none", false)] [InlineData("kafka://orders?acks=all", "kafka://orders", false)] [InlineData("kafka:orders?acks=all", "kafka://orders?acks=all", true)] public void ExactMask_QueryIsSignificantOnlyWhenTheMaskCarriesOne(string pattern, string uri, bool expected) => UriMask.IsMatch(pattern, uri).Should().Be(expected); [Theory] [InlineData("kafka://orders?acks=*", "kafka://orders?acks=all", true)] [InlineData("kafka://orders?acks=*", "kafka://orders?retries=3", false)] [InlineData("kafka://*", "kafka://orders?acks=all", true)] [InlineData("kafka:orders*", "kafka://orders-vip", true)] public void PrefixMask_QueryIsSignificantOnlyWhenTheMaskCarriesOne(string pattern, string uri, bool expected) => UriMask.IsMatch(pattern, uri).Should().Be(expected); [Theory] [InlineData("regex:^kafka:orders$", "kafka://orders?acks=all", true)] [InlineData("regex:ORDERS", "kafka://orders", true)] public void RegexMask_MatchesTheKnownSpellings(string pattern, string uri, bool expected) => UriMask.IsMatch(pattern, uri).Should().Be(expected); } Path: redb-route/tests/redb.Route.Tests/Core/UriMaskValidateTests.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/UriMaskValidateTests.cs ---- using redb.Route.Core; namespace redb.Route.Tests.Core; /// Code review 2026-09-01: a mask is validated where it is declared, so an invalid regex names itself instead of dropping a route at compile. public class UriMaskValidateTests { [Fact] public void InvalidRegex_IsReportedAsSuch() { var act = () => UriMask.Validate("regex:[", "mask"); act.Should().Throw().WithMessage("*regular expression*").And.ParamName.Should().Be("mask"); } [Theory] [InlineData("")] [InlineData(" ")] [InlineData(null)] public void BlankMask_IsRefused(string? pattern) { var act = () => UriMask.Validate(pattern); act.Should().Throw(); } [Theory] [InlineData("kafka://*")] [InlineData("regex:^kafka:.*$")] [InlineData("X-Internal-*")] public void UsableMasks_Pass(string pattern) { var act = () => UriMask.Validate(pattern); act.Should().NotThrow(); } } Path: redb-route/tests/redb.Route.Tests/Core/UriParserTests.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/UriParserTests.cs ---- using redb.Route.Core; using AwesomeAssertions; namespace redb.Route.Tests.Core; public class UriParserTests { [Theory] [InlineData("kafka://orders", "kafka", "orders", "kafka://orders")] [InlineData("rabbitmq://exchange/queue", "rabbitmq", "exchange/queue", "rabbitmq://exchange/queue")] [InlineData("direct://start", "direct", "start", "direct://start")] [InlineData("seda://buffer", "seda", "buffer", "seda://buffer")] [InlineData("timer://heartbeat", "timer", "heartbeat", "timer://heartbeat")] public void Parse_StandardFormat_ExtractsComponents(string uri, string scheme, string path, string key) { var result = EndpointUriParser.Parse(uri); result.Scheme.Should().Be(scheme); result.Path.Should().Be(path); result.NormalizedKey.Should().Be(key); } [Theory] [InlineData("redis:GET:user:123", "redis", "GET:user:123", "redis://GET:user:123")] [InlineData("redis:SET:cache:key", "redis", "SET:cache:key", "redis://SET:cache:key")] public void Parse_ColonFormat_ExtractsComponents(string uri, string scheme, string path, string key) { var result = EndpointUriParser.Parse(uri); result.Scheme.Should().Be(scheme); result.Path.Should().Be(path); result.NormalizedKey.Should().Be(key); } [Fact] public void Parse_WithQueryParams_ExtractsParameters() { var result = EndpointUriParser.Parse("kafka://orders?brokers=localhost:9092&groupId=my-group"); result.Scheme.Should().Be("kafka"); result.Path.Should().Be("orders"); result.NormalizedKey.Should().Be("kafka://orders?brokers=localhost:9092&groupId=my-group"); result.RawParameters.Should().HaveCount(2); result.RawParameters["brokers"].Should().Be("localhost:9092"); result.RawParameters["groupId"].Should().Be("my-group"); } [Fact] public void Parse_ColonWithParams_Works() { var result = EndpointUriParser.Parse("redis:GET:user:123?ttl=60"); result.Scheme.Should().Be("redis"); result.Path.Should().Be("GET:user:123"); result.RawParameters["ttl"].Should().Be("60"); } [Fact] public void Parse_NoParams_EmptyDictionary() { var result = EndpointUriParser.Parse("direct://start"); result.RawParameters.Should().BeEmpty(); } [Fact] public void Parse_SchemeIsCaseInsensitive() { var result = EndpointUriParser.Parse("KAFKA://orders"); result.Scheme.Should().Be("kafka"); } [Fact] public void Parse_ParametersAreCaseInsensitive() { var result = EndpointUriParser.Parse("kafka://t?BrokERS=host"); result.RawParameters["brokers"].Should().Be("host"); } [Theory] [InlineData("")] [InlineData(" ")] [InlineData(null)] public void Parse_EmptyOrNull_Throws(string? uri) { var act = () => EndpointUriParser.Parse(uri!); act.Should().Throw(); } [Fact] public void Parse_NoScheme_Throws() { var act = () => EndpointUriParser.Parse("orders"); act.Should().Throw(); } /// Flag parameters (no =value) should have empty string as value. [Fact] public void Parse_FlagParameter_EmptyValue() { var result = EndpointUriParser.Parse("rabbitmq://orders?transacted"); result.RawParameters["transacted"].Should().Be(string.Empty); } /// Dynamic expressions like ${header.tripId} must be preserved as-is in parameters. [Fact] public void Parse_DynamicExpression_PreservedInParams() { var result = EndpointUriParser.Parse("kafka://orders?key=${header.tripId}"); result.RawParameters["key"].Should().Be("${header.tripId}"); } } Path: redb-route/tests/redb.Route.Tests/Core/UriSanitizationTests.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/UriSanitizationTests.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using AwesomeAssertions; namespace redb.Route.Tests.Core; /// /// Security regression tests: no secret (password / token / key / userinfo password) /// may survive the logging / telemetry / DTO boundary. Guards against the class of /// leak where connector credentials in the endpoint URI reach logs and dashboards. /// public class UriSanitizationTests { // --- EndpointUri.Sanitize — format-preserving redaction ---------------- [Theory] // scheme separator (:// vs :) and non-secret params preserved byte-for-byte [InlineData("direct://props", "direct://props")] [InlineData("kafka://orders?brokers=localhost:9092&groupId=g", "kafka://orders?brokers=localhost:9092&groupId=g")] [InlineData("redis:GET:user:123?ttl=60", "redis:GET:user:123?ttl=60")] public void Sanitize_NoSecrets_ReturnsUnchanged(string uri, string expected) { EndpointUri.Sanitize(uri).Should().Be(expected); } [Theory] [InlineData("kafka://orders?password=s3cret", "kafka://orders?password=****")] [InlineData("ldap://host?bindPassword=p%40ss&host=x", "ldap://host?bindPassword=****&host=x")] [InlineData("sqs://q?accessKey=AKIA123&sessionToken=FQoGtemp®ion=eu", "sqs://q?accessKey=****&sessionToken=****®ion=eu")] [InlineData("kafka://t?saslPassword=x&sslKeyPassword=y&brokers=b", "kafka://t?saslPassword=****&sslKeyPassword=****&brokers=b")] [InlineData("http://api/x?authToken=bearerXYZ", "http://api/x?authToken=****")] [InlineData("sb://ns?connectionString=Endpoint%3Dsb%3B%3BSharedAccessKey%3Dabc", "sb://ns?connectionString=****")] public void Sanitize_QuerySecrets_AreFullyRedacted(string uri, string expected) { EndpointUri.Sanitize(uri).Should().Be(expected); } [Theory] [InlineData("ldap://cn=admin:s3cr3t@ldap.example.com:389/dc=x", "ldap://cn=admin:****@ldap.example.com:389/dc=x")] [InlineData("redis://:p4ss@cache:6379", "redis://:****@cache:6379")] [InlineData("amqp://user:pw@broker:5672/vhost", "amqp://user:****@broker:5672/vhost")] public void Sanitize_UserInfoPassword_IsRedacted(string uri, string expected) { EndpointUri.Sanitize(uri).Should().Be(expected); } [Theory] // host:port and an '@' inside the path (not userinfo) must NOT be touched [InlineData("http://host:8080/path")] [InlineData("http://host:8080/a@b")] [InlineData("rabbitmq://ex/q?routingKey=orders.new&partitionKey=7&clientId=abc&username=admin")] public void Sanitize_BenignParams_AreNotOverMasked(string uri) { EndpointUri.Sanitize(uri).Should().Be(uri); EndpointUri.Sanitize(uri).Should().NotContain("****"); } [Theory] [InlineData("")] [InlineData(null)] public void Sanitize_EmptyOrNull_DoesNotThrow(string? uri) { EndpointUri.Sanitize(uri).Should().Be(string.Empty); } [Fact] public void Sanitize_NeverLeaksTheSecretValue() { const string secret = "SUPERSECRET_pw_9000"; var sanitized = EndpointUri.Sanitize( $"amqp://svc:{secret}@broker:5672/v?password={secret}&sslKeyPassword={secret}"); sanitized.Should().NotContain(secret); sanitized.Should().Contain("****"); } // --- EndpointUri.ToMaskedUriString — used by connector {Uri} logs ------ [Fact] public void ToMaskedUriString_FullyRedacts_NoPartialFirstTwoChars() { var uri = EndpointUriParser.Parse("rabbitmq://q?password=abcdef123"); var masked = uri.ToMaskedUriString(); masked.Should().Contain("password=****"); masked.Should().NotContain("ab****"); // no first-2-char disclosure masked.Should().NotContain("abcdef123"); } [Fact] public void ToMaskedUriString_MasksBindPassword_TheLdapLeak() { var uri = EndpointUriParser.Parse("ldap://host:389?bindDn=cn=admin&bindPassword=svcP4ss"); var masked = uri.ToMaskedUriString(); masked.Should().NotContain("svcP4ss"); masked.Should().Contain("****"); } [Fact] public void ToMaskedUriString_MasksUserInfoPassword() { var uri = EndpointUriParser.Parse("ldap://cn=admin:s3cr3t@host:389/dc=x"); var masked = uri.ToMaskedUriString(); masked.Should().NotContain("s3cr3t"); masked.Should().Contain("****"); } // --- RedactSecrets — free-text / connection-string / exception messages --- [Theory] [InlineData("Server=db;Password=p4ss;Database=x", "Server=db;Password=****;Database=x")] [InlineData("Server=db;Pwd=p4ss;", "Server=db;Pwd=****;")] [InlineData("Endpoint=sb://ns;SharedAccessKey=abc123", "Endpoint=sb://ns;SharedAccessKey=****")] [InlineData("Login failed for host=db user=admin", "Login failed for host=db user=admin")] [InlineData("no assignments here", "no assignments here")] public void RedactSecrets_MasksOnlySensitiveAssignments(string input, string expected) { EndpointUri.RedactSecrets(input).Should().Be(expected); } [Theory] [InlineData("None of the endpoints were reachable: amqp://svc:Sup3rS3cret@broker:5672/vhost", "None of the endpoints were reachable: amqp://svc:****@broker:5672/vhost")] [InlineData("connect to 'redis://default:pw@cache:6379' failed", "connect to 'redis://default:****@cache:6379' failed")] [InlineData("a://u:p@h1 then b://v:q@h2?password=x", "a://u:****@h1 then b://v:****@h2?password=****")] [InlineData("ftp://anonymous@host/dir", "ftp://anonymous@host/dir")] [InlineData("see https://example.com/a?b=c", "see https://example.com/a?b=c")] [InlineData("Endpoint=amqps://u:p@ns;SharedAccessKey=k", "Endpoint=amqps://u:****@ns;SharedAccessKey=****")] public void RedactSecrets_MasksThePasswordOfAQuotedUri(string input, string expected) { EndpointUri.RedactSecrets(input).Should().Be(expected); } [Fact] public void RedactSecrets_KeepsNonSecretKeysAndSurroundingText() { var redacted = EndpointUri.RedactSecrets( "A network error occurred: Server=tcp:db,1433;User ID=svc;Password=Sup3rS3cret;Encrypt=True"); redacted.Should().NotContain("Sup3rS3cret"); redacted.Should().Contain("Server=tcp:db,1433"); redacted.Should().Contain("User ID=svc"); redacted.Should().Contain("Encrypt=True"); redacted.Should().Contain("Password=****"); } [Theory] [InlineData("")] [InlineData(null)] public void RedactSecrets_EmptyOrNull_DoesNotThrow(string? text) { EndpointUri.RedactSecrets(text).Should().Be(string.Empty); } // --- IsSensitiveKey ---------------------------------------------------- [Theory] [InlineData("password")] [InlineData("bindPassword")] [InlineData("sslKeyPassword")] [InlineData("proxyPassword")] [InlineData("clientCertPassword")] [InlineData("passphrase")] [InlineData("privateKeyPassphrase")] [InlineData("secret")] [InlineData("clientSecret")] [InlineData("sessionToken")] [InlineData("authToken")] [InlineData("apiKey")] [InlineData("accessKey")] [InlineData("sharedAccessKey")] [InlineData("connectionString")] [InlineData("credentialPath")] [InlineData("saslJaasConfig")] public void IsSensitiveKey_KnownSecretNames_ReturnTrue(string key) { EndpointUri.IsSensitiveKey(key).Should().BeTrue(); } [Theory] [InlineData("host")] [InlineData("port")] [InlineData("username")] // Camel keeps username visible [InlineData("routingKey")] // must not trip bare "key" [InlineData("partitionKey")] [InlineData("clientId")] [InlineData("groupId")] [InlineData("brokers")] [InlineData("topic")] [InlineData("concurrentConsumers")] public void IsSensitiveKey_BenignNames_ReturnFalse(string key) { EndpointUri.IsSensitiveKey(key).Should().BeFalse(); } [Fact] public void AddSensitiveKeys_RegistersCustomName() { EndpointUri.IsSensitiveKey("zzzConnectorPrivateHandle").Should().BeFalse(); EndpointUri.AddSensitiveKeys("zzzConnectorPrivateHandle"); EndpointUri.IsSensitiveKey("zzzConnectorPrivateHandle").Should().BeTrue(); EndpointUri.Sanitize("x://y?zzzConnectorPrivateHandle=topsecret") .Should().Be("x://y?zzzConnectorPrivateHandle=****"); } // --- [Sensitive] declaration drives masking --------------------------- /// /// Options type whose credential is named so that the name-keyword heuristic can NOT catch it — /// only the declaration can. Mirrors the real-world case that /// caused the original leak (bindPassword was a secret nobody had put on the list). /// private sealed class DeclaredSecretOptions : EndpointOptions { public string? Wibble { get; set; } [Sensitive] public string? Wobble { get; set; } public override void Validate() { } } [Fact] public void SensitiveAttribute_IsHarvestedOnBind_AndDrivesMasking() { // "wobble" matches none of the built-in keywords — before binding it is not sensitive. EndpointUri.IsSensitiveKey("wobble").Should().BeFalse(); var uri = EndpointUriParser.Parse("demo://x?wibble=visible&wobble=T0PSECRET"); new DeclaredSecretOptions().BindFromUri(uri.RawParameters); // Binding the options type harvested its [Sensitive] declarations. EndpointUri.IsSensitiveKey("wobble").Should().BeTrue(); var sanitized = EndpointUri.Sanitize("demo://x?wibble=visible&wobble=T0PSECRET"); sanitized.Should().Be("demo://x?wibble=visible&wobble=****"); sanitized.Should().NotContain("T0PSECRET"); } // --- Safety invariant: routing keys stay RAW -------------------------- [Fact] public void NormalizedKey_KeepsRawValues_ForRoutingIdentity() { // Masking is display-only. The dictionary/cache key that drives routing // must remain byte-identical to the raw URI, or endpoints stop matching. var parsed = EndpointUriParser.Parse("kafka://orders?password=raw_secret&groupId=g"); parsed.NormalizedKey.Should().Contain("raw_secret"); parsed.RawParameters["password"].Should().Be("raw_secret"); } } Path: redb-route/tests/redb.Route.Tests/Definitions/ChoiceDefinitionTests.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/Definitions/ChoiceDefinitionTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Definitions; using redb.Route.Processors; namespace redb.Route.Tests.Definitions; /// /// Tests for W5 F5 — ChoiceDefinition / WhenDefinition / OtherwiseDefinition. /// public class ChoiceDefinitionTests : IAsyncLifetime { private readonly RouteContext _context = new(); public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { await _context.DisposeAsync(); GC.SuppressFinalize(this); } private static Exchange MakeExchange(object? body = null) => new Exchange(new Message { Body = body }); // ── Structure ───────────────────────────────────────────────────────────── [Fact] public void Choice_ReturnsChoiceDefinition() { var route = new RouteDefinition(); route.Choice().Should().BeOfType(); } [Fact] public void Choice_IsAddedToRouteOutputs() { var route = new RouteDefinition(); route.Choice(); route.Outputs.Should().HaveCount(1); route.Outputs[0].Should().BeOfType(); } [Fact] public void Choice_SetsParent() { var route = new RouteDefinition(); var choice = route.Choice(); choice.Parent.Should().BeSameAs(route); } [Fact] public void When_ReturnsWhenDefinition() { var choice = new RouteDefinition().Choice(); choice.When(_ => true).Should().BeOfType(); } [Fact] public void Otherwise_ReturnsOtherwiseDefinition() { var choice = new RouteDefinition().Choice(); choice.Otherwise().Should().BeOfType(); } [Fact] public void Otherwise_CalledTwice_Throws() { var choice = new RouteDefinition().Choice(); choice.Otherwise(); choice.Invoking(c => c.Otherwise()).Should().Throw(); } [Fact] public void EndChoice_ReturnsParentRoute() { var route = new RouteDefinition(); var back = route.Choice().EndChoice(); back.Should().BeSameAs(route); } [Fact] public void WhenDefinition_EndWhen_ReturnsChoiceDefinition() { var choice = new RouteDefinition().Choice(); var when = choice.When(_ => true); when.EndWhen().Should().BeSameAs(choice); } [Fact] public void WhenDefinition_EndChoice_ReturnsParentRoute() { var route = new RouteDefinition(); var when = route.Choice().When(_ => true); when.EndChoice().Should().BeSameAs(route); } [Fact] public void WhenDefinition_When_AddsBranchToChoice() { var route = new RouteDefinition(); var choice = route.Choice(); var when1 = choice.When(_ => true); var when2 = when1.When(_ => false); when2.Should().BeOfType(); when2.Should().NotBeSameAs(when1); } [Fact] public void OtherwiseDefinition_EndOtherwise_ReturnsChoice() { var choice = new RouteDefinition().Choice(); var otherwise = choice.Otherwise(); otherwise.EndOtherwise().Should().BeSameAs(choice); } [Fact] public void OtherwiseDefinition_EndChoice_ReturnsParentRoute() { var route = new RouteDefinition(); var otherwise = route.Choice().Otherwise(); otherwise.EndChoice().Should().BeSameAs(route); } // ── CreateProcessor ─────────────────────────────────────────────────────── [Fact] public void ChoiceDefinition_CreateProcessor_ReturnsChoiceProcessor() { var choice = new RouteDefinition().Choice(); choice.When(_ => true).Process(_ => { }); choice.CreateProcessor(_context).Should().BeOfType(); } // ── Execution: routing ──────────────────────────────────────────────────── [Fact] public async Task Choice_FirstMatchingWhen_Executes() { var log = new List(); var route = new RouteDefinition() .Choice() .When(e => e.In.Body is "A") .Process(_ => { log.Add("branch-A"); }) .When(e => e.In.Body is "B") .Process(_ => { log.Add("branch-B"); }) .EndChoice(); var processor = ((RouteDefinition)route).CreateProcessor(_context); await processor.Process(MakeExchange("A")); await processor.Process(MakeExchange("B")); log.Should().Equal("branch-A", "branch-B"); } [Fact] public async Task Choice_NoMatch_ExecutesOtherwise() { var log = new List(); var route = new RouteDefinition() .Choice() .When(e => e.In.Body is "A") .Process(_ => { log.Add("branch-A"); }) .Otherwise() .Process(_ => { log.Add("otherwise"); }) .EndChoice(); var processor = ((RouteDefinition)route).CreateProcessor(_context); await processor.Process(MakeExchange("Z")); log.Should().Equal("otherwise"); } [Fact] public async Task Choice_NoMatch_NoOtherwise_DoesNothing() { bool reached = false; var route = new RouteDefinition() .Choice() .When(e => e.In.Body is "A") .Process(_ => { reached = true; }) .EndChoice(); var processor = ((RouteDefinition)route).CreateProcessor(_context); await processor.Process(MakeExchange("Z")); reached.Should().BeFalse(); } [Fact] public async Task Choice_OnlyFirstMatchingWhen_Executes() { var log = new List(); var route = new RouteDefinition() .Choice() .When(_ => true) .Process(_ => { log.Add("first"); }) .When(_ => true) .Process(_ => { log.Add("second"); }) .EndChoice(); var processor = ((RouteDefinition)route).CreateProcessor(_context); await processor.Process(MakeExchange()); log.Should().Equal("first"); } [Fact] public async Task StepsAfterEndChoice_ExecuteRegardlessOfBranch() { var log = new List(); var route = new RouteDefinition() .Choice() .When(e => e.In.Body is "A") .Process(_ => { log.Add("inside"); }) .EndChoice() .Process(_ => { log.Add("after"); }); var processor = ((RouteDefinition)route).CreateProcessor(_context); await processor.Process(MakeExchange("Z")); log.Should().Equal("after"); } [Fact] public async Task When_MultipleSteps_AllExecute() { var log = new List(); var route = new RouteDefinition() .Choice() .When(_ => true) .Process(_ => { log.Add("step1"); }) .Process(_ => { log.Add("step2"); }) .EndChoice(); var processor = ((RouteDefinition)route).CreateProcessor(_context); await processor.Process(MakeExchange()); log.Should().Equal("step1", "step2"); } } Path: redb-route/tests/redb.Route.Tests/Definitions/ContentTypeDeserializationTests.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/Definitions/ContentTypeDeserializationTests.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Extensions; using redb.Route.Serialization; namespace redb.Route.Tests.Definitions; /// /// Integration tests for ContentType-based deserialization via /// Unmarshal<T>() and OfType<T>() auto-conversion. /// public class ContentTypeDeserializationTests : IAsyncLifetime { private readonly RouteContext _context = new(); private readonly JsonMessageSerializer _json = new(); public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { await _context.DisposeAsync(); GC.SuppressFinalize(this); } [Fact] public async Task UnmarshalGeneric_DeserializesByContentType() { IExchange? received = null; var bytes = _json.Serialize(new OrderDto("ORD-1", 99m)); _context.AddRoutes(r => { r.From("direct://unmarshal-auto-in") .Unmarshal() .Process(ex => received = ex); }); await _context.Start(); var producer = _context.GetEndpoint("direct://unmarshal-auto-in").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message { Body = bytes, ContentType = "application/json" })); received.Should().NotBeNull(); var order = received!.In.Body.Should().BeOfType().Subject; order.Id.Should().Be("ORD-1"); order.Amount.Should().Be(99m); } [Fact] public async Task UnmarshalGeneric_FromString_DeserializesByContentType() { IExchange? received = null; _context.AddRoutes(r => { r.From("direct://unmarshal-str-in") .Unmarshal() .Process(ex => received = ex); }); await _context.Start(); var producer = _context.GetEndpoint("direct://unmarshal-str-in").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message { Body = """{"id":"ORD-2","amount":50}""", ContentType = "application/json" })); received.Should().NotBeNull(); var order = received!.In.Body.Should().BeOfType().Subject; order.Id.Should().Be("ORD-2"); } [Fact] public async Task OfType_AutoConvertsJsonBody() { OrderDto? received = null; _context.AddRoutes(r => { r.From("direct://oftype-json-in") .OfType() .Process(order => { received = order; }); }); await _context.Start(); var producer = _context.GetEndpoint("direct://oftype-json-in").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message { Body = """{"id":"ORD-3","amount":200}""", ContentType = "application/json" })); received.Should().NotBeNull(); received!.Id.Should().Be("ORD-3"); received.Amount.Should().Be(200m); } [Fact] public async Task OfType_ExistingBody_PassesThrough() { OrderDto? received = null; var original = new OrderDto("ORD-4", 10m); _context.AddRoutes(r => { r.From("direct://oftype-passthrough") .OfType() .Process(order => received = order); }); await _context.Start(); var producer = _context.GetEndpoint("direct://oftype-passthrough").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message { Body = original })); received.Should().BeSameAs(original); } [Fact] public async Task OfType_WithFilter_FiltersDeserialized() { var received = new List(); _context.AddRoutes(r => { r.From("direct://oftype-filter-in") .OfType() .Filter(o => o.Amount > 100) .Process(order => received.Add(order.Id)); }); await _context.Start(); var producer = _context.GetEndpoint("direct://oftype-filter-in").CreateProducer(); await producer.Start(); // passes filter await producer.Process(new Exchange(new Message { Body = """{"id":"BIG","amount":500}""", ContentType = "application/json" })); // filtered out await producer.Process(new Exchange(new Message { Body = """{"id":"SMALL","amount":10}""", ContentType = "application/json" })); received.Should().ContainSingle().Which.Should().Be("BIG"); } [Fact] public async Task OfType_WithTransform_ChangesType() { IExchange? received = null; _context.AddRoutes(r => { r.From("direct://oftype-transform-in") .OfType() .Transform(o => $"Order {o.Id} total: {o.Amount}") .To("direct://oftype-transform-out"); }); _context.AddRoutes(r => { r.From("direct://oftype-transform-out") .Process(ex => received = ex); }); await _context.Start(); var producer = _context.GetEndpoint("direct://oftype-transform-in").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message { Body = """{"id":"X","amount":42}""", ContentType = "application/json" })); received.Should().NotBeNull(); received!.In.Body.Should().Be("Order X total: 42"); } [Fact] public async Task OfType_String_SkipsConvertBody() { string? received = null; _context.AddRoutes(r => { r.From("direct://oftype-string-in") .OfType() .Process(s => received = s); }); await _context.Start(); var producer = _context.GetEndpoint("direct://oftype-string-in").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message { Body = "hello" })); received.Should().Be("hello"); } [Fact] public async Task OfType_XmlContentType_DeserializesXml() { XmlOrder? received = null; var xml = new XmlMessageSerializer(); var bytes = xml.Serialize(new XmlOrder { Id = "XML-1", Total = 77m }); _context.AddRoutes(r => { r.From("direct://oftype-xml") .OfType() .Process(order => received = order); }); await _context.Start(); var producer = _context.GetEndpoint("direct://oftype-xml").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message { Body = bytes, ContentType = "application/xml" })); received.Should().NotBeNull(); received!.Id.Should().Be("XML-1"); received.Total.Should().Be(77m); } public record OrderDto(string Id, decimal Amount); public class XmlOrder { public string Id { get; set; } = ""; public decimal Total { get; set; } } } Path: redb-route/tests/redb.Route.Tests/Definitions/ExpressionDrivenEipTests.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/Definitions/ExpressionDrivenEipTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Aggregation; using redb.Route.Core; using redb.Route.Expressions; using redb.Route.Processors; using redb.Route.TestKit; using XPathExpr = redb.Route.Expressions.XPathExpression; namespace redb.Route.Tests.Definitions; /// /// Six EIPs took a correlation key, a recipient list, a next hop, an idempotency key or an endpoint /// URI only as a delegate, so a route that wanted one out of the message body had to hand-write /// e => XPath("/order/id").Evaluate<string>(e) at every call site. They now accept an /// directly, the way Apache Camel does — which is also what makes a /// language added later reach these EIPs without touching them again. /// public class ExpressionDrivenEipTests { private static readonly TimeSpan Wait = TimeSpan.FromSeconds(2); private static string Order(string customer) => $"{customer}"; // ── Aggregate ── [Fact] public async Task Aggregate_correlates_by_the_expression() { await using var ctx = new RouteContext().AddRoutes(b => b .From("direct://eip-agg") .Aggregate( new XPathExpr("/order/customer"), AggregationStrategies.GroupedBody(), agg => agg.In.Body is List { Count: >= 2 }) .To("mock://eip-agg-out") .EndAggregate()); await ctx.Start(); // Two for A and one for B: only A's group reaches its completion size, which is the whole // point — the key really came from the body rather than from the arrival order. await ctx.SendBody("direct://eip-agg", Order("A")); await ctx.SendBody("direct://eip-agg", Order("B")); await ctx.SendBody("direct://eip-agg", Order("A")); await ctx.Mock("mock://eip-agg-out").ExpectMessageCount(1).AssertIsSatisfiedAsync(Wait); ctx.Mock("mock://eip-agg-out").ReceivedExchanges[0].In.Body .Should().BeEquivalentTo(new List { Order("A"), Order("A") }); } [Fact] public async Task An_expression_that_matched_nothing_says_which_EIP_needed_a_value() { await using var ctx = new RouteContext().AddRoutes(b => b .From("direct://eip-agg-miss") .Aggregate( new XPathExpr("/order/missing"), AggregationStrategies.GroupedBody(), agg => true) .To("mock://eip-agg-miss-out") .EndAggregate()); await ctx.Start(); var act = () => ctx.SendBody("direct://eip-agg-miss", Order("A")); (await act.Should().ThrowAsync()) .Which.ToString().Should() .Contain("Aggregate: the expression produced no value") .And.Contain("A path that matched nothing yields nothing"); } // ── RecipientList ── [Fact] public async Task RecipientList_reads_a_sequence_of_matches() { await using var ctx = new RouteContext().AddRoutes(b => b .From("direct://eip-rl-seq") .RecipientList(new XPathExpr("/order/to/uri"))); await ctx.Start(); await ctx.SendBody("direct://eip-rl-seq", "mock://eip-rl-amock://eip-rl-b"); await ctx.Mock("mock://eip-rl-a").ExpectMessageCount(1).AssertIsSatisfiedAsync(Wait); await ctx.Mock("mock://eip-rl-b").ExpectMessageCount(1).AssertIsSatisfiedAsync(Wait); } [Fact] public async Task RecipientList_reads_one_delimited_string_too() { // Which shape arrives is a property of the message, not of the route, so both are read. await using var ctx = new RouteContext().AddRoutes(b => b .From("direct://eip-rl-str") .RecipientList(new HeaderExpression("recipients"))); await ctx.Start(); await ctx.SendBodyAndHeader("direct://eip-rl-str", "payload", "recipients", "mock://eip-rl-c, mock://eip-rl-d"); await ctx.Mock("mock://eip-rl-c").ExpectMessageCount(1).AssertIsSatisfiedAsync(Wait); await ctx.Mock("mock://eip-rl-d").ExpectMessageCount(1).AssertIsSatisfiedAsync(Wait); } // ── DynamicRouter ── [Fact] public async Task DynamicRouter_takes_the_next_hop_from_the_expression_and_stops_on_no_match() { await using var ctx = new RouteContext().AddRoutes(b => { b.From("direct://eip-dr").DynamicRouter(new XPathExpr("/order/next")); // The hop rewrites the body, so the next evaluation finds no hop and the routing ends. b.From("direct://eip-dr-hop").SetBody("").To("mock://eip-dr-out"); }); await ctx.Start(); await ctx.SendBody("direct://eip-dr", "direct://eip-dr-hop"); await ctx.Mock("mock://eip-dr-out").ExpectMessageCount(1).AssertIsSatisfiedAsync(Wait); } // ── IdempotentConsumer ── [Fact] public async Task IdempotentConsumer_keys_on_the_expression() { var repo = new InMemoryIdempotentRepository(); var processed = 0; await using var ctx = new RouteContext().AddRoutes(b => b .From("direct://eip-ic") .IdempotentConsumer(repo, new JsonPathExpression("$.messageId")) .Process(_ => processed++) .EndIdempotentConsumer()); await ctx.Start(); await ctx.SendBody("direct://eip-ic", """{"messageId":"m-1","n":1}"""); await ctx.SendBody("direct://eip-ic", """{"messageId":"m-1","n":2}"""); await ctx.SendBody("direct://eip-ic", """{"messageId":"m-2","n":3}"""); processed.Should().Be(2, "the second message repeats an id that the first one already claimed"); } // ── Enrich / PollEnrich ── [Fact] public async Task Enrich_takes_the_endpoint_from_the_expression() { await using var ctx = new RouteContext().AddRoutes(b => { b.From("direct://eip-enrich") .Enrich(new XPathExpr("/order/service"), (original, enriched) => { original.In.Body = enriched.In.Body; return original; }) .To("mock://eip-enrich-out"); b.From("direct://eip-enrich-svc").SetBody("enriched"); }); await ctx.Start(); await ctx.SendBody("direct://eip-enrich", "direct://eip-enrich-svc"); await ctx.Mock("mock://eip-enrich-out").ExpectBodies("enriched").AssertIsSatisfiedAsync(Wait); } [Fact] public async Task PollEnrich_takes_the_endpoint_from_the_expression() { await using var ctx = new RouteContext().AddRoutes(b => { b.From("direct://eip-poll") .PollEnrich(new HeaderExpression("source"), TimeSpan.FromSeconds(5)) .To("mock://eip-poll-out"); b.From("direct://eip-poll-src").SetBody("polled"); }); await ctx.Start(); await ctx.SendBodyAndHeader("direct://eip-poll", "original", "source", "direct://eip-poll-src"); await ctx.Mock("mock://eip-poll-out").ExpectBodies("polled").AssertIsSatisfiedAsync(Wait); } // ── The expression form and the lambda form agree ── [Fact] public async Task The_expression_form_routes_exactly_like_the_equivalent_lambda() { await using var ctx = new RouteContext().AddRoutes(b => { b.From("direct://eip-parity-expr").RecipientList(new XPathExpr("/order/to/uri")); b.From("direct://eip-parity-lambda").RecipientList( e => new XPathExpr("/order/to/uri").Evaluate(e)); }); await ctx.Start(); const string body = "mock://eip-parity-1mock://eip-parity-2"; await ctx.SendBody("direct://eip-parity-expr", body); await ctx.SendBody("direct://eip-parity-lambda", body); await ctx.Mock("mock://eip-parity-1").ExpectMessageCount(2).AssertIsSatisfiedAsync(Wait); await ctx.Mock("mock://eip-parity-2").ExpectMessageCount(2).AssertIsSatisfiedAsync(Wait); } } Path: redb-route/tests/redb.Route.Tests/Definitions/F8DefinitionTests.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/Definitions/F8DefinitionTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Definitions; using redb.Route.Processors; namespace redb.Route.Tests.Definitions; /// /// Tests for W5 F8 — AggregateDefinition, ThrottleDefinition, DebounceDefinition, CircuitBreakerDefinition. /// public class F8DefinitionTests : IAsyncLifetime { private readonly RouteContext _context = new(); public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { await _context.DisposeAsync(); GC.SuppressFinalize(this); } private static Exchange MakeExchange(object? body = null) => new Exchange(new Message { Body = body }); // ── AggregateDefinition — structure ─────────────────────────────────────── [Fact] public void Aggregate_ReturnsAggregateDefinition() { var route = new RouteDefinition(); var agg = route.Aggregate(_ => "key", (old, @new) => @new, _ => false); agg.Should().BeOfType(); } [Fact] public void Aggregate_SetsParentOnDefinition() { var route = new RouteDefinition(); var agg = route.Aggregate(_ => "key", (old, @new) => @new, _ => false); agg.Parent.Should().BeSameAs(route); } [Fact] public void Aggregate_IsAddedToRouteOutputs() { var route = new RouteDefinition(); route.Aggregate(_ => "key", (old, @new) => @new, _ => false); route.Outputs.Should().HaveCount(1); route.Outputs[0].Should().BeOfType(); } [Fact] public void EndAggregate_ReturnsParentRoute() { var route = new RouteDefinition(); var back = route.Aggregate(_ => "k", (o, n) => n, _ => true).EndAggregate(); back.Should().BeSameAs(route); } // ── AggregateDefinition — runtime ───────────────────────────────────────── [Fact] public async Task Aggregate_CompletedGroup_ForwardsToTargetPipeline() { var received = new List(); var route = new RouteDefinition(); route.Aggregate( _ => "key", (old, @new) => { var merged = new Exchange(new Message { Body = (old?.In.Body is string s ? s : "") + (@new.In.Body?.ToString() ?? "") }); return merged; }, agg => (agg.In.Body as string)?.Length >= 3) .Process(e => received.Add(e.In.Body)) .EndAggregate(); var proc = route.CreateProcessor(_context); await proc.Process(MakeExchange("A")); await proc.Process(MakeExchange("B")); await proc.Process(MakeExchange("C")); // completion: length >= 3 received.Should().HaveCount(1); received[0].Should().Be("ABC"); } // ── ThrottleDefinition — structure ──────────────────────────────────────── [Fact] public void Throttle_ReturnsThrottleDefinition() { var route = new RouteDefinition(); var throttle = route.Throttle(5); throttle.Should().BeOfType(); } [Fact] public void Throttle_SetsParentOnDefinition() { var route = new RouteDefinition(); var throttle = route.Throttle(5); throttle.Parent.Should().BeSameAs(route); } [Fact] public void Throttle_InvalidRate_Throws() { var route = new RouteDefinition(); route.Invoking(r => r.Throttle(0)) .Should().Throw(); } [Fact] public void EndThrottle_ReturnsParentRoute() { var route = new RouteDefinition(); var back = route.Throttle(5).EndThrottle(); back.Should().BeSameAs(route); } // ── ThrottleDefinition — runtime ────────────────────────────────────────── [Fact] public async Task Throttle_ProcessorCreated_ForwardsExchange() { var processed = new List(); var route = new RouteDefinition(); route.Throttle(100) .Process(e => processed.Add(e.In.Body)) .EndThrottle(); var proc = route.CreateProcessor(_context); await proc.Process(MakeExchange("hello")); processed.Should().ContainSingle().Which.Should().Be("hello"); } // ── DebounceDefinition — structure ──────────────────────────────────────── [Fact] public void Debounce_ReturnsDebounceDefinition() { var route = new RouteDefinition(); var deb = route.Debounce(_ => "k", TimeSpan.FromMilliseconds(100)); deb.Should().BeOfType(); } [Fact] public void Debounce_SetsParentOnDefinition() { var route = new RouteDefinition(); var deb = route.Debounce(_ => "k", TimeSpan.FromMilliseconds(100)); deb.Parent.Should().BeSameAs(route); } [Fact] public void EndDebounce_ReturnsParentRoute() { var route = new RouteDefinition(); var back = route.Debounce(_ => "k", TimeSpan.FromMilliseconds(50)).EndDebounce(); back.Should().BeSameAs(route); } // ── DebounceDefinition — runtime ────────────────────────────────────────── [Fact] public async Task Debounce_QuietPeriodElapsed_ForwardsLastExchange() { var received = new List(); var route = new RouteDefinition(); route.Debounce(_ => "key", TimeSpan.FromMilliseconds(50)) .Process(e => received.Add(e.In.Body)) .EndDebounce(); var proc = route.CreateProcessor(_context); await proc.Process(MakeExchange("first")); await proc.Process(MakeExchange("second")); // Wait for quiet period to expire await Task.Delay(200); received.Should().ContainSingle().Which.Should().Be("second"); } // ── CircuitBreakerDefinition — structure ────────────────────────────────── [Fact] public void CircuitBreaker_ReturnsCircuitBreakerDefinition() { var route = new RouteDefinition(); var cb = route.CircuitBreaker(); cb.Should().BeOfType(); } [Fact] public void CircuitBreaker_SetsParentOnDefinition() { var route = new RouteDefinition(); var cb = route.CircuitBreaker(); cb.Parent.Should().BeSameAs(route); } [Fact] public void CircuitBreaker_IsAddedToRouteOutputs() { var route = new RouteDefinition(); route.CircuitBreaker(); route.Outputs.Should().HaveCount(1); route.Outputs[0].Should().BeOfType(); } [Fact] public void EndCircuitBreaker_ReturnsParentRoute() { var route = new RouteDefinition(); var back = route.CircuitBreaker().EndCircuitBreaker(); back.Should().BeSameAs(route); } [Fact] public void OnFallback_ReturnsFallbackDefinition() { var cb = new CircuitBreakerDefinition(); var fallback = cb.OnFallback(); fallback.Should().BeOfType(); cb.FallbackBlock.Should().BeSameAs(fallback); } [Fact] public void OnFallback_ThrowsIfCalledTwice() { var cb = new CircuitBreakerDefinition(); cb.OnFallback(); cb.Invoking(c => c.OnFallback()) .Should().Throw(); } [Fact] public void FallbackDefinition_EndFallback_ReturnsCircuitBreaker() { var cb = new CircuitBreakerDefinition(); var back = cb.OnFallback().EndFallback(); back.Should().BeSameAs(cb); } [Fact] public void FallbackDefinition_EndCircuitBreaker_ReturnsParent() { var route = new RouteDefinition(); var cb = route.CircuitBreaker(); var back = cb.OnFallback().EndCircuitBreaker(); back.Should().BeSameAs(route); } // ── CircuitBreakerDefinition — runtime ──────────────────────────────────── [Fact] public async Task CircuitBreaker_Closed_ForwardsExchange() { var processed = new List(); var route = new RouteDefinition(); route.CircuitBreaker() .FailureThreshold(3) .Process(e => processed.Add(e.In.Body)) .EndCircuitBreaker(); var proc = route.CreateProcessor(_context); await proc.Process(MakeExchange("ok")); processed.Should().ContainSingle().Which.Should().Be("ok"); } [Fact] public async Task CircuitBreaker_Opens_AfterThresholdFailures_UsesFallback() { var fallbackRan = new List(); var route = new RouteDefinition(); route.CircuitBreaker() .FailureThreshold(2) .ResetTimeout(TimeSpan.FromSeconds(60)) .Process(_ => throw new InvalidOperationException("bang")) .OnFallback() .Process(e => fallbackRan.Add("fallback")) .EndFallback() .EndCircuitBreaker(); var proc = route.CreateProcessor(_context); // Trip the circuit: 2 failures open it for (var i = 0; i < 2; i++) { try { await proc.Process(MakeExchange()); } catch { /* expected */ } } // Now circuit is open — fallback should run await proc.Process(MakeExchange()); fallbackRan.Should().ContainSingle().Which.Should().Be("fallback"); } } Path: redb-route/tests/redb.Route.Tests/Definitions/GapFeatureTests.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/Definitions/GapFeatureTests.cs ---- using System.Collections.Concurrent; using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Definitions; using redb.Route.Transactions; namespace redb.Route.Tests.Definitions; /// /// Tests for features added to close DSL gaps: /// 1. Loop copy mode /// 2. RollbackAll DSL step /// 3. ExceptionHandled DSL step /// 4. RedeliveryPolicy class + DSL /// 5. OnException(params Type[]) /// public class GapFeatureTests : IAsyncLifetime { private readonly RouteContext _context = new(); public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { await _context.DisposeAsync(); GC.SuppressFinalize(this); } // ══════════════════════════════════════════ // 1. Loop with copy: true — DSL integration // ══════════════════════════════════════════ [Fact] public async Task Loop_CopyTrue_IsolatesIterations_Lambda() { var bodies = new List(); _context.AddRoutes(r => { r.From("direct://loop-copy-in") .Loop(3, cfg => { cfg.Process(ex => { var val = (int)(ex.In.Body ?? 0); bodies.Add(val); ex.In.Body = val + 100; // should NOT carry over }); }, copy: true) .To("direct://loop-copy-out"); }); IExchange? received = null; _context.AddRoutes(r => { r.From("direct://loop-copy-out") .Process(ex => received = ex); }); await _context.Start(); var producer = _context.GetEndpoint("direct://loop-copy-in").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message(1))); // Each iteration sees original body = 1 bodies.Should().AllBeEquivalentTo(1); // Last iteration result (1+100=101) is merged back received.Should().NotBeNull(); ((int)received!.In.Body!).Should().Be(101); } [Fact] public async Task Loop_CopyFalse_MutationsAccumulate_Lambda() { var bodies = new List(); _context.AddRoutes(r => { r.From("direct://loop-nocopy-in") .Loop(3, cfg => { cfg.Process(ex => { var val = (int)(ex.In.Body ?? 0); bodies.Add(val); ex.In.Body = val + 1; }); }) .To("direct://loop-nocopy-out"); }); IExchange? received = null; _context.AddRoutes(r => { r.From("direct://loop-nocopy-out") .Process(ex => received = ex); }); await _context.Start(); var producer = _context.GetEndpoint("direct://loop-nocopy-in").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message(0))); bodies.Should().BeEquivalentTo(new[] { 0, 1, 2 }); received.Should().NotBeNull(); ((int)received!.In.Body!).Should().Be(3); } [Fact] public async Task Loop_CopyTrue_Fluent() { var bodies = new List(); _context.AddRoutes(r => { r.From("direct://loop-copy-fluent-in") .Loop(3, copy: true) .Process(ex => { var val = (int)(ex.In.Body ?? 0); bodies.Add(val); ex.In.Body = val + 100; }) .End() .To("direct://loop-copy-fluent-out"); }); IExchange? received = null; _context.AddRoutes(r => { r.From("direct://loop-copy-fluent-out") .Process(ex => received = ex); }); await _context.Start(); var producer = _context.GetEndpoint("direct://loop-copy-fluent-in").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message(5))); // Each iteration sees original body = 5 bodies.Should().AllBeEquivalentTo(5); received.Should().NotBeNull(); ((int)received!.In.Body!).Should().Be(105); } [Fact] public async Task Loop_CopyTrue_HeadersIsolated() { var headerValues = new List(); _context.AddRoutes(r => { r.From("direct://loop-header-in") .Loop(3, cfg => { cfg.Process(ex => { headerValues.Add(ex.In.Headers.TryGetValue("Counter", out var v) ? v?.ToString() : null); ex.In.Headers["Counter"] = "modified"; }); }, copy: true); }); await _context.Start(); var producer = _context.GetEndpoint("direct://loop-header-in").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("body"))); // None of the iterations should see the "modified" header from a previous one headerValues.Should().AllSatisfy(v => v.Should().BeNull()); } [Fact] public void Loop_CopyTrue_RecordedInStep_Lambda() { var def = new RouteDefinition(); def.Loop(5, copy: true).EndLoop(); def.Outputs.Should().ContainSingle().Which.Should().BeOfType() .Which.Copy.Should().BeTrue(); } [Fact] public void Loop_CopyFalse_RecordedInStep_Lambda() { var def = new RouteDefinition(); def.Loop(5).EndLoop(); def.Outputs.Should().ContainSingle().Which.Should().BeOfType() .Which.Copy.Should().BeFalse(); } // ══════════════════════════════════════════ // 2. RollbackAll DSL step // ══════════════════════════════════════════ private sealed class TrackingAction : ITransactedAction { public bool Committed { get; private set; } public bool RolledBack { get; private set; } public Task Commit(CancellationToken ct = default) { Committed = true; return Task.CompletedTask; } public Task Rollback(CancellationToken ct = default) { RolledBack = true; return Task.CompletedTask; } } [Fact] public async Task RollbackAll_RollsBackAllTransactedActions() { var action1 = new TrackingAction(); var action2 = new TrackingAction(); _context.AddRoutes(r => { r.From("direct://rb-in") .Process(ex => { // Simulate transacted actions registered by TransactedProcessor var dict = new ConcurrentDictionary(StringComparer.OrdinalIgnoreCase); dict["action1"] = action1; dict["action2"] = action2; ex.Properties[TransactedProcessor.TransactActionPropertyKey] = dict; }) .RollbackAll() .To("direct://rb-out"); }); IExchange? received = null; _context.AddRoutes(r => { r.From("direct://rb-out") .Process(ex => received = ex); }); await _context.Start(); var producer = _context.GetEndpoint("direct://rb-in").CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("data")); await producer.Process(exchange); action1.RolledBack.Should().BeTrue(); action2.RolledBack.Should().BeTrue(); action1.Committed.Should().BeFalse(); action2.Committed.Should().BeFalse(); // Camel's markRollbackOnly(): the exchange is marked and the route stops there. exchange.IsRollbackOnly().Should().BeTrue(); received.Should().BeNull("the route stops at .RollbackAll()"); } [Fact] public async Task RollbackAll_NoActions_SetsRollbackOnlyWithoutError() { _context.AddRoutes(r => { r.From("direct://rb-empty-in") .RollbackAll() .To("direct://rb-empty-out"); }); IExchange? received = null; _context.AddRoutes(r => { r.From("direct://rb-empty-out") .Process(ex => received = ex); }); await _context.Start(); var producer = _context.GetEndpoint("direct://rb-empty-in").CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("data")); await producer.Process(exchange); // no error exchange.IsRollbackOnly().Should().BeTrue(); received.Should().BeNull("the route stops at .RollbackAll()"); } [Fact] public void RollbackAll_RecordedInSteps() { var def = new RouteDefinition(); def.From("direct://x").RollbackAll(); def.Outputs.Should().ContainSingle().Which.Should().BeOfType(); } // ══════════════════════════════════════════ // 3. ExceptionHandled DSL step // ══════════════════════════════════════════ [Fact] public async Task ExceptionHandled_ClearsExceptionAndSetsFlag() { _context.AddRoutes(r => { r.From("direct://eh-in") .Process(ex => { ex.Exception = new InvalidOperationException("test error"); }) .ExceptionHandled() .To("direct://eh-out"); }); IExchange? received = null; _context.AddRoutes(r => { r.From("direct://eh-out") .Process(ex => received = ex); }); await _context.Start(); var producer = _context.GetEndpoint("direct://eh-in").CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("data")); await producer.Process(exchange); received.Should().NotBeNull(); received!.Exception.Should().BeNull(); received.ExceptionHandled.Should().BeTrue(); } [Fact] public void ExceptionHandled_RecordedInSteps() { var def = new RouteDefinition(); def.From("direct://x").ExceptionHandled(); def.Outputs.Should().ContainSingle().Which.Should().BeOfType(); } [Fact] public async Task ExceptionHandled_UsableOutsideOnExceptionScope() { // Key test: ExceptionHandled() is NOT restricted to OnException blocks var processed = false; _context.AddRoutes(r => { r.From("direct://eh-outside-in") .Process(ex => ex.Exception = new Exception("bad")) .ExceptionHandled() .Process(_ => processed = true); }); await _context.Start(); var producer = _context.GetEndpoint("direct://eh-outside-in").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("go"))); processed.Should().BeTrue(); } // ══════════════════════════════════════════ // 4. RedeliveryPolicy class + DSL // ══════════════════════════════════════════ [Fact] public void RedeliveryPolicy_DefaultValues() { var policy = new RedeliveryPolicy(); policy.MaximumRedeliveries.Should().Be(0); policy.RedeliveryDelay.Should().Be(TimeSpan.FromSeconds(1)); policy.BackOffMultiplier.Should().Be(1.0); policy.UseExponentialBackOff.Should().BeFalse(); } [Fact] public void RedeliveryPolicy_InitProperties() { var policy = new RedeliveryPolicy { MaximumRedeliveries = 5, RedeliveryDelay = TimeSpan.FromMilliseconds(200), BackOffMultiplier = 2.5, UseExponentialBackOff = true }; policy.MaximumRedeliveries.Should().Be(5); policy.RedeliveryDelay.Should().Be(TimeSpan.FromMilliseconds(200)); policy.BackOffMultiplier.Should().Be(2.5); policy.UseExponentialBackOff.Should().BeTrue(); } [Fact] public void RedeliveryPolicy_AppliedInOnExceptionScope() { var policy = new RedeliveryPolicy { MaximumRedeliveries = 3, RedeliveryDelay = TimeSpan.FromMilliseconds(50), BackOffMultiplier = 2.0, UseExponentialBackOff = true }; var def = new RouteDefinition(); def.From("direct://x") .OnException() .RedeliveryPolicy(policy) .Handled() .End(); var oe = def.Outputs.Should().ContainSingle().Which.Should().BeOfType().Subject; oe.ExceptionTypes.Should().Equal([typeof(InvalidOperationException)]); oe.MaxRedeliveries.Should().Be(3); oe.RedeliveryDelayValue.Should().Be(TimeSpan.FromMilliseconds(50)); oe.BackoffMultiplierValue.Should().Be(2.0); oe.UseExponentialBackoffValue.Should().BeTrue(); } [Fact] public void RedeliveryPolicy_OutsideOnException_Throws() { var policy = new RedeliveryPolicy { MaximumRedeliveries = 1 }; var def = new RouteDefinition(); def.From("direct://x"); var act = () => def.RedeliveryPolicy(policy); act.Should().Throw() .WithMessage("*OnException*"); } [Fact] public void RedeliveryPolicy_NullPolicy_Throws() { var def = new RouteDefinition(); var act = () => def.OnException().RedeliveryPolicy(null!); act.Should().Throw(); } [Fact] public async Task RedeliveryPolicy_IntegrationWithEngine() { var callCount = 0; var policy = new RedeliveryPolicy { MaximumRedeliveries = 2, RedeliveryDelay = TimeSpan.FromMilliseconds(10) }; #pragma warning disable CS0618 // v1 DSL — OnException fluent chain requires v1 semantics _context.AddRoutes((InlineRouteBuilder r) => { r.From("direct://rp-engine-in") .OnException() .RedeliveryPolicy(policy) .Handled() .End() .Process(_ => { callCount++; throw new InvalidOperationException("retry me"); }); }); #pragma warning restore CS0618 await _context.Start(); var producer = _context.GetEndpoint("direct://rp-engine-in").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("go"))); // 1 original + 2 redeliveries callCount.Should().Be(3); } // ══════════════════════════════════════════ // 5. OnException(params Type[]) // ══════════════════════════════════════════ [Fact] public void OnException_ParamsTypes_RecordsMultipleHandlers() { var def = new RouteDefinition(); def.From("direct://x") .OnException(typeof(InvalidOperationException), typeof(TimeoutException)) .Handled() .MaximumRedeliveries(2) .End(); var oe = def.Outputs.Should().ContainSingle().Which.Should().BeOfType().Subject; oe.ExceptionTypes.Should().HaveCount(2); oe.ExceptionTypes[0].Should().Be(typeof(InvalidOperationException)); oe.ExceptionTypes[1].Should().Be(typeof(TimeoutException)); oe.MaxRedeliveries.Should().Be(2); oe.IsHandled.Should().BeTrue(); } [Fact] public void OnException_ParamsTypes_EmptyArray_Throws() { var def = new RouteDefinition(); var act = () => def.OnException(Array.Empty()); act.Should().Throw(); } [Fact] public void OnException_ParamsTypes_NonExceptionType_Throws() { var def = new RouteDefinition(); var act = () => def.OnException(typeof(string)); act.Should().Throw() .WithMessage("*String*not an Exception*"); } [Fact] public async Task OnException_ParamsTypes_CatchesBothTypes() { var handledTypes = new List(); _context.AddRoutes(r => { r.From("direct://multi-ex-in") .OnException(typeof(InvalidOperationException), typeof(ArgumentException)) .Handled() .Process(ex => handledTypes.Add(ex.Exception!.GetType().Name)) .End() .Process(_ => throw new InvalidOperationException("first")); }); await _context.Start(); var producer = _context.GetEndpoint("direct://multi-ex-in").CreateProducer(); await producer.Start(); // Send message that throws InvalidOperationException await producer.Process(new Exchange(new Message("go"))); handledTypes.Should().Contain("InvalidOperationException"); } [Fact] public async Task OnException_ParamsTypes_SecondTypeCaughtToo() { var handled = false; _context.AddRoutes(r => { r.From("direct://multi-ex2-in") .OnException(typeof(InvalidOperationException), typeof(ArgumentException)) .Handled() .Process(_ => handled = true) .End() .Process(_ => throw new ArgumentException("second type")); }); await _context.Start(); var producer = _context.GetEndpoint("direct://multi-ex2-in").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("go"))); handled.Should().BeTrue(); } [Fact] public void OnException_ParamsTypes_RedeliveryPolicyAppliedToAll() { var policy = new RedeliveryPolicy { MaximumRedeliveries = 4, RedeliveryDelay = TimeSpan.FromMilliseconds(100), BackOffMultiplier = 3.0, UseExponentialBackOff = true }; var def = new RouteDefinition(); def.From("direct://x") .OnException(typeof(InvalidOperationException), typeof(TimeoutException)) .RedeliveryPolicy(policy) .Handled() .End(); var oe = def.Outputs.Should().ContainSingle().Which.Should().BeOfType().Subject; oe.ExceptionTypes.Should().HaveCount(2); oe.MaxRedeliveries.Should().Be(4); oe.RedeliveryDelayValue.Should().Be(TimeSpan.FromMilliseconds(100)); oe.BackoffMultiplierValue.Should().Be(3.0); oe.UseExponentialBackoffValue.Should().BeTrue(); } // ── Builder-level OnException(params Type[]) ── [Fact] public async Task OnException_ParamsTypes_BuilderLevel() { var handled = false; _context.AddRoutes(r => { r.OnException(typeof(InvalidOperationException), typeof(TimeoutException)) .Handled() .Process(_ => handled = true); r.From("direct://builder-multi-in") .Process(_ => throw new TimeoutException("timeout")); }); await _context.Start(); var producer = _context.GetEndpoint("direct://builder-multi-in").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("go"))); handled.Should().BeTrue(); } [Fact] public void OnException_ParamsTypes_BuilderLevel_EmptyThrows() { var builder = new TestParamsBuilder(b => { b.CallOnException(Array.Empty()); }); var act = () => ((IRouteBuilder)builder).Configure(null!); act.Should().Throw(); } private sealed class TestParamsBuilder : RouteBuilder { private readonly Action? _configure; internal TestParamsBuilder(Action? configure = null) => _configure = configure; protected override void Configure() => _configure?.Invoke(this); public IRouteDefinition CallOnException(params Type[] types) => OnException(types); } } Path: redb-route/tests/redb.Route.Tests/Definitions/LeafDefinitionTests.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/Definitions/LeafDefinitionTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Definitions; using redb.Route.Processors; using redb.Route.Validation; namespace redb.Route.Tests.Definitions; /// /// Tests for W5 F2 — all leaf ProcessorDefinition subclasses. /// public class LeafDefinitionTests : IAsyncLifetime { private readonly RouteContext _context = new(); public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { await _context.DisposeAsync(); GC.SuppressFinalize(this); } private static Exchange MakeExchange(object? body = null) { var msg = new Message { Body = body }; return new Exchange(msg); } // ── Process ────────────────────────────────────────────────────────────── [Fact] public void ProcessActionDefinition_CreatesDelegate() { bool called = false; var def = new ProcessActionDefinition(_ => { called = true; }); var proc = def.CreateProcessor(_context); proc.Should().BeOfType(); proc.Process(MakeExchange()); called.Should().BeTrue(); } [Fact] public async Task ProcessAsyncDefinition_CreatesDelegate() { bool called = false; var def = new ProcessAsyncDefinition(async (_, _) => { called = true; await Task.CompletedTask; }); var proc = def.CreateProcessor(_context); await proc.Process(MakeExchange()); called.Should().BeTrue(); } [Fact] public void ProcessInstanceDefinition_ReturnsSameProcessor() { var inner = new DelegateProcessor(_ => { }); var def = new ProcessInstanceDefinition(inner); def.CreateProcessor(_context).Should().BeSameAs(inner); } // ── SetBody ─────────────────────────────────────────────────────────────── [Fact] public async Task SetBodyStaticDefinition_SetsBody() { var def = new SetBodyStaticDefinition("hello"); var ex = MakeExchange(); await def.CreateProcessor(_context).Process(ex); ex.In.Body.Should().Be("hello"); } [Fact] public async Task SetBodyFactoryDefinition_SetsBodyFromFactory() { var def = new SetBodyFactoryDefinition(e => "from-factory"); var ex = MakeExchange(); await def.CreateProcessor(_context).Process(ex); ex.In.Body.Should().Be("from-factory"); } // ── Transform ───────────────────────────────────────────────────────────── [Fact] public async Task TransformDefinition_TransformsBody() { var def = new TransformDefinition(e => e.In.Body?.ToString()?.ToUpperInvariant()); var ex = MakeExchange("hello"); await def.CreateProcessor(_context).Process(ex); ex.In.Body.Should().Be("HELLO"); } // ── SetHeader ───────────────────────────────────────────────────────────── [Fact] public async Task SetHeaderStaticDefinition_SetsHeader() { var def = new SetHeaderStaticDefinition("X-Test", 42); var ex = MakeExchange(); await def.CreateProcessor(_context).Process(ex); ex.In.Headers["X-Test"].Should().Be(42); } [Fact] public async Task RemoveHeaderDefinition_RemovesHeader() { var def = new RemoveHeaderDefinition("X-Remove"); var ex = MakeExchange(); ex.In.Headers["X-Remove"] = "val"; await def.CreateProcessor(_context).Process(ex); ex.In.Headers.ContainsKey("X-Remove").Should().BeFalse(); } [Fact] public async Task RemoveBodyDefinition_NullsBody() { var def = new RemoveBodyDefinition(); var ex = MakeExchange("not-null"); await def.CreateProcessor(_context).Process(ex); ex.In.Body.Should().BeNull(); } // ── SetProperty ─────────────────────────────────────────────────────────── [Fact] public async Task SetPropertyStaticDefinition_SetsProperty() { var def = new SetPropertyStaticDefinition("myKey", "myValue"); var ex = MakeExchange(); await def.CreateProcessor(_context).Process(ex); ex.Properties["myKey"].Should().Be("myValue"); } [Fact] public async Task RemovePropertyDefinition_RemovesProperty() { var def = new RemovePropertyDefinition("myKey"); var ex = MakeExchange(); ex.Properties["myKey"] = "v"; await def.CreateProcessor(_context).Process(ex); ex.Properties.ContainsKey("myKey").Should().BeFalse(); } // ── Throw / ExceptionHandled ────────────────────────────────────────────── [Fact] public void ThrowMessageDefinition_Throws() { var def = new ThrowMessageDefinition("boom"); var act = () => def.CreateProcessor(_context).Process(MakeExchange()); act.Should().ThrowAsync().WithMessage("boom"); } [Fact] public async Task ExceptionHandledDefinition_ClearsException() { var def = new ExceptionHandledDefinition(); var ex = MakeExchange(); ex.Exception = new Exception("test"); await def.CreateProcessor(_context).Process(ex); ex.ExceptionHandled.Should().BeTrue(); ex.Exception.Should().BeNull(); } // ── Stop ────────────────────────────────────────────────────────────────── [Fact] public async Task StopDefinition_StopsExchange() { var def = new StopDefinition(); var ex = MakeExchange(); await def.CreateProcessor(_context).Process(ex); ex.IsStopped.Should().BeTrue(); } // ── Delay ───────────────────────────────────────────────────────────────── [Fact] public void DelayDefinition_CreatesDelayProcessor() { var def = new DelayDefinition(TimeSpan.FromMilliseconds(100)); def.CreateProcessor(_context).Should().BeOfType(); } // ── Sampling ────────────────────────────────────────────────────────────── [Fact] public void SampleCountDefinition_CreatesSamplingProcessor() { var def = new SampleCountDefinition(3); def.CreateProcessor(_context).Should().BeOfType(); } [Fact] public void SamplePeriodDefinition_CreatesSamplingProcessor() { var def = new SamplePeriodDefinition(TimeSpan.FromSeconds(1)); def.CreateProcessor(_context).Should().BeOfType(); } // ── Validate ────────────────────────────────────────────────────────────── [Fact] public void ValidatePredicateDefinition_CreatesValidateProcessor() { var def = new ValidatePredicateDefinition(e => true, "error", throwOnFailure: false); def.CreateProcessor(_context).Should().BeOfType(); } // ── SetPattern / Respond ────────────────────────────────────────────────── [Fact] public async Task SetPatternDefinition_SetsPattern() { var def = new SetPatternDefinition(ExchangePattern.InOut); var ex = MakeExchange(); await def.CreateProcessor(_context).Process(ex); ex.Pattern.Should().Be(ExchangePattern.InOut); } } Path: redb-route/tests/redb.Route.Tests/Definitions/OnExceptionNestedScopeHoistingTests.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/Definitions/OnExceptionNestedScopeHoistingTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Definitions; using redb.Route.Transactions; using Xunit; namespace redb.Route.Tests.Definitions; /// /// Regression tests for route-scoped OnException hoisting (Camel parity): /// an OnException declared inside a nested scope (Transacted, Traced, ...) must be /// hoisted to wrap the whole route — and must NOT compile into an inline pipeline /// step that runs its handler on every healthy exchange. /// public class OnExceptionNestedScopeHoistingTests : IAsyncLifetime { private readonly RouteContext _context = new(); public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { await _context.DisposeAsync(); GC.SuppressFinalize(this); } [Fact] public async Task OnException_InsideTransactedScope_DoesNotRunHandlerOnHealthyExchange() { var handlerRan = false; var endReached = false; _context.AddRoutes(r => { var scope = r.From("direct://oe-tx-healthy") .Transaction(TransactionPolicy.Suppress); scope .OnException() .Handled() .Process(_ => handlerRan = true) .EndOnException() .Process(_ => endReached = true); }); await _context.Start(); var producer = _context.GetEndpoint("direct://oe-tx-healthy").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("ok"))); handlerRan.Should().BeFalse("the OnException handler must only run when an exception was thrown"); endReached.Should().BeTrue(); } [Fact] public async Task OnException_InsideTransactedScope_IsHoistedAndHandlesException() { var handlerRan = false; Exception? seenAtHandlerTime = null; _context.AddRoutes(r => { var scope = r.From("direct://oe-tx-throw") .Transaction(TransactionPolicy.Suppress); scope .OnException() .Handled() .Process(ex => { handlerRan = true; seenAtHandlerTime = ex.Exception; }) .EndOnException() .Process(_ => throw new InvalidOperationException("boom")); }); await _context.Start(); var producer = _context.GetEndpoint("direct://oe-tx-throw").CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("go")); await producer.Process(exchange); handlerRan.Should().BeTrue("the OnException declared inside the Transacted scope must be hoisted to route level"); seenAtHandlerTime.Should().BeOfType(); } [Fact] public async Task OnException_InsideTransactedScope_OnWhenPredicateIsRespected() { var handlerRan = false; _context.AddRoutes(r => { var scope = r.From("direct://oe-tx-onwhen") .Transaction(TransactionPolicy.Suppress); scope .OnException() .OnWhen(e => e.Exception?.Message == "match") .Handled() .Process(_ => handlerRan = true) .EndOnException() .Process(_ => throw new InvalidOperationException("no-match")); }); await _context.Start(); var producer = _context.GetEndpoint("direct://oe-tx-onwhen").CreateProducer(); await producer.Start(); var act = () => producer.Process(new Exchange(new Message("go"))); await act.Should().ThrowAsync("OnWhen returned false, so the exception must propagate"); handlerRan.Should().BeFalse(); } [Fact] public void OnException_InsideCatchBlock_FailsFastAtCompilation() { var def = new RouteDefinition(); var tryScope = ((IRouteDefinition)def.From("direct://oe-ff")).TryCatch(); tryScope.Catch() .OnException() .Handled(); var act = () => def.CreateProcessor(_context); act.Should().Throw() .WithMessage("*route-scoped*"); } } Path: redb-route/tests/redb.Route.Tests/Definitions/ProcessorDefinitionTests.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/Definitions/ProcessorDefinitionTests.cs ---- using AwesomeAssertions; using redb.Route.Core; using redb.Route.Definitions; using redb.Route.Processors; namespace redb.Route.Tests.Definitions; /// /// Tests for W5 ProcessorDefinition migration: F0-F1 foundations. /// public class ProcessorDefinitionTests : IAsyncLifetime { private readonly RouteContext _context = new(); public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { await _context.DisposeAsync(); GC.SuppressFinalize(this); } [Fact] public void ToDefinition_CompilesToToProcessor() { var def = new ToDefinition("direct:target"); var proc = def.CreateProcessor(_context); proc.Should().BeOfType(); ((ToProcessor)proc).EndpointUri.Should().Be("direct:target"); } [Fact] public void ProcessorDefinition_AddOutput_SetsParent() { var parent = new ToDefinition("direct:a"); var child = new ToDefinition("direct:b"); // ProcessorDefinition.AddOutput is protected, so test through RouteDefinition once it exists. // For now verify the interface contract manually. child.Parent = parent; child.Parent.Should().BeSameAs(parent); } } Path: redb-route/tests/redb.Route.Tests/Definitions/RouteBuilderTests.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/Definitions/RouteBuilderTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Definitions; namespace redb.Route.Tests.Definitions; /// /// Tests for W5 F10 — RouteBuilder (class-based and inline) factory. /// public class RouteBuilderTests : IAsyncLifetime { private readonly RouteContext _context = new(); public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { await _context.DisposeAsync(); GC.SuppressFinalize(this); } // ── Helper builder subclass ──────────────────────────────────────────────── private sealed class SingleRouteBuilder : RouteBuilder { private readonly string _from; private readonly Action _configure; public SingleRouteBuilder(string from, Action configure) { _from = from; _configure = configure; } protected override void Configure() => _configure(From(_from)); } private sealed class TwoRouteBuilder : RouteBuilder { private readonly List _hits; public TwoRouteBuilder(List hits) => _hits = hits; protected override void Configure() { From("direct://rb2-multi-1").Process(e => _hits.Add("1:" + e.In.Body)); From("direct://rb2-multi-2").Process(e => _hits.Add("2:" + e.In.Body)); } } // ── RouteBuilder class-based ───────────────────────────────────────────── [Fact] public async Task ClassBased_SingleRoute_ProcessesExchange() { IExchange? captured = null; var builder = new SingleRouteBuilder( "direct://rb2-class", r => r.Process(e => captured = e).SetBody("rb2")); _context.AddRoutes(builder); await _context.Start(); var producer = _context.GetEndpoint("direct://rb2-class").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message { Body = "in" })); captured.Should().NotBeNull(); captured!.In.Body.Should().Be("rb2"); } [Fact] public async Task ClassBased_MultipleRoutes_BothProcess() { var hits = new List(); _context.AddRoutes(new TwoRouteBuilder(hits)); await _context.Start(); var p1 = _context.GetEndpoint("direct://rb2-multi-1").CreateProducer(); var p2 = _context.GetEndpoint("direct://rb2-multi-2").CreateProducer(); await p1.Start(); await p2.Start(); await p1.Process(new Exchange(new Message { Body = "a" })); await p2.Process(new Exchange(new Message { Body = "b" })); hits.Should().BeEquivalentTo(["1:a", "2:b"]); } [Fact] public async Task ClassBased_RouteId_Preserved() { var builder = new SingleRouteBuilder( "direct://rb2-id", r => r.RouteId("my-builder2-route").SetBody("ok")); _context.AddRoutes(builder); await _context.Start(); _context.GetRoute("my-builder2-route").Should().NotBeNull(); } [Fact] public async Task ClassBased_AutoStartFalse_RouteStopped() { var builder = new SingleRouteBuilder( "direct://rb2-stopped", r => r.RouteId("rb2-no-start").AutoStart(false).SetBody("x")); _context.AddRoutes(builder); await _context.Start(); _context.GetRoute("rb2-no-start")!.Status.Should().Be(RouteStatus.Stopped); } // ── AddRoutes inline ────────────────────────────────────────────────────── [Fact] public async Task Inline_AddRoutes_ProcessesExchange() { IExchange? captured = null; _context.AddRoutes(r => { r.From("direct://rb2-inline") .SetBody("inline-ok") .Process(e => captured = e); }); await _context.Start(); var producer = _context.GetEndpoint("direct://rb2-inline").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message { Body = "x" })); captured!.In.Body.Should().Be("inline-ok"); } [Fact] public async Task Inline_AddRoutes_MultipleRoutes() { var hits = new List(); _context.AddRoutes(r => { r.From("direct://rb2-il-a").Process(e => hits.Add("A")); r.From("direct://rb2-il-b").Process(e => hits.Add("B")); }); await _context.Start(); var pa = _context.GetEndpoint("direct://rb2-il-a").CreateProducer(); var pb = _context.GetEndpoint("direct://rb2-il-b").CreateProducer(); await pa.Start(); await pb.Start(); await pa.Process(new Exchange(new Message())); await pb.Process(new Exchange(new Message())); hits.Should().BeEquivalentTo(["A", "B"]); } [Fact] public async Task Inline_AddRoutes_WithScopes() { var passed = new List(); _context.AddRoutes(r => { r.From("direct://rb2-scope") .Filter(e => e.In.Body is int n && n > 5) .Process(e => passed.Add(e.In.Body)) .EndFilter(); }); await _context.Start(); var producer = _context.GetEndpoint("direct://rb2-scope").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message { Body = 3 })); await producer.Process(new Exchange(new Message { Body = 7 })); await producer.Process(new Exchange(new Message { Body = 10 })); passed.Should().BeEquivalentTo([7, 10]); } // ── AddRoutes(RouteBuilder) null guard ─────────────────────────────────── [Fact] public void AddRoutes_NullBuilder2_Throws() { _context.Invoking(c => c.AddRoutes((RouteBuilder)null!)) .Should().Throw(); } [Fact] public void AddRoutes_NullAction_Throws() { _context.Invoking(c => c.AddRoutes((Action)null!)) .Should().Throw(); } // ── OnException via RouteBuilder2BatchBridge ─────────────────────────────── private sealed class BuilderWithOnException : RouteBuilder { private readonly List _log; public BuilderWithOnException(List log) => _log = log; protected override void Configure() { OnException() .Handled() .Process(e => _log.Add("caught:" + e.Exception?.Message)); From("direct://rb2-ex") .Process(_ => throw new InvalidOperationException("boom")) .Process(e => _log.Add("should-not-reach")); } } [Fact] public async Task OnException_InRouteBuilder2_HandlesException() { var log = new List(); _context.AddRoutes(new BuilderWithOnException(log)); await _context.Start(); var producer = _context.GetEndpoint("direct://rb2-ex").CreateProducer(); await producer.Start(); // Should NOT throw because the exception is handled await producer.Process(new Exchange(new Message { Body = "test" })); log.Should().ContainSingle(s => s.StartsWith("caught:boom")); log.Should().NotContain("should-not-reach"); } } Path: redb-route/tests/redb.Route.Tests/Definitions/RouteDefinitionTests.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/Definitions/RouteDefinitionTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Definitions; using redb.Route.Processors; using redb.Route.Transactions; using redb.Route.Validation; namespace redb.Route.Tests.Definitions; /// /// Tests for W5 F3 — RouteDefinition skeleton (pipeline compilation). /// public class RouteDefinitionTests : IAsyncLifetime { private readonly RouteContext _context = new(); public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { await _context.DisposeAsync(); GC.SuppressFinalize(this); } private static Exchange MakeExchange(object? body = null) => new Exchange(new Message { Body = body }); // ── CreateProcessor pipeline ────────────────────────────────────────────── [Fact] public void CreateProcessor_EmptyOutputs_ReturnsDelegate() { var def = new RouteDefinition(); def.CreateProcessor(_context).Should().BeOfType(); } [Fact] public void CreateProcessor_SingleOutput_ReturnsThatProcessor() { var def = new RouteDefinition().To("direct:target"); def.CreateProcessor(_context).Should().BeOfType(); } [Fact] public void CreateProcessor_MultipleOutputs_ReturnsPipeline() { var def = new RouteDefinition() .To("direct:a") .To("direct:b"); def.CreateProcessor(_context).Should().BeOfType(); } // ── Fluent identity ─────────────────────────────────────────────────────── [Fact] public void RouteId_Stored() { var def = new RouteDefinition().RouteId("my-route"); def.GetRouteId().Should().Be("my-route"); } [Fact] public void From_Stored() { var def = new RouteDefinition().From("kafka://orders"); def.GetFromUri().Should().Be("kafka://orders"); } [Fact] public void AutoStart_DefaultTrue() { new RouteDefinition().GetAutoStart().Should().BeTrue(); } [Fact] public void AutoStart_CanBeSetFalse() { new RouteDefinition().AutoStart(false).GetAutoStart().Should().BeFalse(); } // ── Leaf methods add to Outputs ─────────────────────────────────────────── [Fact] public void To_AddsToDefinition() { var def = new RouteDefinition(); def.To("direct:x"); def.Outputs.Should().HaveCount(1); def.Outputs[0].Should().BeOfType(); } [Fact] public void SetBody_AddsSetBodyStaticDefinition() { var def = new RouteDefinition(); def.SetBody("hello"); def.Outputs.Should().HaveCount(1); def.Outputs[0].Should().BeOfType(); } [Fact] public void Chaining_AddsInOrder() { var def = new RouteDefinition() .SetBody("a") .SetHeader("x", 1) .To("direct:out"); def.Outputs.Should().HaveCount(3); } // ── End-to-end pipeline execution ──────────────────────────────────────── [Fact] public async Task Pipeline_ExecutesOutputsInOrder() { var log = new List(); var def = new RouteDefinition() .Process(_ => { log.Add("step1"); }) .Process(_ => { log.Add("step2"); }); var proc = def.CreateProcessor(_context); await proc.Process(MakeExchange()); log.Should().Equal("step1", "step2"); } [Fact] public async Task SetBody_ThenTransform_ProducesExpectedBody() { var def = new RouteDefinition() .SetBody("hello") .Transform(e => e.In.Body?.ToString()?.ToUpperInvariant()); var ex = MakeExchange(); await def.CreateProcessor(_context).Process(ex); ex.In.Body.Should().Be("HELLO"); } [Fact] public async Task Stop_HaltsRemainingOutputs() { bool reached = false; var def = new RouteDefinition() .Stop() .Process(_ => { reached = true; }); var ex = MakeExchange(); await def.CreateProcessor(_context).Process(ex); reached.Should().BeFalse(); ex.IsStopped.Should().BeTrue(); } // ── AddOutput sets Parent on child ──────────────────────────────────────── [Fact] public void AddOutput_SetsParentOnChild() { var def = new RouteDefinition(); def.To("direct:x"); def.Outputs[0].Parent.Should().BeSameAs(def); } [Fact] public async Task StreamCaching_WrapsStreamBodyForReread() { using var ms = new MemoryStream("hello"u8.ToArray()); string? firstRead = null; string? secondRead = null; _context.AddRoutes(r => { r.From("direct://stream-cache-test") .StreamCaching() .Process(async (e, ct) => { var s = (Stream)e.In.Body!; using var sr = new StreamReader(s, leaveOpen: true); firstRead = await sr.ReadToEndAsync(ct); }) .Process(async (e, ct) => { // Without StreamCaching this read would return empty string var s = (Stream)e.In.Body!; s.Position = 0; using var sr = new StreamReader(s, leaveOpen: true); secondRead = await sr.ReadToEndAsync(ct); }); }); await _context.Start(); var producer = _context.GetEndpoint("direct://stream-cache-test").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message { Body = ms })); firstRead.Should().Be("hello"); secondRead.Should().Be("hello"); } // ── Loop ───────────────────────────────────────────────────────────────── [Fact] public async Task Loop_CountBased_RepeatsExactTimes() { int count = 0; var def = new RouteDefinition() .Loop(3) .Process(_ => count++) .EndLoop(); await def.CreateProcessor(_context).Process(MakeExchange()); count.Should().Be(3); } [Fact] public async Task Loop_ZeroCount_ExecutesNothing() { int count = 0; var def = new RouteDefinition() .Loop(0) .Process(_ => count++) .EndLoop(); await def.CreateProcessor(_context).Process(MakeExchange()); count.Should().Be(0); } [Fact] public async Task Loop_DynamicCount_ResolvesFromExchange() { int count = 0; var def = new RouteDefinition() .Loop(e => (int)e.In.Body!) .Process(_ => count++) .EndLoop(); var ex = MakeExchange(5); await def.CreateProcessor(_context).Process(ex); count.Should().Be(5); } [Fact] public async Task Loop_WhileCondition_StopsWhenFalse() { int count = 0; var def = new RouteDefinition() .Loop(e => count < 4) .Process(_ => count++) .EndLoop(); await def.CreateProcessor(_context).Process(MakeExchange()); count.Should().Be(4); } [Fact] public void Loop_EndLoop_ReturnsParent() { var root = new RouteDefinition(); var loopDef = root.Loop(1); loopDef.EndLoop().Should().BeSameAs(root); } // ── WireTap overloads ──────────────────────────────────────────────────── [Fact] public void WireTap_WithOnPrepare_AddsWireTapDefinition() { var def = new RouteDefinition(); def.WireTap("direct:tap", _ => { }); def.Outputs.Should().HaveCount(1); def.Outputs[0].Should().BeOfType(); } [Fact] public void WireTap_WithNewBodyFactory_AddsWireTapDefinition() { var def = new RouteDefinition(); def.WireTap("direct:tap", e => e.In.Body); def.Outputs.Should().HaveCount(1); def.Outputs[0].Should().BeOfType(); } [Fact] public void WireTap_WithOnPrepareAndBodyFactory_AddsWireTapDefinition() { var def = new RouteDefinition(); def.WireTap("direct:tap", _ => { }, e => e.In.Body); def.Outputs.Should().HaveCount(1); def.Outputs[0].Should().BeOfType(); } // ── Transactions ─────────────────────────────────────────────────────────── [Fact] public void BeginTransaction_AddsBeginTransactionDefinition() { var def = new RouteDefinition(); def.BeginTransaction(); def.Outputs.Should().HaveCount(1); def.Outputs[0].Should().BeOfType(); } [Fact] public void BeginTransaction_WithPolicy_AddsBeginTransactionDefinition() { var def = new RouteDefinition(); def.BeginTransaction(redb.Route.Transactions.TransactionPolicy.RequiresNew); def.Outputs.Should().HaveCount(1); def.Outputs[0].Should().BeOfType(); } [Fact] public void CommitTransaction_AddsCommitTransactionDefinition() { var def = new RouteDefinition(); def.CommitTransaction(); def.Outputs.Should().HaveCount(1); def.Outputs[0].Should().BeOfType(); } [Fact] public void RollbackTransaction_AddsRollbackTransactionDefinition() { var def = new RouteDefinition(); def.RollbackTransaction(); def.Outputs.Should().HaveCount(1); def.Outputs[0].Should().BeOfType(); } // ── Validation ───────────────────────────────────────────────────────────── [Fact] public void Validate_WithPredicate_AddsValidatePredicateDefinition() { var def = new RouteDefinition(); def.Validate(_ => true, "must be true"); def.Outputs.Should().HaveCount(1); def.Outputs[0].Should().BeOfType(); } [Fact] public void ValidateJsonSchema_WithString_AddsValidateJsonSchemaStringDefinition() { var def = new RouteDefinition(); def.ValidateJsonSchema("""{ "type": "object" }"""); def.Outputs.Should().HaveCount(1); def.Outputs[0].Should().BeOfType(); } [Fact] public void ValidateXsd_WithString_AddsValidateXsdStringDefinition() { var def = new RouteDefinition(); def.ValidateXsd(""); def.Outputs.Should().HaveCount(1); def.Outputs[0].Should().BeOfType(); } [Fact] public void ValidateXsd_WithNamespace_AddsValidateXsdNamespaceDefinition() { var def = new RouteDefinition(); def.ValidateXsd("urn:test", ""); def.Outputs.Should().HaveCount(1); def.Outputs[0].Should().BeOfType(); } // ── Serialization ────────────────────────────────────────────────────────── [Fact] public void Marshal_WithType_AddsMarshalDefinition() { var def = new RouteDefinition(); def.Marshal(typeof(DummySerializer)); def.Outputs.Should().HaveCount(1); def.Outputs[0].Should().BeOfType(); } [Fact] public void Marshal_Generic_AddsMarshalDefinition() { var def = new RouteDefinition(); def.Marshal(); def.Outputs.Should().HaveCount(1); def.Outputs[0].Should().BeOfType(); } [Fact] public void Unmarshal_WithTypes_AddsUnmarshalDefinition() { var def = new RouteDefinition(); def.Unmarshal(typeof(DummySerializer), typeof(string)); def.Outputs.Should().HaveCount(1); def.Outputs[0].Should().BeOfType(); } [Fact] public void Unmarshal_Generic_AddsUnmarshalDefinition() { var def = new RouteDefinition(); def.Unmarshal(); def.Outputs.Should().HaveCount(1); def.Outputs[0].Should().BeOfType(); } // ── Telemetry ────────────────────────────────────────────────────────────── [Fact] public void Traced_Scope_ReturnsTracedDefinition() { var def = new RouteDefinition(); var scope = def.Traced("my-op"); scope.Should().BeOfType(); scope.OperationName.Should().Be("my-op"); def.Outputs.Should().HaveCount(1).And.Contain(scope); } [Fact] public void Traced_EndTraced_ReturnsParent() { var def = new RouteDefinition(); var parent = def.Traced("my-op").Process(_ => { }).EndTraced(); parent.Should().BeSameAs(def); } [Fact] public void Traced_End_ReturnsParent() { var def = new RouteDefinition(); var parent = def.Traced("my-op").End(); parent.Should().BeSameAs(def); } [Fact] public void Traced_Inline_AddsProcessInstanceDefinition() { var def = new RouteDefinition(); def.Traced("inline-op", _ => { }); def.Outputs.Should().HaveCount(1); def.Outputs[0].Should().BeOfType(); } [Fact] public void Traced_Scope_CompilesInstrumentedProcessor() { var def = new RouteDefinition(); def.Traced("compile-op").Process(_ => { }).EndTraced(); using var ctx = new RouteContext(); var proc = def.Outputs[0].CreateProcessor(ctx); proc.Should().BeOfType(); } [Fact] public void Metered_Scope_ReturnsMeteredDefinition() { var def = new RouteDefinition(); var scope = def.Metered("sql-step"); scope.Should().BeOfType(); scope.StepName.Should().Be("sql-step"); def.Outputs.Should().HaveCount(1).And.Contain(scope); } [Fact] public void Metered_EndMetered_ReturnsParent() { var def = new RouteDefinition(); var parent = def.Metered("sql-step").Process(_ => { }).EndMetered(); parent.Should().BeSameAs(def); } [Fact] public void Metered_End_ReturnsParent() { var def = new RouteDefinition(); var parent = def.Metered("sql-step").End(); parent.Should().BeSameAs(def); } [Fact] public void Metered_Inline_AddsProcessInstanceDefinition() { var def = new RouteDefinition(); def.Metered("inline-step", _ => { }); def.Outputs.Should().HaveCount(1); def.Outputs[0].Should().BeOfType(); } [Fact] public void Metered_Scope_CompilesMeteredStepProcessor() { var def = new RouteDefinition(); def.Metered("sql-step").Process(_ => { }).EndMetered(); using var ctx = new RouteContext(); var proc = def.Outputs[0].CreateProcessor(ctx); proc.Should().BeOfType(); } // ── TransactionDefinition ───────────────────────────────────────────────── [Fact] public void Transaction_Scope_ReturnsTransactionDefinition() { var def = new RouteDefinition(); var scope = def.Transaction(); scope.Should().BeOfType(); } [Fact] public void Transaction_EndTransaction_ReturnsParent() { var def = new RouteDefinition(); var parent = def.Transaction().Process(_ => { }).EndTransaction(); parent.Should().BeSameAs(def); } [Fact] public void Transaction_End_ReturnsParent() { var def = new RouteDefinition(); var parent = def.Transaction().End(); parent.Should().BeSameAs(def); } [Fact] public void Transaction_Scope_CompilesTransactedProcessor() { var def = new RouteDefinition(); def.Transaction().Process(_ => { }).EndTransaction(); using var ctx = new RouteContext(); var proc = def.Outputs[0].CreateProcessor(ctx); proc.Should().BeOfType(); } [Fact] public void Transaction_WithPolicy_IsRegistered() { var def = new RouteDefinition(); var policy = new redb.Route.Transactions.TransactionPolicy(); var scope = def.Transaction(policy); scope.Should().BeOfType(); def.Outputs.Should().HaveCount(1); } } // Minimal serializer stub for Serialization DSL tests. file sealed class DummySerializer : redb.Route.Abstractions.IMessageSerializer { public string ContentType => "application/octet-stream"; public byte[] Serialize(T value) => []; public T? Deserialize(byte[] data) => default; public object? Deserialize(byte[] data, Type type) => null; } Path: redb-route/tests/redb.Route.Tests/Definitions/ScopeDefinitionTests.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/Definitions/ScopeDefinitionTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Definitions; using redb.Route.Processors; namespace redb.Route.Tests.Definitions; /// /// Tests for W5 F4 — FilterDefinition and IdempotentConsumerDefinition. /// public class ScopeDefinitionTests : IAsyncLifetime { private readonly RouteContext _context = new(); public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { await _context.DisposeAsync(); GC.SuppressFinalize(this); } private static Exchange MakeExchange(object? body = null) => new Exchange(new Message { Body = body }); // ── FilterDefinition ───────────────────────────────────────────────────── [Fact] public void Filter_ReturnsFilterDefinition() { var route = new RouteDefinition(); var filter = route.Filter(_ => true); filter.Should().BeOfType(); } [Fact] public void Filter_SetsParentOnFilterDefinition() { var route = new RouteDefinition(); var filter = route.Filter(_ => true); filter.Parent.Should().BeSameAs(route); } [Fact] public void Filter_IsAddedToRouteOutputs() { var route = new RouteDefinition(); route.Filter(_ => true); route.Outputs.Should().HaveCount(1); route.Outputs[0].Should().BeOfType(); } [Fact] public void FilterDefinition_EndFilter_ReturnsParentRoute() { var route = new RouteDefinition(); var filter = route.Filter(_ => true); var back = filter.EndFilter(); back.Should().BeSameAs(route); } [Fact] public void FilterDefinition_EndFilter_WithoutParent_Throws() { var filter = new FilterDefinition(_ => true); var act = () => filter.EndFilter(); act.Should().Throw(); } [Fact] public void FilterDefinition_LeafMethods_ReturnSelf() { var filter = new FilterDefinition(_ => true); filter.Process(_ => { }).Should().BeSameAs(filter); filter.To("direct:x").Should().BeSameAs(filter); filter.SetBody("v").Should().BeSameAs(filter); filter.Stop().Should().BeSameAs(filter); } [Fact] public async Task FilterDefinition_PredicateTrue_PassesExchange() { bool processed = false; var route = new RouteDefinition() .Filter(_ => true) .Process(_ => { processed = true; }) .EndFilter(); var processor = ((RouteDefinition)route).CreateProcessor(_context); await processor.Process(MakeExchange()); processed.Should().BeTrue(); } [Fact] public async Task FilterDefinition_PredicateFalse_SkipsExchange() { bool processed = false; var route = new RouteDefinition() .Filter(_ => false) .Process(_ => { processed = true; }) .EndFilter(); var processor = ((RouteDefinition)route).CreateProcessor(_context); await processor.Process(MakeExchange()); processed.Should().BeFalse(); } [Fact] public async Task Filter_StepsAfterEndFilter_ExecuteRegardlessOfPredicate() { var log = new List(); var route = new RouteDefinition() .Filter(_ => false) .Process(_ => { log.Add("inside"); }) .EndFilter() .Process(_ => { log.Add("after"); }); var processor = ((RouteDefinition)route).CreateProcessor(_context); await processor.Process(MakeExchange()); log.Should().Equal("after"); } [Fact] public void FilterDefinition_CreateProcessor_ReturnsFilterProcessor() { var filter = new FilterDefinition(_ => true); filter.Process(_ => { }); filter.CreateProcessor(_context).Should().BeOfType(); } // ── IdempotentConsumerDefinition ────────────────────────────────────────── [Fact] public void IdempotentConsumer_ReturnsIdempotentConsumerDefinition() { var repo = new InMemoryIdempotentRepository(); var route = new RouteDefinition(); var ic = route.IdempotentConsumer(repo, e => e.In.GetHeader("id") ?? string.Empty); ic.Should().BeOfType(); } [Fact] public void IdempotentConsumer_SetsParent() { var repo = new InMemoryIdempotentRepository(); var route = new RouteDefinition(); var ic = route.IdempotentConsumer(repo, e => e.In.GetHeader("id") ?? string.Empty); ic.Parent.Should().BeSameAs(route); } [Fact] public void IdempotentConsumerDefinition_EndIdempotentConsumer_ReturnsParent() { var repo = new InMemoryIdempotentRepository(); var route = new RouteDefinition(); var ic = route.IdempotentConsumer(repo, e => e.In.GetHeader("id") ?? string.Empty); ic.EndIdempotentConsumer().Should().BeSameAs(route); } [Fact] public async Task IdempotentConsumer_DeduplicatesDuplicateMessages() { var repo = new InMemoryIdempotentRepository(); int processCount = 0; var route = new RouteDefinition() .IdempotentConsumer(repo, e => e.In.GetHeader("id") ?? string.Empty) .Process(_ => { processCount++; }) .EndIdempotentConsumer(); var processor = ((RouteDefinition)route).CreateProcessor(_context); var ex1 = MakeExchange(); ex1.In.setHeader("id", "msg-1"); await processor.Process(ex1); var ex2 = MakeExchange(); ex2.In.setHeader("id", "msg-1"); await processor.Process(ex2); processCount.Should().Be(1); } [Fact] public async Task IdempotentConsumer_ProcessesUniqueMessages() { var repo = new InMemoryIdempotentRepository(); int processCount = 0; var route = new RouteDefinition() .IdempotentConsumer(repo, e => e.In.GetHeader("id") ?? string.Empty) .Process(_ => { processCount++; }) .EndIdempotentConsumer(); var processor = ((RouteDefinition)route).CreateProcessor(_context); for (int i = 1; i <= 3; i++) { var ex = MakeExchange(); ex.In.setHeader("id", $"msg-{i}"); await processor.Process(ex); } processCount.Should().Be(3); } } Path: redb-route/tests/redb.Route.Tests/Definitions/SplitMulticastDefinitionTests.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/Definitions/SplitMulticastDefinitionTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Definitions; using redb.Route.Processors; namespace redb.Route.Tests.Definitions; /// /// Tests for W5 F6 — SplitDefinition and MulticastDefinition. /// public class SplitMulticastDefinitionTests : IAsyncLifetime { private readonly RouteContext _context = new(); public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { await _context.DisposeAsync(); GC.SuppressFinalize(this); } private static Exchange MakeExchange(object? body = null) => new Exchange(new Message { Body = body }); // ── SplitDefinition structure ───────────────────────────────────────────── [Fact] public void Split_ReturnsASplitDefinition() { var route = new RouteDefinition(); route.Split(_ => []).Should().BeOfType(); } [Fact] public void Split_IsAddedToRouteOutputs() { var route = new RouteDefinition(); route.Split(_ => []); route.Outputs.Should().HaveCount(1); route.Outputs[0].Should().BeOfType(); } [Fact] public void Split_SetsParent() { var route = new RouteDefinition(); var split = route.Split(_ => []); split.Parent.Should().BeSameAs(route); } [Fact] public void SplitDefinition_EndSplit_ReturnsParent() { var route = new RouteDefinition(); var back = route.Split(_ => []).EndSplit(); back.Should().BeSameAs(route); } [Fact] public void SplitDefinition_EndSplit_WithoutParent_Throws() { var split = new SplitDefinition(_ => []); split.Invoking(s => s.EndSplit()).Should().Throw(); } [Fact] public void SplitDefinition_CreateProcessor_ReturnsSplitterProcessor() { var split = new SplitDefinition(_ => []); split.Process(_ => { }); split.CreateProcessor(_context).Should().BeOfType(); } // ── SplitDefinition execution ───────────────────────────────────────────── [Fact] public async Task Split_ProcessesEachPart() { var log = new List(); var route = new RouteDefinition() .Split(e => (e.In.Body as IEnumerable)!) .Process(e => { log.Add(e.In.Body); }) .EndSplit(); var processor = ((RouteDefinition)route).CreateProcessor(_context); var ex = MakeExchange(new object?[] { "a", "b", "c" }); await processor.Process(ex); log.Should().Equal("a", "b", "c"); } [Fact] public async Task Split_EmptyList_ProcessesNothing() { int count = 0; var route = new RouteDefinition() .Split(_ => Array.Empty()) .Process(_ => { count++; }) .EndSplit(); var processor = ((RouteDefinition)route).CreateProcessor(_context); await processor.Process(MakeExchange()); count.Should().Be(0); } [Fact] public async Task StepsAfterEndSplit_ExecuteOnce() { int afterCount = 0; var route = new RouteDefinition() .Split(e => (e.In.Body as IEnumerable)!) .Process(_ => { }) .EndSplit() .Process(_ => { afterCount++; }); var processor = ((RouteDefinition)route).CreateProcessor(_context); await processor.Process(MakeExchange(new object?[] { "x", "y" })); afterCount.Should().Be(1); } // ── MulticastDefinition structure ───────────────────────────────────────── [Fact] public void Multicast_ReturnsMulticastDefinition() { var route = new RouteDefinition(); route.Multicast().Should().BeOfType(); } [Fact] public void Multicast_IsAddedToRouteOutputs() { var route = new RouteDefinition(); route.Multicast(); route.Outputs.Should().HaveCount(1); route.Outputs[0].Should().BeOfType(); } [Fact] public void Multicast_SetsParent() { var route = new RouteDefinition(); var mc = route.Multicast(); mc.Parent.Should().BeSameAs(route); } [Fact] public void MulticastDefinition_EndMulticast_ReturnsParent() { var route = new RouteDefinition(); var back = route.Multicast().EndMulticast(); back.Should().BeSameAs(route); } [Fact] public void MulticastDefinition_CreateProcessor_ReturnsMulticastProcessor() { var mc = new MulticastDefinition(); mc.Process(_ => { }); mc.CreateProcessor(_context).Should().BeOfType(); } // ── MulticastDefinition execution ───────────────────────────────────────── [Fact] public async Task Multicast_Sequential_SendsToAllTargets() { var log = new List(); var route = new RouteDefinition() .Multicast().Sequential() .Process(_ => { log.Add("target1"); }) .Process(_ => { log.Add("target2"); }) .EndMulticast(); var processor = ((RouteDefinition)route).CreateProcessor(_context); await processor.Process(MakeExchange()); log.Should().Equal("target1", "target2"); } } Path: redb-route/tests/redb.Route.Tests/Definitions/TryCatchDefinitionTests.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/Definitions/TryCatchDefinitionTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Definitions; namespace redb.Route.Tests.Definitions; /// /// Tests for W5 F7 — TryCatchDefinition, CatchDefinition, FinallyDefinition. /// public class TryCatchDefinitionTests : IAsyncLifetime { private readonly RouteContext _context = new(); public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { await _context.DisposeAsync(); GC.SuppressFinalize(this); } private static Exchange MakeExchange(object? body = null) => new Exchange(new Message { Body = body }); // ── Structure ───────────────────────────────────────────────────────────── [Fact] public void TryCatch_ReturnsDefinitionWithParentSet() { var route = new RouteDefinition(); var tc = route.TryCatch(); tc.Should().BeOfType(); tc.Parent.Should().BeSameAs(route); } [Fact] public void TryCatch_IsAddedToRouteOutputs() { var route = new RouteDefinition(); route.TryCatch(); route.Outputs.Should().HaveCount(1); route.Outputs[0].Should().BeOfType(); } [Fact] public void Catch_AddsCatchDefinitionToTryCatch() { var route = new RouteDefinition(); var tc = route.TryCatch(); tc.Catch(); tc.Catches.Should().HaveCount(1); tc.Catches[0].ExceptionType.Should().Be(typeof(InvalidOperationException)); } [Fact] public void Catch_ReturnsDefinitionWithParentSet() { var route = new RouteDefinition(); var catchDef = route.TryCatch().Catch(); catchDef.Parent.Should().BeOfType(); } [Fact] public void Finally_SetsFinallyBlock() { var route = new RouteDefinition(); var tc = route.TryCatch(); var fin = tc.Finally(); tc.FinallyBlock.Should().BeSameAs(fin); fin.Parent.Should().BeSameAs(tc); } [Fact] public void Finally_ThrowsIfCalledTwice() { var tc = new TryCatchDefinition(); tc.Finally(); tc.Invoking(t => t.Finally()) .Should().Throw(); } [Fact] public void EndTryCatch_ReturnsParentRouteDefinition() { var route = new RouteDefinition(); var back = route.TryCatch().EndTryCatch(); back.Should().BeSameAs(route); } [Fact] public void EndCatch_ReturnsTryCatchDefinition() { var route = new RouteDefinition(); var tc = route.TryCatch(); var back = tc.Catch().EndCatch(); back.Should().BeSameAs(tc); } [Fact] public void EndFinally_ReturnsTryCatchDefinition() { var route = new RouteDefinition(); var tc = route.TryCatch(); var back = tc.Finally().EndFinally(); back.Should().BeSameAs(tc); } // ── Runtime — happy path ───────────────────────────────────────────────── [Fact] public async Task TryCatch_NoException_RunsBody() { var route = new RouteDefinition(); route.TryCatch() .SetBody("ok") .Catch().SetBody("caught").EndCatch() .EndTryCatch(); var exchange = MakeExchange(); var proc = route.CreateProcessor(_context); await proc.Process(exchange); exchange.In.Body.Should().Be("ok"); } [Fact] public async Task TryCatch_MatchingCatch_CatchesException() { var route = new RouteDefinition(); route.TryCatch() .Process(_ => throw new InvalidOperationException("boom")) .Catch().SetBody("handled").EndCatch() .EndTryCatch(); var exchange = MakeExchange(); var proc = route.CreateProcessor(_context); await proc.Process(exchange); exchange.In.Body.Should().Be("handled"); exchange.ExceptionHandled.Should().BeTrue(); } [Fact] public async Task TryCatch_NonMatchingCatch_PropagatesException() { var route = new RouteDefinition(); route.TryCatch() .Process(_ => throw new ArgumentException("bad arg")) .Catch().SetBody("not this one").EndCatch() .EndTryCatch(); var exchange = MakeExchange(); var proc = route.CreateProcessor(_context); Func act = () => proc.Process(exchange); await act.Should().ThrowAsync(); } [Fact] public async Task TryCatch_Finally_RunsOnSuccess() { var finallyRan = false; var route = new RouteDefinition(); route.TryCatch() .SetBody("ok") .Finally().Process(_ => finallyRan = true).EndFinally() .EndTryCatch(); var exchange = MakeExchange(); var proc = route.CreateProcessor(_context); await proc.Process(exchange); finallyRan.Should().BeTrue(); exchange.In.Body.Should().Be("ok"); } [Fact] public async Task TryCatch_Finally_RunsEvenWhenExceptionNotCaught() { var finallyRan = false; var route = new RouteDefinition(); route.TryCatch() .Process(_ => throw new InvalidOperationException()) .Finally().Process(_ => finallyRan = true).EndFinally() .EndTryCatch(); var exchange = MakeExchange(); var proc = route.CreateProcessor(_context); Func act = () => proc.Process(exchange); await act.Should().ThrowAsync(); finallyRan.Should().BeTrue(); } [Fact] public async Task TryCatch_MultipleCatches_MatchesFirstCompatible() { var route = new RouteDefinition(); route.TryCatch() .Process(_ => throw new IOException("disk")) .Catch().SetBody("wrong").EndCatch() .Catch().SetBody("io-caught").EndCatch() .EndTryCatch(); var exchange = MakeExchange(); var proc = route.CreateProcessor(_context); await proc.Process(exchange); exchange.In.Body.Should().Be("io-caught"); } [Fact] public async Task TryCatch_Finally_RunsAfterCatch() { var finallyRan = false; var route = new RouteDefinition(); route.TryCatch() .Process(_ => throw new InvalidOperationException()) .Catch().SetBody("handled").EndCatch() .Finally().Process(_ => finallyRan = true).EndFinally() .EndTryCatch(); var exchange = MakeExchange(); var proc = route.CreateProcessor(_context); await proc.Process(exchange); exchange.In.Body.Should().Be("handled"); finallyRan.Should().BeTrue(); } // ── Chained navigation from CatchDefinition ─────────────────────────────── [Fact] public void CatchDefinition_ChainedCatch_AddsToTryCatch() { var route = new RouteDefinition(); var tc = route.TryCatch(); tc.Catch() .Catch() .EndTryCatch(); tc.Catches.Should().HaveCount(2); } } Path: redb-route/tests/redb.Route.Tests/Definitions/TypedRouteAndOptionTests.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/Definitions/TypedRouteAndOptionTests.cs ---- using redb.Route.Abstractions; using redb.Route.Configuration; using redb.Route.Core; using redb.Route.Extensions; namespace redb.Route.Tests.Definitions; /// /// Tests for typed route definitions (). /// public class TypedRouteDefinitionTests : IAsyncLifetime { private readonly RouteContext _context = new(); public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { await _context.DisposeAsync(); GC.SuppressFinalize(this); } [Fact] public async Task TypedRoute_FilterByType_OnlyProcessesMatchingMessages() { var received = new List(); _context.AddRoutes(r => { r.From("direct://typed-in") .OfType() .Filter(order => order.Amount > 50) .Process(ex => received.Add(ex.In.Body)); }); await _context.Start(); var producer = _context.GetEndpoint("direct://typed-in").CreateProducer(); await producer.Start(); // This one should pass the filter await producer.Process(new Exchange(new Message { Body = new OrderMessage("ORD-1", 100m) })); // This one should be filtered out (amount <= 50) await producer.Process(new Exchange(new Message { Body = new OrderMessage("ORD-2", 25m) })); received.Should().HaveCount(1); ((OrderMessage)received[0]!).Id.Should().Be("ORD-1"); } [Fact] public async Task TypedRoute_Transform_ChangesBody() { IExchange? received = null; _context.AddRoutes(r => { r.From("direct://transform-in") .OfType() .Transform(order => new OrderResult(order.Id, true)) .To("direct://transform-out"); }); _context.AddRoutes(r => { r.From("direct://transform-out") .Process(ex => received = ex); }); await _context.Start(); var producer = _context.GetEndpoint("direct://transform-in").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message { Body = new OrderMessage("ORD-3", 99m) })); received.Should().NotBeNull(); received!.In.Body.Should().BeOfType(); var result = (OrderResult)received.In.Body!; result.OrderId.Should().Be("ORD-3"); result.Accepted.Should().BeTrue(); } public record OrderMessage(string Id, decimal Amount); public record OrderResult(string OrderId, bool Accepted); } /// /// Tests for integration. /// public class RouteEngineOptionsTests : IAsyncLifetime { private RouteContext? _context; public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { if (_context != null) await _context.DisposeAsync(); GC.SuppressFinalize(this); } [Fact] public void Default_Options_AreReasonable() { var options = new RouteEngineOptions(); options.EnableTelemetry.Should().BeTrue(); options.EnableMetrics.Should().BeTrue(); options.ShutdownTimeout.Should().Be(TimeSpan.FromSeconds(30)); options.ThrowOnCompilationError.Should().BeTrue(); RouteEngineOptions.SectionName.Should().Be("RedbRoute"); } [Fact] public async Task Engine_WithTelemetryDisabled_StillWorks() { var options = new RouteEngineOptions { EnableTelemetry = false, EnableMetrics = false }; _context = new RouteContext(options: options); IExchange? received = null; _context.AddRoutes(r => { r.From("direct://no-tel-in") .Process(ex => received = ex) .To("direct://no-tel-out"); }); _context.AddRoutes(r => { r.From("direct://no-tel-out") .Process(_ => { }); }); await _context.Start(); var producer = _context.GetEndpoint("direct://no-tel-in").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message { Body = "test" })); received.Should().NotBeNull(); } [Fact] public async Task Engine_WithThrowOnCompilationError_False_SkipsBadRoutes() { var options = new RouteEngineOptions { ThrowOnCompilationError = false }; _context = new RouteContext(options: options); // Add a broken route (no From) _context.AddRoutes(r => { r.From("direct://good-route") .Process(_ => { }); }); // This should not throw even with compilation issues await _context.Start(); _context.Routes.Should().HaveCount(1); } } Path: redb-route/tests/redb.Route.Tests/Dsl/AsyncPredicateEndToEndTests.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/Dsl/AsyncPredicateEndToEndTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Tests.Dsl; /// /// End-to-end proof that is the method the engine calls. /// Until 2026-08-28 every branching definition unwrapped a predicate into its synchronous /// at the boundary, so an asynchronous predicate — one that /// consults a store or a service — was silently run synchronously, and the async half of the /// contract was dead. The predicate below answers only through the asynchronous method and /// refuses the synchronous one, which is exactly what a real awaiting predicate would do. /// [Collection("ExpressionResolver")] public class AsyncPredicateEndToEndTests : IAsyncLifetime { private readonly RouteContext _context = new(); public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { await _context.DisposeAsync(); GC.SuppressFinalize(this); } /// A predicate that is only ever right asynchronously. private sealed class AsyncOnlyPredicate(Func decide) : IPredicate { public int AsyncCalls { get; private set; } public bool Matches(IExchange exchange) => throw new InvalidOperationException("The engine must await MatchesAsync, not call Matches."); public async Task MatchesAsync(IExchange exchange) { await Task.Yield(); AsyncCalls++; return decide(exchange); } } private async Task Send(string uri, int amount) { var exchange = new Exchange(new Message("payload")); exchange.In.Headers["amount"] = amount; var producer = _context.GetEndpoint(uri).CreateProducer(); await producer.Start(); await producer.Process(exchange); return exchange; } [Fact] public async Task Filter_AwaitsThePredicate() { var predicate = new AsyncOnlyPredicate(e => (int)e.In.Headers["amount"]! > 1000); var passed = new List(); _context.AddRoutes(r => r.From("direct://async-filter") .Filter(predicate) .Process(e => passed.Add((int)e.In.Headers["amount"]!))); await _context.Start(); await Send("direct://async-filter", 5000); await Send("direct://async-filter", 10); passed.Should().Equal(5000); predicate.AsyncCalls.Should().Be(2); } [Fact] public async Task Choice_AwaitsThePredicate() { var predicate = new AsyncOnlyPredicate(e => (int)e.In.Headers["amount"]! > 1000); string? taken = null; _context.AddRoutes(r => r.From("direct://async-choice").Choice() .When(predicate).Process(_ => taken = "big").EndWhen() .Otherwise().Process(_ => taken = "small").EndChoice()); await _context.Start(); await Send("direct://async-choice", 5000); taken.Should().Be("big"); await Send("direct://async-choice", 10); taken.Should().Be("small"); predicate.AsyncCalls.Should().Be(2); } [Fact] public async Task Loop_AwaitsThePredicateBeforeEveryIteration() { var predicate = new AsyncOnlyPredicate(e => (int)e.Properties["i"]! < 3); var iterations = 0; _context.AddRoutes(r => r.From("direct://async-loop") .Loop(predicate) .Process(e => { iterations++; e.Properties["i"] = (int)e.Properties["i"]! + 1; }) .EndLoop()); await _context.Start(); var exchange = new Exchange(new Message("payload")); exchange.Properties["i"] = 0; var producer = _context.GetEndpoint("direct://async-loop").CreateProducer(); await producer.Start(); await producer.Process(exchange); iterations.Should().Be(3); predicate.AsyncCalls.Should().Be(4, "three iterations plus the final check that ends the loop"); } [Fact] public async Task Filter_RecordsThePredicateItWasGiven() { var predicate = new AsyncOnlyPredicate(_ => true); redb.Route.Definitions.FilterDefinition? filter = null; _context.AddRoutes(r => filter = r.From("direct://async-source").Filter(predicate)); await _context.Start(); filter!.SourcePredicate.Should().BeSameAs(predicate, "the stored condition is the source, not a copy beside it"); } } Path: redb-route/tests/redb.Route.Tests/Dsl/ConditionSourceTests.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/Dsl/ConditionSourceTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Definitions; using redb.Route.Expressions; using redb.Route.Predicates; namespace redb.Route.Tests.Dsl; /// /// The contract: every scope driven by a condition records what the /// author wrote under one name and one fixed type, so a reader never has to guess and an /// introspecting consumer can match on a single type instead of enumerating definition classes. /// // Shares the process-wide ExpressionResolver caches with the other expression tests, so it runs // in the same collection: cache-statistics assertions there are global and must not race. [Collection("ExpressionResolver")] public class ConditionSourceTests : IAsyncLifetime { private readonly RouteContext _context = new(); public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { await _context.DisposeAsync(); GC.SuppressFinalize(this); } private static IExchange WithFlag(bool flag) { var exchange = new Exchange(new Message("payload")); exchange.In.Headers["flag"] = flag; return exchange; } // ── Filter ──────────────────────────────────────────────────────────────── [Fact] public async Task Filter_FromString_CapturesTemplateAndPredicate() { FilterDefinition? filter = null; _context.AddRoutes(r => filter = r.From("direct://cs-filter-string").Filter("header.flag")); await _context.Start(); filter!.SourceTemplate.Should().Be("header.flag"); filter.SourcePredicate.Should().NotBeNull(); filter.SourceExpression.Should().BeNull(); } [Fact] public async Task Filter_FromExpression_CapturesExpressionOnly() { var expression = new HeaderExpression("flag"); FilterDefinition? filter = null; _context.AddRoutes(r => filter = r.From("direct://cs-filter-expr").Filter(expression)); await _context.Start(); filter!.SourceExpression.Should().BeSameAs(expression); filter.SourceTemplate.Should().BeNull(); filter.SourcePredicate.Should().BeNull(); } [Fact] public async Task Filter_FromPredicate_CapturesPredicateOnly() { var predicate = new HeaderExpression("flag").isEqualTo(true); FilterDefinition? filter = null; _context.AddRoutes(r => filter = r.From("direct://cs-filter-pred").Filter(predicate)); await _context.Start(); filter!.SourcePredicate.Should().BeSameAs(predicate); filter.SourceExpression.Should().BeNull(); filter.SourceTemplate.Should().BeNull(); } [Fact] public async Task Filter_FromDelegate_CapturesNothing() { FilterDefinition? filter = null; _context.AddRoutes(r => filter = r.From("direct://cs-filter-lambda").Filter(_ => true)); await _context.Start(); filter!.SourcePredicate.Should().BeNull("a lambda has no source to capture"); filter.SourceExpression.Should().BeNull(); filter.SourceTemplate.Should().BeNull(); } // ── When ────────────────────────────────────────────────────────────────── [Fact] public async Task When_FromString_CapturesTemplateAndPredicate() { WhenDefinition? branch = null; _context.AddRoutes(r => branch = r.From("direct://cs-when-string").Choice().When("header.flag")); await _context.Start(); branch!.SourceTemplate.Should().Be("header.flag"); branch.SourcePredicate.Should().NotBeNull(); branch.SourceExpression.Should().BeNull(); } /// /// Before the contract landed this path recorded nothing at all: the expression was folded into /// a delegate and lost. /// [Fact] public async Task When_FromExpression_CapturesExpressionOnly() { var expression = new HeaderExpression("flag"); WhenDefinition? branch = null; _context.AddRoutes(r => branch = r.From("direct://cs-when-expr").Choice().When(expression)); await _context.Start(); branch!.SourceExpression.Should().BeSameAs(expression); branch.SourceTemplate.Should().BeNull(); branch.SourcePredicate.Should().BeNull(); } [Fact] public async Task When_FromPredicate_CapturesPredicateOnly() { var predicate = new HeaderExpression("flag").isEqualTo(true); WhenDefinition? branch = null; _context.AddRoutes(r => branch = r.From("direct://cs-when-pred").Choice().When(predicate)); await _context.Start(); branch!.SourcePredicate.Should().BeSameAs(predicate); branch.SourceExpression.Should().BeNull(); branch.SourceTemplate.Should().BeNull(); } [Fact] public async Task When_FromDelegate_CapturesNothing() { WhenDefinition? branch = null; _context.AddRoutes(r => branch = r.From("direct://cs-when-lambda").Choice().When(_ => true)); await _context.Start(); branch!.SourcePredicate.Should().BeNull(); branch.SourceExpression.Should().BeNull(); branch.SourceTemplate.Should().BeNull(); } [Fact] public async Task AliasWhen_FromExpression_CapturesExpressionOnly() { var expression = new HeaderExpression("flag"); WhenDefinition? branch = null; _context.AddRoutes(r => { var choice = r.From("direct://cs-when-alias").Choice(); var nested = choice.When("header.flag").Filter("header.flag"); branch = nested.When(expression); }); await _context.Start(); branch!.SourceExpression.Should().BeSameAs(expression); } // ── The contract itself ─────────────────────────────────────────────────── /// /// Both condition scopes are reachable through the same type, which is the whole point: an /// introspecting consumer matches on rather than enumerating /// definition classes and hoping the property names line up. /// [Fact] public async Task BothConditionScopes_AreReadableThroughOneContract() { var scopes = new List(); _context.AddRoutes(r => { scopes.Add(r.From("direct://cs-contract-filter").Filter("header.flag")); scopes.Add(r.From("direct://cs-contract-when").Choice().When("header.flag")); }); await _context.Start(); scopes.Should().AllBeAssignableTo(); foreach (var source in scopes.Cast()) { source.SourceTemplate.Should().Be("header.flag"); source.SourceExpression.Should().BeNull(); source.SourcePredicate.Should().NotBeNull(); source.SourcePredicate!.Matches(WithFlag(true)).Should().BeTrue(); source.SourcePredicate.Matches(WithFlag(false)).Should().BeFalse(); } } /// /// The contract is read-only: nothing outside the assembly can rewrite what a route recorded. /// [Fact] public void TheContractExposesNoSetters() => typeof(IConditionSource).GetProperties() .Should().OnlyContain(p => p.CanRead && !p.CanWrite); } Path: redb-route/tests/redb.Route.Tests/Dsl/DeepNestedDslTests.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/Dsl/DeepNestedDslTests.cs ---- using System.Collections.Concurrent; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Definitions; namespace redb.Route.Tests.Dsl; /// /// Integration tests for deeply nested fluent scopes after the RouteStep removal. /// Validates two things at once: /// 1) The DSL compiles end-to-end (Choice → When → RichLog → Split → TryCatch → ...) /// using the full Camel-style scope toolbox with mixed End*() / End() closers. /// 2) The runtime tree produces the expected processor behavior — split fan-out, /// log capture (rich logs with route id + headers + properties), Catch handling, /// Otherwise fallback. /// public class DeepNestedDslTests { // ── Test logger that records every entry ───────────────────────────────── private 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(CapturingLoggerProvider owner, string category) : 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) => owner.Entries.Add(new LogEntry(category, logLevel, formatter(state, exception), exception)); } } private static (RouteContext Ctx, CapturingLoggerProvider Capture) NewContext() { var capture = new CapturingLoggerProvider(); var services = new ServiceCollection(); services.AddLogging(b => { b.SetMinimumLevel(LogLevel.Trace); b.AddProvider(capture); }); var provider = services.BuildServiceProvider(); var loggerFactory = provider.GetRequiredService(); var ctx = new RouteContext(provider, loggerFactory: loggerFactory); ctx.AddComponent(new Route.Components.DirectComponent()); return (ctx, capture); } private static IExchange NewExchange(object? body, IDictionary? headers = null) { var ex = Exchange.Create(new Message(body), null); if (headers is not null) foreach (var kv in headers) ex.In.Headers[kv.Key] = kv.Value; return ex; } // ───────────────────────────────────────────────────────────────────────── // Scenario 1 — Choice → When → RichLog → Split → Process×N + dyn-Log → EndLog, // sibling-When (string) and Otherwise reachable via the // extension methods on IRouteDefinition (typed parent recovery // after EndSplit). // ───────────────────────────────────────────────────────────────────────── [Fact] public async Task DeepNest_ChoiceWhenSplitRichLog_ExecutesAndLogs() { var (ctx, capture) = NewContext(); var processed = new ConcurrentBag(); var route = new RouteDefinition().RouteId("deep-1"); route.From("direct:in") .SetHeader("step", "start") .Choice() .When(e => e.In.Body is IEnumerable && e.In.Body is not string) .SetHeader("branch", "list") .Log(LogLevel.Information) .Message("opening list branch") .Header("branch") .Property("trace") .ShowRouteId(true) .EndLog() .Split((IExchange e) => (IEnumerable)((IEnumerable)e.In.Body!).Cast()) .Process(e => { var s = (string)e.In.Body!; processed.Add(s.ToUpperInvariant()); }) .Log(LogLevel.Debug) .Message(e => $"processed item={e.In.Body}") .Message("after-item") .EndLog() .EndSplit() .Log(LogLevel.Information).Message("list branch done").EndLog() .When(e => e.In.Body is string s && s.Length > 0) // sibling When via extension .SetHeader("branch", "string") .Process(e => processed.Add($"STR:{e.In.Body}")) .Otherwise() // sibling Otherwise via extension .SetHeader("branch", "fallback") .Process(e => processed.Add("FALLBACK")) .EndChoice() .Log(LogLevel.Information).Message("route complete").ShowRouteId(true).EndLog(); var processor = route.CreateProcessor(ctx); var ex1 = NewExchange(new[] { "alpha", "beta", "gamma" }); ex1.RouteId = "deep-1"; ex1.Properties["trace"] = "T-1"; await processor.Process(ex1); var ex2 = NewExchange("solo"); ex2.RouteId = "deep-1"; await processor.Process(ex2); var ex3 = NewExchange(42); ex3.RouteId = "deep-1"; await processor.Process(ex3); processed.Should().BeEquivalentTo(new[] { "ALPHA", "BETA", "GAMMA", "STR:solo", "FALLBACK" }); // Rich log fired at least once with the ShowRouteId / Header / Property pieces. var richListBranch = capture.Entries .Where(e => e.Level == LogLevel.Information && e.Message.Contains("opening list branch")) .ToList(); richListBranch.Should().NotBeEmpty(); var msg = richListBranch[0].Message; msg.Should().Contain("deep-1"); // ShowRouteId(true) msg.Should().Contain("branch=list"); // captured Header("branch") // Per-item dynamic message logged 3 times. capture.Entries.Count(e => e.Level == LogLevel.Debug && e.Message.Contains("processed item=")) .Should().Be(3); } // ───────────────────────────────────────────────────────────────────────── // Scenario 2 — TryCatch nested inside When, RichLog inside Catch handler. // ───────────────────────────────────────────────────────────────────────── [Fact] public async Task DeepNest_TryCatchInsideWhen_RichLogInCatch_HandlesAndLogs() { var (ctx, capture) = NewContext(); var route = new RouteDefinition().RouteId("deep-2"); route.From("direct:in") .Choice() .When(e => e.In.Body is string) .TryCatch() .Process(e => throw new InvalidOperationException("boom")) .DoCatch() .Log(LogLevel.Warning) .Message(e => $"caught: {e.Exception?.GetType().Name}") .ShowRouteId(true) .EndLog() .Process(e => e.In.Headers["caught"] = true) .EndTryCatch() .EndChoice(); var processor = route.CreateProcessor(ctx); var ex = NewExchange("trigger"); ex.RouteId = "deep-2"; await processor.Process(ex); ex.In.Headers["caught"].Should().Be(true); capture.Entries .Any(e => e.Level == LogLevel.Warning && e.Message.Contains("caught: InvalidOperationException") && e.Message.Contains("deep-2")) .Should().BeTrue(); } // ───────────────────────────────────────────────────────────────────────── // Scenario 3 — Universal End() walks Parent chain through every nested scope. // ───────────────────────────────────────────────────────────────────────── [Fact] public void DeepNest_UniversalEnd_ClosesNestedScopesInOrder() { var route = new RouteDefinition(); // 4-deep nest: Choice → When → Split → Log; close with two .End() and final .EndChoice(). // Note: WhenDefinition.End() cascades to EndChoice(), so we use only two .End()s // (Log → Split, Split → When) before the explicit .EndChoice(). var closed = route.From("direct:in") .Choice() .When(e => true) .Split(e => new object?[] { 1, 2 }) .Log(LogLevel.Information) .Message("inside") .End() // closes RichLog → SplitDefinition .End() // closes Split → WhenDefinition .EndChoice(); // walks Parent chain to Choice and closes it // After all closers we must be back at the root RouteDefinition, // which means subsequent leaf-DSL calls go to the root (no exception). closed.SetHeader("after-close", "ok"); // Tree shape: RouteDefinition.Outputs has 1 Choice + 1 SetHeader, // Choice.Whens[0].Outputs has 1 Split, Split.Outputs has 1 RichLog. route.Outputs.Should().HaveCount(2); route.Outputs[0].Should().BeOfType(); var choice = (ChoiceDefinition)route.Outputs[0]; choice.Whens.Should().HaveCount(1); choice.Whens[0].Outputs.Should().HaveCount(1); choice.Whens[0].Outputs[0].Should().BeOfType(); var split = (SplitDefinition)choice.Whens[0].Outputs[0]; split.Outputs.Should().HaveCount(1); split.Outputs[0].Should().BeOfType(); } // ───────────────────────────────────────────────────────────────────────── // Scenario 4 — EndChoice() called from inside a deeply nested Log scope // cascades through all open intermediate scopes (the real // ergonomic regression that motivated the refactor). // ───────────────────────────────────────────────────────────────────────── [Fact] public void DeepNest_EndChoice_FromDeepInside_CascadesAllIntermediateScopes() { var route = new RouteDefinition(); // Open 4 levels deep, then a single .EndChoice() must fast-forward through // RichLog + Split + When and land at the route root. var afterChoice = route.From("direct:in") .Choice() .When(e => true) .Split(e => new object?[] { 1 }) .Log(LogLevel.Information) .Message("deep") .ShowRouteId(true) .EndLog() // close RichLog → SplitDefinition .EndChoice(); // skips Split + When afterChoice.Should().BeAssignableTo(); // We can keep chaining leaf DSL on the route root after the cascade. afterChoice.SetHeader("post-cascade", "ok"); route.Outputs.Should().HaveCount(2); route.Outputs[0].Should().BeOfType(); } // ───────────────────────────────────────────────────────────────────────── // Scenario 5 — End() from outside any scope throws a useful diagnostic. // ───────────────────────────────────────────────────────────────────────── [Fact] public void End_OutsideAnyScope_Throws() { var route = new RouteDefinition(); route.From("direct:in").Process(_ => { }); var act = () => ((IRouteDefinition)route).EndSplit(); act.Should().Throw() .WithMessage("*EndSplit*outside*Split*"); } } Path: redb-route/tests/redb.Route.Tests/Dsl/ExpressionConditionEndToEndTests.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/Dsl/ExpressionConditionEndToEndTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Expressions; namespace redb.Route.Tests.Dsl; /// /// End-to-end coverage of an written in a condition position. The /// string-born expression — Expr("..."), i.e. — is the /// case that mattered: until 2026-08-28 it was read as a value and then coerced, so /// Filter(Expr("header.amount>1000")) looked up a header literally named /// amount>1000 and silently dropped every message. The string overload had already /// been fixed; this closes the same hole for the expression overload. /// [Collection("ExpressionResolver")] public class ExpressionConditionEndToEndTests : IAsyncLifetime { private readonly RouteContext _context = new(); public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { await _context.DisposeAsync(); GC.SuppressFinalize(this); } private async Task SendAmount(string uri, int amount) { var exchange = new Exchange(new Message("payload")); exchange.In.Headers["amount"] = amount; var producer = _context.GetEndpoint(uri).CreateProducer(); await producer.Start(); await producer.Process(exchange); return exchange.Properties.TryGetValue("reached", out var reached) && reached is true; } [Theory] [InlineData("header.amount>1000")] [InlineData("header.amount > 1000")] [InlineData("header.amount\t>\t1000")] public async Task Filter_WithStringBornExpression_ComparesLikeTheStringOverload(string condition) { var uri = "direct://expr-filter-" + Guid.NewGuid().ToString("N"); _context.AddRoutes(r => r.From(uri) .Filter(new StringExpression(condition)) .Process(e => e.Properties["reached"] = true)); await _context.Start(); (await SendAmount(uri, 5000)).Should().BeTrue("5000 > 1000"); (await SendAmount(uri, 10)).Should().BeFalse("10 is not > 1000"); } [Fact] public async Task Filter_WithStringBornExpression_AgreesWithTheStringOverloadOnEveryMessage() { var viaExpression = new List(); var viaString = new List(); _context.AddRoutes(r => { r.From("direct://expr-a").Filter(new StringExpression("header.amount>1000")) .Process(e => viaExpression.Add((int)e.In.Headers["amount"]!)); r.From("direct://expr-b").Filter("header.amount>1000") .Process(e => viaString.Add((int)e.In.Headers["amount"]!)); }); await _context.Start(); foreach (var amount in new[] { 10, 1000, 1001, 5000 }) { await SendAmount("direct://expr-a", amount); await SendAmount("direct://expr-b", amount); } viaExpression.Should().Equal(viaString); viaExpression.Should().Equal(1001, 5000); } [Fact] public async Task When_WithStringBornExpression_RoutesLikeTheStringOverload() { string? taken = null; _context.AddRoutes(r => r.From("direct://expr-when").Choice() .When(new StringExpression("header.amount>1000")).Process(_ => taken = "big").EndWhen() .Otherwise().Process(_ => taken = "small").EndChoice()); await _context.Start(); await SendAmount("direct://expr-when", 5000); taken.Should().Be("big"); await SendAmount("direct://expr-when", 5); taken.Should().Be("small"); } [Fact] public async Task Filter_WithStringBornTemplate_KeepsTheTruthinessReading() { var uri = "direct://expr-tpl"; _context.AddRoutes(r => r.From(uri) .Filter(new StringExpression("${header.amount}")) .Process(e => e.Properties["reached"] = true)); await _context.Start(); (await SendAmount(uri, 7)).Should().BeTrue("a non-zero number is truthy"); (await SendAmount(uri, 0)).Should().BeFalse("zero is false"); } [Fact] public async Task Filter_WithMalformedStringBornExpression_FailsWhileTheRouteIsBuilt() { // The value dialect accepts "header.amount >" as a lookup of a header named "amount >", // so the StringExpression itself constructs; the condition position rejects it when the // route is compiled at Start(), before any message flows. var reached = false; _context.AddRoutes(r => r.From("direct://expr-broken") .Filter(new StringExpression("header.amount >")) .Process(_ => reached = true)); var start = async () => await _context.Start(); await start.Should().ThrowAsync(); reached.Should().BeFalse(); } /// /// A typed expression that is not string-born keeps the plain truthiness reading: it has no /// source text to compile as a condition, only a value to read. /// [Theory] [InlineData(5000, true)] [InlineData(0, false)] public async Task Filter_WithTypedExpression_ReadsTheValueForTruthiness(int amount, bool expected) { var uri = "direct://expr-typed-" + amount; _context.AddRoutes(r => r.From(uri) .Filter(new HeaderExpression("amount")) .Process(e => e.Properties["reached"] = true)); await _context.Start(); (await SendAmount(uri, amount)).Should().Be(expected); } } Path: redb-route/tests/redb.Route.Tests/Dsl/StringConditionTests.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/Dsl/StringConditionTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Definitions; using redb.Route.Expressions; using redb.Route.Validation; namespace redb.Route.Tests.Dsl; /// /// Behaviour of the string-condition overloads of the route DSL: Filter, When, LoopWhile and /// Validate. They all compile a condition the same way, so a condition means the same thing /// wherever it is written. /// // Shares the process-wide ExpressionResolver caches with the other expression tests, so it runs // in the same collection: cache-statistics assertions there are global and must not race. [Collection("ExpressionResolver")] public class StringConditionTests : IAsyncLifetime { private readonly RouteContext _context = new(); public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { await _context.DisposeAsync(); GC.SuppressFinalize(this); } private async Task Send(string uri, IExchange exchange) { var producer = _context.GetEndpoint(uri).CreateProducer(); await producer.Start(); await producer.Process(exchange); return exchange; } private static IExchange WithAmount(int amount) { var exchange = new Exchange(new Message("payload")); exchange.In.Headers["amount"] = amount; return exchange; } // ── Filter ──────────────────────────────────────────────────────────────── [Theory] [InlineData("header.amount > 1000")] [InlineData("header.amount>1000")] public async Task Filter_ComparisonPassesTheMatchingMessage(string condition) { object? captured = null; var uri = "direct://filter-pass-" + condition.GetHashCode().ToString("x"); _context.AddRoutes(r => r.From(uri).Filter(condition).Process(e => captured = e.In.Body)); await _context.Start(); await Send(uri, WithAmount(5000)); captured.Should().Be("payload"); } [Theory] [InlineData("header.amount > 1000")] [InlineData("header.amount>1000")] public async Task Filter_ComparisonBlocksTheNonMatchingMessage(string condition) { object? captured = null; var uri = "direct://filter-block-" + condition.GetHashCode().ToString("x"); _context.AddRoutes(r => r.From(uri).Filter(condition).Process(e => captured = e.In.Body)); await _context.Start(); await Send(uri, WithAmount(10)); captured.Should().BeNull(); } /// /// The regression this whole change is about: without the fix the unspaced form compiles to a /// header lookup named amount>1000, which is always missing, so the filter silently /// dropped every message including the ones it was supposed to pass. /// [Fact] public async Task Filter_UnspacedComparison_BehavesExactlyLikeTheSpacedForm() { var spaced = new List(); var unspaced = new List(); _context.AddRoutes(r => { r.From("direct://filter-spaced") .Filter("header.amount > 1000").Process(e => spaced.Add((int)e.In.Headers["amount"]!)); r.From("direct://filter-unspaced") .Filter("header.amount>1000").Process(e => unspaced.Add((int)e.In.Headers["amount"]!)); }); await _context.Start(); foreach (var amount in new[] { 10, 1000, 1001, 5000 }) { await Send("direct://filter-spaced", WithAmount(amount)); await Send("direct://filter-unspaced", WithAmount(amount)); } unspaced.Should().Equal(spaced); unspaced.Should().Equal(1001, 5000); } [Theory] [InlineData("true", "payload")] [InlineData("false", null)] public async Task Filter_WithTemplate_KeepsHistoricalBehaviour(string headerValue, string? expected) { object? captured = null; _context.AddRoutes(r => r.From("direct://filter-template-" + headerValue) .Filter("${header.enabled}").Process(e => captured = e.In.Body)); await _context.Start(); var exchange = new Exchange(new Message("payload")); exchange.In.Headers["enabled"] = headerValue; await Send("direct://filter-template-" + headerValue, exchange); captured.Should().Be(expected); } /// /// A condition that cannot be compiled stops the route from starting. Before the unification /// it compiled to a missing-header lookup and quietly turned into "never match" on live /// traffic, with nothing in the log. /// [Fact] public async Task Filter_WithMalformedCondition_ThrowsWhileTheRouteIsBuilt() { var reached = false; _context.AddRoutes(r => r.From("direct://filter-broken").Filter("header.amount >").Process(_ => reached = true)); var start = async () => await _context.Start(); await start.Should().ThrowAsync(); reached.Should().BeFalse(); } [Fact] public async Task Filter_WithBlankCondition_ThrowsWhileTheRouteIsBuilt() { _context.AddRoutes(r => r.From("direct://filter-blank").Filter(" ").Process(_ => { })); var start = async () => await _context.Start(); await start.Should().ThrowAsync(); } [Fact] public async Task Filter_RecordsTheConditionItWasGiven() { FilterDefinition? filter = null; _context.AddRoutes(r => filter = r.From("direct://filter-source").Filter("header.amount>1000")); await _context.Start(); filter!.SourceTemplate.Should().Be("header.amount>1000"); filter.SourcePredicate.Should().NotBeNull(); filter.SourcePredicate!.Matches(WithAmount(5000)).Should().BeTrue(); filter.SourcePredicate.Matches(WithAmount(5)).Should().BeFalse(); } [Fact] public async Task Filter_NestedConfiguratorOverload_RecordsTheConditionToo() { FilterDefinition? filter = null; object? captured = null; _context.AddRoutes(r => r.From("direct://filter-nested") .Filter("header.amount>1000", f => { filter = f; f.Process(e => captured = e.In.Body); })); await _context.Start(); await Send("direct://filter-nested", WithAmount(5000)); filter!.SourceTemplate.Should().Be("header.amount>1000"); filter.SourcePredicate.Should().NotBeNull(); captured.Should().Be("payload"); } // ── When ────────────────────────────────────────────────────────────────── [Fact] public async Task When_UnspacedComparison_BehavesExactlyLikeTheSpacedForm() { var spaced = new List(); var unspaced = new List(); _context.AddRoutes(r => { r.From("direct://when-spaced").Choice() .When("header.amount > 1000").Process(_ => spaced.Add("big")).EndWhen() .Otherwise().Process(_ => spaced.Add("small")).EndChoice(); r.From("direct://when-unspaced").Choice() .When("header.amount>1000").Process(_ => unspaced.Add("big")).EndWhen() .Otherwise().Process(_ => unspaced.Add("small")).EndChoice(); }); await _context.Start(); foreach (var amount in new[] { 10, 1000, 1001, 5000 }) { await Send("direct://when-spaced", WithAmount(amount)); await Send("direct://when-unspaced", WithAmount(amount)); } unspaced.Should().Equal(spaced); unspaced.Should().Equal("small", "small", "big", "big"); } [Fact] public async Task When_RecordsTheConditionItWasGiven() { WhenDefinition? branch = null; _context.AddRoutes(r => branch = r.From("direct://when-source").Choice().When("header.amount>1000")); await _context.Start(); branch!.SourceTemplate.Should().Be("header.amount>1000"); branch.SourceExpression.Should().BeNull("a condition written as a string is not an IExpression"); branch.SourcePredicate.Should().NotBeNull(); branch.SourcePredicate!.Matches(WithAmount(5000)).Should().BeTrue(); } /// /// When reached through the route-level alias, which looks up the enclosing Choice. /// Before the unification this path recorded nothing at all. /// [Fact] public async Task AliasWhen_RecordsTheConditionItWasGiven() { WhenDefinition? branch = null; _context.AddRoutes(r => { var choice = r.From("direct://when-alias").Choice(); var nested = choice.When("header.amount>9000").Filter("header.amount>9500"); // Reached from a scope inside the When: the alias walks up to the enclosing Choice. branch = nested.When("header.amount>1000"); }); await _context.Start(); branch!.SourceTemplate.Should().Be("header.amount>1000"); branch.SourceExpression.Should().BeNull("a condition written as a string is not an IExpression"); branch.SourcePredicate.Should().NotBeNull(); branch.SourcePredicate!.Matches(WithAmount(5000)).Should().BeTrue(); branch.SourcePredicate.Matches(WithAmount(5)).Should().BeFalse(); } // ── LoopWhile ───────────────────────────────────────────────────────────── [Fact] public async Task LoopWhile_RepeatsWhileTheConditionHolds() { var iterations = 0; _context.AddRoutes(r => r.From("direct://loop-while") .LoopWhile("property.i<3") .Process(e => { iterations++; e.Properties["i"] = (int)e.Properties["i"]! + 1; }) .EndLoop()); await _context.Start(); var exchange = new Exchange(new Message("payload")); exchange.Properties["i"] = 0; await Send("direct://loop-while", exchange); iterations.Should().Be(3); exchange.Properties["i"].Should().Be(3); } [Fact] public async Task LoopWhile_NestedConfiguratorOverload_RepeatsWhileTheConditionHolds() { var iterations = 0; _context.AddRoutes(r => r.From("direct://loop-while-nested") .LoopWhile("property.i<2", loop => loop.Process(e => { iterations++; e.Properties["i"] = (int)e.Properties["i"]! + 1; })) .Process(_ => { })); await _context.Start(); var exchange = new Exchange(new Message("payload")); exchange.Properties["i"] = 0; await Send("direct://loop-while-nested", exchange); iterations.Should().Be(2); } [Fact] public async Task LoopWhile_ConditionFalseFromTheStart_RunsNothing() { var iterations = 0; _context.AddRoutes(r => r.From("direct://loop-while-none") .LoopWhile("property.i<3").Process(_ => iterations++).EndLoop()); await _context.Start(); var exchange = new Exchange(new Message("payload")); exchange.Properties["i"] = 99; await Send("direct://loop-while-none", exchange); iterations.Should().Be(0); } /// /// LoopExpression takes an iteration count, LoopWhile takes a condition. The /// same string means different things to them, which is why they must not share a name. /// [Fact] public async Task LoopWhile_IsNotTheSameAsLoopExpression() { var byCount = 0; var byCondition = 0; _context.AddRoutes(r => { r.From("direct://loop-count").Loop("${property.i}").Process(_ => byCount++).EndLoop(); r.From("direct://loop-cond").LoopWhile("property.i<3") .Process(e => { byCondition++; e.Properties["i"] = (int)e.Properties["i"]! + 1; }).EndLoop(); }); await _context.Start(); var counted = new Exchange(new Message("payload")); counted.Properties["i"] = 5; await Send("direct://loop-count", counted); var conditioned = new Exchange(new Message("payload")); conditioned.Properties["i"] = 5; await Send("direct://loop-cond", conditioned); byCount.Should().Be(5, "LoopExpression reads the value as an iteration count"); byCondition.Should().Be(0, "LoopWhile reads the same value through a condition that is already false"); } [Fact] public async Task LoopWhile_WithMalformedCondition_ThrowsWhileTheRouteIsBuilt() { _context.AddRoutes(r => r.From("direct://loop-broken") .LoopWhile("property.i <").Process(_ => { }).EndLoop()); var start = async () => await _context.Start(); await start.Should().ThrowAsync(); } // ── Validate ────────────────────────────────────────────────────────────── [Fact] public async Task Validate_WithConditionString_PassesWhenTheConditionHolds() { object? captured = null; _context.AddRoutes(r => r.From("direct://validate-ok") .Validate("header.amount>0").Process(e => captured = e.In.Body)); await _context.Start(); await Send("direct://validate-ok", WithAmount(5)); captured.Should().Be("payload"); } [Fact] public async Task Validate_WithConditionString_ThrowsOnFailure() { _context.AddRoutes(r => r.From("direct://validate-throw") .Validate("header.amount>0", "amount must be positive").Process(_ => { })); await _context.Start(); var send = async () => await Send("direct://validate-throw", WithAmount(-1)); (await send.Should().ThrowAsync()) .WithMessage("*amount must be positive*"); } [Fact] public async Task Validate_WithConditionString_FlagsWhenNotThrowing() { _context.AddRoutes(r => r.From("direct://validate-soft") .Validate("header.amount>0", "amount must be positive", throwOnFailure: false) .Process(_ => { })); await _context.Start(); var exchange = await Send("direct://validate-soft", WithAmount(-1)); exchange.Properties[ValidateProcessor.ValidationResultProperty].Should().Be(false); exchange.Properties[ValidateProcessor.ValidationErrorsProperty].Should().Be("amount must be positive"); } [Fact] public async Task Validate_WithMalformedCondition_ThrowsWhileTheRouteIsBuilt() { _context.AddRoutes(r => r.From("direct://validate-broken").Validate("header.amount >").Process(_ => { })); var start = async () => await _context.Start(); await start.Should().ThrowAsync(); } } Path: redb-route/tests/redb.Route.Tests/Dsl/StringOverloadsF13Tests.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/Dsl/StringOverloadsF13Tests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Components; using redb.Route.Aggregation; using redb.Route.Core; using redb.Route.Definitions; using redb.Route.Processors; using redb.Route.Processors.LoadBalancer; namespace redb.Route.Tests.Dsl; /// /// String overloads on the remaining lambda-only EIPs. Each test mirrors the /// behaviour of the lambda form through a compiled route; a malformed expression fails at build /// (the StringExpression compiles at declaration). /// public class StringOverloadsF13Tests : IAsyncLifetime { private readonly RouteContext _context = new(); public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { await _context.DisposeAsync(); GC.SuppressFinalize(this); } private async Task StartAndProducer(string fromUri) { await _context.Start(); var producer = _context.GetEndpoint(fromUri).CreateProducer(); await producer.Start(); return producer; } 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; } // ── RecipientList(string) ──────────────────────────────────────────────── [Fact] public async Task RecipientList_FromDelimitedHeader_RoutesToEveryUri() { var seen = new List(); _context.AddRoutes(r => { r.From("direct://f13-rcpt-in").RecipientList("${header.targets}"); r.From("direct://f13-rcpt-a").Process(_ => seen.Add("a")); r.From("direct://f13-rcpt-b").Process(_ => seen.Add("b")); }); var producer = await StartAndProducer("direct://f13-rcpt-in"); await producer.Process(Msg("x", ("targets", "direct://f13-rcpt-a, direct://f13-rcpt-b"))); seen.Should().BeEquivalentTo(["a", "b"]); } [Fact] public async Task RecipientList_FromCollectionHeader_RoutesToEveryUri() { var seen = new List(); _context.AddRoutes(r => { r.From("direct://f13-rcpt2-in").RecipientList("${header.targets}"); r.From("direct://f13-rcpt2-a").Process(_ => seen.Add("a")); r.From("direct://f13-rcpt2-b").Process(_ => seen.Add("b")); }); var producer = await StartAndProducer("direct://f13-rcpt2-in"); await producer.Process(Msg("x", ("targets", new List { "direct://f13-rcpt2-a", "direct://f13-rcpt2-b" }))); seen.Should().BeEquivalentTo(["a", "b"]); } // ── DynamicRouter(string) ──────────────────────────────────────────────── [Fact] public async Task DynamicRouter_PureExpressionOverSteppedProperty_VisitsHopsInOrderAndStops() { var visited = new List(); _context.AddRoutes(r => { // The XML idiom from examples/eip.route.xml: the router expression is pure, the hops // advance the step property themselves. r.From("direct://f13-dr-in") .SetProperty("step", 0) .DynamicRouter("property.step == 0 ? 'direct://f13-dr-a' : (property.step == 1 ? 'direct://f13-dr-b' : null)"); r.From("direct://f13-dr-a").Process(e => { visited.Add("a"); e.Properties["step"] = 1; }); r.From("direct://f13-dr-b").Process(e => { visited.Add("b"); e.Properties["step"] = 2; }); }); var producer = await StartAndProducer("direct://f13-dr-in"); await producer.Process(Msg("x")); visited.Should().Equal("a", "b"); } // ── Resequence(string) ─────────────────────────────────────────────────── [Fact] public async Task Resequence_ByHeaderExpression_DeliversInKeyOrder() { var order = new List(); _context.AddRoutes(r => { r.From("direct://f13-rseq-in") .Resequence("header.seq", batchSize: 3) .Process(e => order.Add(e.In.Body)); }); var producer = await StartAndProducer("direct://f13-rseq-in"); await producer.Process(Msg("third", ("seq", 3))); await producer.Process(Msg("first", ("seq", 1))); await producer.Process(Msg("second", ("seq", 2))); order.Should().Equal("first", "second", "third"); } // ── Debounce(string) ───────────────────────────────────────────────────── [Fact] public async Task Debounce_ByKeyExpression_ForwardsOnlyTheLastAfterQuiet() { var received = new List(); _context.AddRoutes(r => { r.From("direct://f13-deb-in") .Debounce("header.device", TimeSpan.FromMilliseconds(100)) .Process(e => received.Add(e.In.Body)); }); var producer = await StartAndProducer("direct://f13-deb-in"); await producer.Process(Msg("v1", ("device", "d1"))); await producer.Process(Msg("v2", ("device", "d1"))); await producer.Process(Msg("v3", ("device", "d1"))); await WaitUntil(() => received.Count == 1, TimeSpan.FromSeconds(3)); received.Should().Equal("v3"); } // ── IdempotentConsumer(string, string) ─────────────────────────────────── [Fact] public async Task IdempotentConsumer_KeyExpressionAndRegistryName_SkipsDuplicates() { var processed = new List(); _context.AddIdempotentRepository("f13-idemp-repo", new InMemoryIdempotentRepository()); _context.AddRoutes(r => { r.From("direct://f13-idemp-in") .IdempotentConsumer("${header.messageId}", "f13-idemp-repo") .Process(e => processed.Add(e.In.Body)); }); var producer = await StartAndProducer("direct://f13-idemp-in"); await producer.Process(Msg("first", ("messageId", "m-1"))); await producer.Process(Msg("dup", ("messageId", "m-1"))); await producer.Process(Msg("second", ("messageId", "m-2"))); processed.Should().Equal("first", "second"); } // ── Aggregate(string, ...) ─────────────────────────────────────────────── [Fact] public async Task Aggregate_CorrelationExpressionAndCompletionSize_GroupsBodies() { var batches = new List>(); _context.AddRoutes(r => { r.From("direct://f13-agg-in") .Aggregate("${header.batch}", AggregationStrategies.GroupedBody(), completionSize: 3) .Process(e => batches.Add(new List((List)e.In.Body!))); }); var producer = await StartAndProducer("direct://f13-agg-in"); await producer.Process(Msg("a", ("batch", "b1"))); await producer.Process(Msg("b", ("batch", "b1"))); await producer.Process(Msg("c", ("batch", "b1"))); batches.Should().ContainSingle().Which.Should().Equal("a", "b", "c"); } [Fact] public async Task Aggregate_CompletionCondition_CompletesWhenTheConditionHolds() { var results = new List(); _context.AddRoutes(r => { r.From("direct://f13-aggc-in") .Aggregate("${header.batch}", AggregationStrategies.Concat("+"), completionCondition: "contains(body, '+')") .Process(e => results.Add(e.In.Body)); }); var producer = await StartAndProducer("direct://f13-aggc-in"); await producer.Process(Msg("a", ("batch", "b1"))); await producer.Process(Msg("b", ("batch", "b1"))); results.Should().ContainSingle().Which.Should().Be("a+b"); } [Fact] public async Task Aggregate_CompletionTimeout_FlushesTheGroupWithWhatItHas() { var batches = new List>(); _context.AddRoutes(r => { r.From("direct://f13-aggt-in") .Aggregate("${header.batch}", AggregationStrategies.GroupedBody(), completionSize: 100, completionTimeout: TimeSpan.FromMilliseconds(150)) .Process(e => batches.Add(new List((List)e.In.Body!))); }); var producer = await StartAndProducer("direct://f13-aggt-in"); await producer.Process(Msg("a", ("batch", "b1"))); await producer.Process(Msg("b", ("batch", "b1"))); await WaitUntil(() => batches.Count == 1, TimeSpan.FromSeconds(5)); batches.Should().ContainSingle().Which.Should().Equal("a", "b"); } [Fact] public async Task Aggregate_CompletionTimeout_DoesNotFlushAfterTheContextIsDisposed() { // Review: the scan timer must die with the context. Before the fix nothing disposed // processors at all (the resequencer's DisposeAsync was dead code), so a pending group // was flushed into a stopped pipeline by a background timer that lived forever. var flushed = 0; var context = new RouteContext(); context.AddRoutes(r => r.From("direct://f13-aggd-in") .Aggregate("${header.batch}", AggregationStrategies.GroupedBody(), completionSize: 100, completionTimeout: TimeSpan.FromMilliseconds(200)) .Process(_ => Interlocked.Increment(ref flushed))); await context.Start(); var producer = context.GetEndpoint("direct://f13-aggd-in").CreateProducer(); await producer.Start(); await producer.Process(Msg("a", ("batch", "b1"))); // the group stays pending await context.DisposeAsync(); await Task.Delay(600); // well past the inactivity timeout flushed.Should().Be(0, "a disposed context must not flush pending groups from a background timer"); } [Fact] public async Task Aggregate_WithoutAnyCompletionCriterion_IsRefusedWhenTheBuilderRuns() { // Review: the first version of this test discarded an un-awaited ThrowAsync and was // green no matter what. Builder lambdas are deferred, so the declaration error surfaces // at Start() — and the assertion must actually await it. _context.AddRoutes(r => r.From("direct://f13-aggx-in") .Aggregate("${header.batch}", AggregationStrategies.GroupedBody())); var act = () => _context.Start(); (await act.Should().ThrowAsync()) .WithMessage("*at least one completion criterion*"); } // ── OfType(Type) ───────────────────────────────────────────────────────── [Fact] public async Task OfType_NonGeneric_BuildsTheSameTypedSectionAsTheGenericForm() { // OfType is a typed-view section, not a guard: the body converts to T and typed // helpers run only for matching bodies. The non-generic form's contract is parity of // construction — the same closed OfTypeDefinition the generic verb creates. var seen = new List(); _context.AddRoutes(r => { var section = r.From("direct://f13-oftype-in").OfType(typeof(int)); section.Should().BeOfType>(); section.Process(e => seen.Add(e.In.Body)); }); var producer = await StartAndProducer("direct://f13-oftype-in"); await producer.Process(Msg("42")); // ConvertBody inside the section: "42" becomes int 42 seen.Should().ContainSingle().Which.Should().Be(42); } // ── RoutePolicy(string) ────────────────────────────────────────────────── private sealed class RecordingPolicy : IRoutePolicy { public int Started; public Task OnStart(IRouteContext context, CompiledRoute route, CancellationToken ct) { Interlocked.Increment(ref Started); return Task.CompletedTask; } } [Fact] public async Task RoutePolicy_ByRegistryName_ResolvesAtCompile() { var policy = new RecordingPolicy(); _context.AddToRegistry("f13-policy", policy); _context.AddRoutes(r => r.From("direct://f13-pol-in").RoutePolicy("#f13-policy").Process(_ => { })); await _context.Start(); policy.Started.Should().Be(1); } [Fact] public async Task RoutePolicy_MissingRegistryName_FailsStartNamingTheRoute() { _context.AddRoutes(r => r.From("direct://f13-polx-in").RouteId("f13-polx").RoutePolicy("absent-policy").Process(_ => { })); var act = () => _context.Start(); (await act.Should().ThrowAsync()) .WithMessage("*f13-polx*absent-policy*not in the context registry*"); } // ── UseSticky(string) / Normalizer.When(string) ────────────────────────── [Fact] public void UseSticky_KeyExpression_SelectsTheStickyStrategy() { var lb = new LoadBalancerDefinition(); lb.UseSticky("header.customerId"); lb.Strategy.Should().BeOfType(); } [Fact] public async Task NormalizerWhen_ConditionString_TransformsMatchingBodies() { _context.AddRoutes(r => r.From("direct://f13-norm-in") .Normalize(n => n .When("header.kind == 'greeting'", e => $"hello:{e.In.Body}") .Otherwise(e => $"other:{e.In.Body}")) .Process(_ => { })); var producer = await StartAndProducer("direct://f13-norm-in"); var greeting = Msg("bob", ("kind", "greeting")); var other = Msg("bob", ("kind", "misc")); await producer.Process(greeting); await producer.Process(other); greeting.In.Body.Should().Be("hello:bob"); other.In.Body.Should().Be("other:bob"); } // ── Fail-fast: a malformed expression fails while the route is built ───── [Fact] public async Task MalformedKeyExpression_FailsAtBuild_NotOnTheFirstMessage() { _context.AddRoutes(r => r.From("direct://f13-bad-in").Debounce("header.a >", TimeSpan.FromMilliseconds(50))); var act = () => _context.Start(); await act.Should().ThrowAsync("a malformed expression must fail Start(), not the first message"); } private static async Task WaitUntil(Func condition, TimeSpan timeout) { var deadline = DateTime.UtcNow + timeout; while (!condition() && DateTime.UtcNow < deadline) await Task.Delay(25); condition().Should().BeTrue($"condition not reached within {timeout}"); } } Path: redb-route/tests/redb.Route.Tests/Dsl/ThrottleDynamicLimitTests.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/Dsl/ThrottleDynamicLimitTests.cs ---- using System.Diagnostics; using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Expressions; namespace redb.Route.Tests.Dsl; /// /// The throttle limit is computed per message. Until 2026-08-29 ThrottleExpression /// evaluated its template once at route build against an empty exchange and silently fell back /// to int.MaxValue, so ${header.rate} throttled nothing at all. /// [Collection("ExpressionResolver")] public class ThrottleDynamicLimitTests : IAsyncLifetime { private readonly RouteContext _context = new(); public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { await _context.DisposeAsync(); GC.SuppressFinalize(this); } private async Task Send(string uri, int rate) { var exchange = new Exchange(new Message("payload")); exchange.In.Headers["rate"] = rate; var producer = _context.GetEndpoint(uri).CreateProducer(); await producer.Start(); await producer.Process(exchange); return exchange; } /// /// Red before the fix: the limit used to be int.MaxValue whatever the header said, so the /// second message was never rejected. /// [Fact] public async Task ThrottleExpression_ReadsTheLimitFromTheMessage() { var reached = 0; _context.AddRoutes(r => r.From("direct://throttle-dyn-reject") .Throttle("${header.rate}", TimeSpan.FromSeconds(10)).RejectOnOverflow() .Process(_ => Interlocked.Increment(ref reached)) .EndThrottle()); await _context.Start(); await Send("direct://throttle-dyn-reject", 1); await Send("direct://throttle-dyn-reject", 1); reached.Should().Be(1, "the second message exceeds a limit of one per period and is rejected"); } /// The limit belongs to the message: a later message with a larger limit gets in. [Fact] public async Task ThrottleExpression_LimitChangesBetweenMessages() { var reached = 0; _context.AddRoutes(r => r.From("direct://throttle-dyn-grow") .Throttle("${header.rate}", TimeSpan.FromSeconds(10)).RejectOnOverflow() .Process(_ => Interlocked.Increment(ref reached)) .EndThrottle()); await _context.Start(); await Send("direct://throttle-dyn-grow", 1); // occupies the single slot await Send("direct://throttle-dyn-grow", 1); // rejected: one slot, one occupant await Send("direct://throttle-dyn-grow", 3); // its own limit is three: room for it reached.Should().Be(2); } [Fact] public async Task ThrottleExpression_WithExpressionForm_Works() { var reached = 0; _context.AddRoutes(r => r.From("direct://throttle-dyn-expr") .Throttle("header.rate * 2", TimeSpan.FromSeconds(10)).RejectOnOverflow() .Process(_ => Interlocked.Increment(ref reached)) .EndThrottle()); await _context.Start(); await Send("direct://throttle-dyn-expr", 1); await Send("direct://throttle-dyn-expr", 1); await Send("direct://throttle-dyn-expr", 1); reached.Should().Be(2, "rate 1 * 2 gives two slots per period"); } [Fact] public async Task ThrottleExpression_WaitsForASlotWhenNotRejecting() { var period = TimeSpan.FromMilliseconds(300); _context.AddRoutes(r => r.From("direct://throttle-dyn-wait") .Throttle("${header.rate}", period) .Process(_ => { }) .EndThrottle()); await _context.Start(); var stopwatch = Stopwatch.StartNew(); await Send("direct://throttle-dyn-wait", 1); await Send("direct://throttle-dyn-wait", 1); stopwatch.Stop(); stopwatch.Elapsed.Should().BeGreaterThanOrEqualTo(period - TimeSpan.FromMilliseconds(50), "the second message waits for the slot released after one period"); } [Fact] public async Task ThrottleExpression_WithMalformedTemplate_ThrowsWhileTheRouteIsBuilt() { _context.AddRoutes(r => r.From("direct://throttle-dyn-broken") .Throttle("header.rate >", TimeSpan.FromSeconds(1)).Process(_ => { }).EndThrottle()); var start = async () => await _context.Start(); await start.Should().ThrowAsync(); } [Fact] public async Task ThrottleExpression_WithNonPositiveLimit_FailsThatExchangeLoudly() { _context.AddRoutes(r => r.From("direct://throttle-dyn-zero") .Throttle("${header.rate}", TimeSpan.FromSeconds(1)).Process(_ => { }).EndThrottle()); await _context.Start(); var send = async () => await Send("direct://throttle-dyn-zero", 0); await send.Should().ThrowAsync(); } /// The fixed-limit form is untouched by the change. [Fact] public async Task Throttle_WithFixedLimit_StillRejectsOverflow() { var reached = 0; _context.AddRoutes(r => r.From("direct://throttle-fixed") .Throttle(2).Period(TimeSpan.FromSeconds(10)).RejectOnOverflow() .Process(_ => Interlocked.Increment(ref reached)) .EndThrottle()); await _context.Start(); for (var i = 0; i < 5; i++) await Send("direct://throttle-fixed", 99); reached.Should().Be(2); } } Path: redb-route/tests/redb.Route.Tests/Dsl/TruthinessEndToEndTests.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/Dsl/TruthinessEndToEndTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Tests.Dsl; /// /// End-to-end coverage of the single truthiness rule on live routes: real RouteContext, real /// producers, real messages. Unit-level coverage lives in the characterisation snapshot; these /// tests prove the rule reaches the wire — a zero header actually drops a message, a "yes" /// header actually routes a branch. /// [Collection("ExpressionResolver")] public class TruthinessEndToEndTests : IAsyncLifetime { private readonly RouteContext _context = new(); public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { await _context.DisposeAsync(); GC.SuppressFinalize(this); } private async Task Send(string uri, object? headerValue) { var exchange = new Exchange(new Message("payload")); if (headerValue is not null) exchange.In.Headers["v"] = headerValue; var producer = _context.GetEndpoint(uri).CreateProducer(); await producer.Start(); await producer.Process(exchange); return exchange; } // ── Filter over a bare accessor ─────────────────────────────────────────── [Theory] [InlineData(0, false)] [InlineData(1, true)] [InlineData(-1, true)] [InlineData(0.0, false)] [InlineData(2.5, true)] [InlineData(true, true)] [InlineData(false, false)] [InlineData("", false)] [InlineData("0", false)] [InlineData("1", true)] [InlineData("no", false)] [InlineData("yes", true)] [InlineData("off", false)] [InlineData("on", true)] [InlineData("false", false)] [InlineData("true", true)] [InlineData("anything", true)] public async Task Filter_BareAccessor_FollowsTheOneTruthinessRule(object value, bool shouldPass) { var passed = false; var uri = "direct://truth-" + Guid.NewGuid().ToString("N"); _context.AddRoutes(r => r.From(uri).Filter("header.v").Process(_ => passed = true)); await _context.Start(); await Send(uri, value); passed.Should().Be(shouldPass, $"header value {value} ({value.GetType().Name}) reads as {shouldPass}"); } [Fact] public async Task Filter_MissingHeader_IsFalse() { var passed = false; _context.AddRoutes(r => r.From("direct://truth-missing").Filter("header.v").Process(_ => passed = true)); await _context.Start(); await Send("direct://truth-missing", null); passed.Should().BeFalse(); } // ── The same rule through a template placeholder ────────────────────────── [Theory] [InlineData(0, false)] [InlineData(7, true)] [InlineData("no", false)] [InlineData("anything", true)] public async Task Filter_WholeStringPlaceholder_AgreesWithTheBareAccessor(object value, bool shouldPass) { var passed = false; var uri = "direct://truth-tpl-" + Guid.NewGuid().ToString("N"); _context.AddRoutes(r => r.From(uri).Filter("${header.v}").Process(_ => passed = true)); await _context.Start(); await Send(uri, value); passed.Should().Be(shouldPass); } // ── The same rule inside the expression language ────────────────────────── [Theory] [InlineData("logical(header.v)")] [InlineData("header.v AND true")] [InlineData("NOT (NOT header.v)")] public async Task Filter_WordLogicAndLogicalFunction_AgreeWithTheBareAccessor(string condition) { var zeroPassed = false; var sevenPassed = false; var uriZero = "direct://truth-z-" + condition.GetHashCode().ToString("x"); var uriSeven = "direct://truth-s-" + condition.GetHashCode().ToString("x"); _context.AddRoutes(r => { r.From(uriZero).Filter(condition).Process(_ => zeroPassed = true); r.From(uriSeven).Filter(condition).Process(_ => sevenPassed = true); }); await _context.Start(); await Send(uriZero, 0); await Send(uriSeven, 7); zeroPassed.Should().BeFalse("zero is false everywhere"); sevenPassed.Should().BeTrue("a non-zero number is true everywhere"); } // ── Choice takes the branch the rule dictates ───────────────────────────── [Theory] [InlineData(0, "otherwise")] [InlineData(3, "when")] [InlineData("no", "otherwise")] [InlineData("yes", "when")] public async Task Choice_RoutesByTheSameRule(object value, string expectedBranch) { string? taken = null; var uri = "direct://truth-choice-" + Guid.NewGuid().ToString("N"); _context.AddRoutes(r => r.From(uri).Choice() .When("header.v").Process(_ => taken = "when").EndWhen() .Otherwise().Process(_ => taken = "otherwise").EndChoice()); await _context.Start(); await Send(uri, value); taken.Should().Be(expectedBranch); } // ── Equality is not truthiness ──────────────────────────────────────────── /// /// The strict boundary that keeps the total rule safe: 42 and "x" are both truthy, but /// 42 == 'x' must stay false — coercion to boolean happens in equality only for explicit /// boolean words, bools and numbers. /// [Fact] public async Task Equality_DoesNotCoerceThroughTruthiness() { var passed = false; _context.AddRoutes(r => r.From("direct://truth-eq").Filter("header.v == 'x'").Process(_ => passed = true)); await _context.Start(); await Send("direct://truth-eq", 42); passed.Should().BeFalse("42 == 'x' compares values, not truthiness"); } } Path: redb-route/tests/redb.Route.Tests/Dsl/V4BreakingChangesTests.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/Dsl/V4BreakingChangesTests.cs ---- using System.Diagnostics; using redb.Route.Core; using redb.Route.TestKit; namespace redb.Route.Tests.Dsl; /// The 4.0 breaking bundle: string verbs that replaced the *Expression(string) synonyms, and the consumer-URI guard. public class V4BreakingChangesTests { private static readonly TimeSpan Wait = TimeSpan.FromSeconds(2); [Fact] public async Task Loop_String_CountsFromTheMessage() { var iterations = 0; await using var ctx = new RouteContext().AddRoutes(b => b .From("direct://loop").Loop("${header.count}").Process(_ => Interlocked.Increment(ref iterations)).EndLoop()); await ctx.Start(); await ctx.SendBodyAndHeader("direct://loop", "x", "count", 3); await ctx.SendBodyAndHeader("direct://loop", "x", "count", 2); iterations.Should().Be(5); } [Fact] public async Task Loop_String_BareExpression_Works() { var iterations = 0; await using var ctx = new RouteContext().AddRoutes(b => b .From("direct://loop2").Loop("header.count * 2").Process(_ => Interlocked.Increment(ref iterations)).EndLoop()); await ctx.Start(); await ctx.SendBodyAndHeader("direct://loop2", "x", "count", 2); iterations.Should().Be(4); } [Fact] public async Task Delay_String_MillisecondsFromTheMessage() { await using var ctx = new RouteContext().AddRoutes(b => b.From("direct://delay").Delay("${header.ms}").To("mock://delayed")); await ctx.Start(); var clock = Stopwatch.StartNew(); await ctx.SendBodyAndHeader("direct://delay", "x", "ms", 150); clock.Elapsed.Should().BeGreaterThanOrEqualTo(TimeSpan.FromMilliseconds(120)); await ctx.Mock("mock://delayed").ExpectMessageCount(1).AssertIsSatisfiedAsync(Wait); } [Fact] public async Task Throttle_String_LimitFromTheMessage() { await using var ctx = new RouteContext().AddRoutes(b => b .From("direct://thr").Throttle("${header.rate}", TimeSpan.FromSeconds(10)).RejectOnOverflow().To("mock://thr").EndThrottle()); await ctx.Start(); for (var i = 0; i < 5; i++) await ctx.SendBodyAndHeader("direct://thr", i, "rate", 2); await ctx.Mock("mock://thr").ExpectMessageCount(2).AssertIsSatisfiedAsync(Wait); } [Fact] public async Task Throttle_String_MalformedExpression_FailsAtStart() { await using var ctx = new RouteContext().AddRoutes(b => b.From("direct://thr-bad").Throttle("max(header.rate, ", TimeSpan.FromSeconds(1)).EndThrottle()); var act = () => ctx.Start(); await act.Should().ThrowAsync(); } [Fact] public async Task DollarPlaceholder_InConsumerUri_FailsAtStart() { await using var ctx = new RouteContext().AddRoutes(b => b.From("direct://in-${header.tenant}").To("mock://x")); var act = () => ctx.Start(); await act.Should().ThrowAsync().WithMessage("*consumer URI*${...}*no message*"); } } Path: redb-route/tests/redb.Route.Tests/Dsl/ValueAndValidateEndToEndTests.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/Dsl/ValueAndValidateEndToEndTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Expressions; using redb.Route.Validation; namespace redb.Route.Tests.Dsl; /// /// Closes the last two seams of the unification on live routes: Validate awaits its /// predicate like every other branching scope, and an explicit expression in the value position /// reads an operator without caring about the whitespace around it. /// [Collection("ExpressionResolver")] public class ValueAndValidateEndToEndTests : IAsyncLifetime { private readonly RouteContext _context = new(); public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { await _context.DisposeAsync(); GC.SuppressFinalize(this); } /// A predicate that is only ever right asynchronously. private sealed class AsyncOnlyPredicate(Func decide) : IPredicate { public int AsyncCalls { get; private set; } public bool Matches(IExchange exchange) => throw new InvalidOperationException("The engine must await MatchesAsync, not call Matches."); public async Task MatchesAsync(IExchange exchange) { await Task.Yield(); AsyncCalls++; return decide(exchange); } } private async Task SendAmount(string uri, int amount) { var exchange = new Exchange(new Message("payload")); exchange.In.Headers["amount"] = amount; var producer = _context.GetEndpoint(uri).CreateProducer(); await producer.Start(); await producer.Process(exchange); return exchange; } // ── Validate awaits the predicate ───────────────────────────────────────── [Fact] public async Task Validate_AwaitsThePredicate_AndPassesWhenItHolds() { var predicate = new AsyncOnlyPredicate(e => (int)e.In.Headers["amount"]! > 0); var reached = false; _context.AddRoutes(r => r.From("direct://validate-async-ok") .Validate(predicate, "amount must be positive") .Process(_ => reached = true)); await _context.Start(); await SendAmount("direct://validate-async-ok", 5); reached.Should().BeTrue(); predicate.AsyncCalls.Should().Be(1); } [Fact] public async Task Validate_AwaitsThePredicate_AndThrowsWhenItDoesNot() { var predicate = new AsyncOnlyPredicate(e => (int)e.In.Headers["amount"]! > 0); _context.AddRoutes(r => r.From("direct://validate-async-throw") .Validate(predicate, "amount must be positive") .Process(_ => { })); await _context.Start(); var send = async () => await SendAmount("direct://validate-async-throw", -1); (await send.Should().ThrowAsync()).WithMessage("*amount must be positive*"); predicate.AsyncCalls.Should().Be(1); } [Fact] public async Task Validate_FromConditionString_StillWorksThroughTheSamePath() { var exchange = default(IExchange); _context.AddRoutes(r => r.From("direct://validate-string-soft") .Validate("header.amount>0", "amount must be positive", throwOnFailure: false) .Process(e => exchange = e)); await _context.Start(); await SendAmount("direct://validate-string-soft", -1); exchange!.Properties[ValidateProcessor.ValidationResultProperty].Should().Be(false); } // ── Value position: whitespace is not part of the language ──────────────── [Theory] [InlineData("header.amount>1000")] [InlineData("header.amount > 1000")] [InlineData("header.amount\t>\t1000")] [InlineData("header.amount>1000 AND header.amount<9000")] public async Task SetHeader_WithExplicitExpression_ReadsTheOperatorWhateverTheSpacing(string expression) { var uri = "direct://value-expr-" + Guid.NewGuid().ToString("N"); _context.AddRoutes(r => r.From(uri).SetHeader("big", new StringExpression(expression)).Process(_ => { })); await _context.Start(); (await SendAmount(uri, 5000)).In.Headers["big"].Should().Be(true); (await SendAmount(uri, 10)).In.Headers["big"].Should().Be(false); } /// /// The other half of the same rule: a plain string in the value position is a literal, /// whatever operator-looking characters it carries. Only an explicit expression is parsed. /// [Theory] [InlineData("a>b")] [InlineData("black and white")] [InlineData("dGVzdC1zZWNyZXQ==")] public async Task SetHeader_WithPlainString_StaysALiteral(string literal) { var uri = "direct://value-literal-" + Guid.NewGuid().ToString("N"); _context.AddRoutes(r => r.From(uri).SetHeader("v", literal).Process(_ => { })); await _context.Start(); (await SendAmount(uri, 1)).In.Headers["v"].Should().Be(literal); } } Path: redb-route/tests/redb.Route.Tests/Eip/CompletionVerdictTests.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/Eip/CompletionVerdictTests.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.TestKit; namespace redb.Route.Tests.Eip; /// /// OnCompletion blocks and the exchange events reach the consumer's verdict. A route whose OnException has no /// Handled returns normally with the failure left on the exchange, and .RollbackAll() returns normally with /// the exchange marked rollback-only: the consumer does not acknowledge either, so neither is a completion. /// public class CompletionVerdictTests { private static readonly TimeSpan Wait = TimeSpan.FromSeconds(2); private static async Task Start(RouteContext context, string uri) { await context.Start(); var producer = context.GetEndpoint(uri).CreateProducer(); await producer.Start(); return producer; } private sealed class Outcomes : IRouteLifecycleListener { public readonly List Seen = []; public Task OnExchangeCompleted(string routeId, IExchange exchange, CancellationToken ct) { lock (Seen) Seen.Add("completed"); return Task.CompletedTask; } public Task OnExchangeFailed(string routeId, IExchange exchange, Exception exception, CancellationToken ct) { lock (Seen) Seen.Add($"failed: {exception.Message}"); return Task.CompletedTask; } } [Fact] public async Task OnCompletion_takes_a_failure_left_unhandled_on_the_exchange_for_a_failure() { var failures = new List(); var completions = 0; await using var context = new RouteContext(); context.AddRoutes(r => r .From("direct://v-unhandled") .OnException() .Log("seen, not handled") .End() .OnCompletion().OnFailureOnly().ModeBeforeConsumer().Process(e => failures.Add(e.Exception?.Message)).EndOnCompletion() .OnCompletion().OnCompleteOnly().ModeBeforeConsumer().Process(_ => completions++).EndOnCompletion() .Process(_ => throw new InvalidOperationException("boom"))); var producer = await Start(context, "direct://v-unhandled"); await producer.Process(new Exchange(new Message("x"))); failures.Should().Equal("boom"); completions.Should().Be(0, "the consumer does not acknowledge this exchange"); } [Fact] public async Task OnCompletion_takes_a_rollback_only_exchange_for_a_failure() { var completions = 0; await using var context = new RouteContext(); context.AddRoutes(r => r .From("direct://v-rollback") .OnCompletion().OnFailureOnly().To("mock://v-rollback-failed").EndOnCompletion() .OnCompletion().OnCompleteOnly().ModeBeforeConsumer().Process(_ => completions++).EndOnCompletion() .RollbackAll()); var producer = await Start(context, "direct://v-rollback"); await producer.Process(new Exchange(new Message("x"))); await context.Mock("mock://v-rollback-failed").ExpectMessageCount(1).AssertIsSatisfiedAsync(Wait); completions.Should().Be(0, "OnCompleteOnly must not run for a rolled-back exchange"); } [Fact] public async Task The_events_report_a_failure_left_unhandled_on_the_exchange_as_failed() { var outcomes = new Outcomes(); await using var context = new RouteContext(); context.AddLifecycleListener(outcomes); context.AddRoutes(r => r .From("direct://v-events-unhandled") .OnException() .Log("seen, not handled") .End() .Process(_ => throw new InvalidOperationException("boom"))); var producer = await Start(context, "direct://v-events-unhandled"); await producer.Process(new Exchange(new Message("x"))); outcomes.Seen.Should().Equal("failed: boom"); } [Fact] public async Task The_events_report_a_rollback_only_exchange_as_failed() { var outcomes = new Outcomes(); await using var context = new RouteContext(); context.AddLifecycleListener(outcomes); context.AddRoutes(r => r .From("direct://v-events-rollback") .RollbackAll()); var producer = await Start(context, "direct://v-events-rollback"); await producer.Process(new Exchange(new Message("x"))); outcomes.Seen.Should().ContainSingle().Which.Should().StartWith("failed: ").And.Contain("rollback-only"); } [Fact] public async Task A_handled_failure_stays_a_completion() { var outcomes = new Outcomes(); var completions = 0; await using var context = new RouteContext(); context.AddLifecycleListener(outcomes); context.AddRoutes(r => r .From("direct://v-handled") .OnException() .Handled() .End() .OnCompletion().OnCompleteOnly().ModeBeforeConsumer().Process(_ => completions++).EndOnCompletion() .Process(_ => throw new InvalidOperationException("boom"))); var producer = await Start(context, "direct://v-handled"); await producer.Process(new Exchange(new Message("x"))); completions.Should().Be(1); outcomes.Seen.Should().Equal("completed"); } } Path: redb-route/tests/redb.Route.Tests/Eip/InterceptReviewTests.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/Eip/InterceptReviewTests.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.TestKit; namespace redb.Route.Tests.Eip; /// /// Defects from the 2026-09-01 code review: the target URI an interception publishes in headers is sanitized, /// and a blank From mask is refused where it is declared instead of silently dropping the route at compile. /// public class InterceptReviewTests { [Fact] public async Task InterceptSendToEndpoint_PublishesTheTargetWithoutThePassword() { await using var ctx = new RouteContext().AddRoutes(b => b .From("direct://secret") .InterceptSendToEndpoint("amqp://*").To("mock://tap").SkipSendToOriginalEndpoint().EndIntercept() .To("amqp://user:s3cret@broker/orders")); await ctx.Start(); await ctx.SendBody("direct://secret", "x"); var properties = ctx.Mock("mock://tap").ReceivedExchanges[0].Properties; properties[ExchangePropertyKeys.ToEndpoint].Should().Be(EndpointUri.Sanitize("amqp://user:s3cret@broker/orders")); properties[ExchangePropertyKeys.ToEndpoint]!.ToString().Should().NotContain("s3cret", "exchange properties reach logs, traces and the dashboard"); ctx.Mock("mock://tap").ReceivedExchanges[0].In.Headers.Should().NotContainKey("CamelToEndpoint").And.NotContainKey("redb.toEndpoint"); } [Fact] public async Task InterceptFrom_BlankMask_IsRefusedAtDeclaration() { await using var ctx = new RouteContext(); var act = async () => { ctx.AddRoutes(b => { b.InterceptFrom(" ").SetHeader("x", 1); b.From("direct://blank").To("mock://blank"); }); await ctx.Start(); }; await act.Should().ThrowAsync().WithMessage("*InterceptFrom*"); } // Second batch of the review (intercept order, {{config}} targets, dynamic targets, regex masks). [Fact] public async Task Intercepts_RunInDeclarationOrder_BuilderLevelFirst() { var order = new List(); await using var ctx = new RouteContext().AddRoutes(b => { b.Intercept().Process(_ => order.Add("builder")); b.From("direct://order") .Intercept().Process(_ => order.Add("A")).EndIntercept() .Intercept().Process(_ => order.Add("B")).EndIntercept() .SetHeader("x", 1); }); await ctx.Start(); await ctx.SendBody("direct://order", "m"); order.Should().Equal("builder", "A", "B"); } [Fact] public async Task InterceptSendToEndpoint_MatchesAConfigPlaceholderTarget_ByItsResolvedUri() { await using var ctx = new RouteContext(); ctx.SetProperty("audit.endpoint", "kafka://audit"); // container-free {{key}} source ctx.AddRoutes(b => b .From("direct://cfg") .InterceptSendToEndpoint("kafka://*").To("mock://cfg-tap").SkipSendToOriginalEndpoint().EndIntercept() .To("{{audit.endpoint}}")); await ctx.Start(); await ctx.SendBody("direct://cfg", "m"); // unmatched, the real kafka send would fail: no such component here await ctx.Mock("mock://cfg-tap").ExpectMessageCount(1).ExpectProperty(ExchangePropertyKeys.ToEndpoint, "kafka://audit").AssertIsSatisfiedAsync(TimeSpan.FromSeconds(2)); } [Fact] public async Task InterceptSendToEndpoint_EvaluatesADynamicTargetOnce() { var evaluations = 0; await using var ctx = new RouteContext().AddRoutes(b => b .From("direct://once") .InterceptSendToEndpoint("mock://*").SetHeader("tapped", true).EndIntercept() .ToD(_ => { Interlocked.Increment(ref evaluations); return "mock://dyn-once"; })); await ctx.Start(); await ctx.SendBody("direct://once", "m"); evaluations.Should().Be(1, "the wrapper resolves the target and the send uses that very URI"); await ctx.Mock("mock://dyn-once").ExpectMessageCount(1).ExpectHeader("tapped", true).AssertIsSatisfiedAsync(TimeSpan.FromSeconds(2)); } [Fact] public async Task InterceptSendToEndpoint_InvalidRegexMask_IsRefusedAtDeclaration() { await using var ctx = new RouteContext(); var act = async () => { ctx.AddRoutes(b => b.From("direct://rx").InterceptSendToEndpoint("regex:[").To("mock://x").EndIntercept().To("mock://y")); await ctx.Start(); }; await act.Should().ThrowAsync().WithMessage("*regular expression*"); } } Path: redb-route/tests/redb.Route.Tests/Eip/InterceptTests.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/Eip/InterceptTests.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.TestKit; namespace redb.Route.Tests.Eip; /// Intercept(), InterceptFrom(), InterceptSendToEndpoint() — route-level and builder-level. public class InterceptTests { private static readonly TimeSpan Wait = TimeSpan.FromSeconds(2); [Fact] public async Task Intercept_RunsBeforeEveryStep_IncludingStepsNestedInScopes() { var hits = 0; await using var ctx = new RouteContext().AddRoutes(b => b .From("direct://every") .Intercept().Process(_ => Interlocked.Increment(ref hits)).EndIntercept() .SetHeader("a", 1) .Split(e => (IEnumerable)e.In.Body!).To("mock://parts").EndSplit() .To("mock://end")); await ctx.Start(); await ctx.SendBody("direct://every", new object?[] { "x", "y" }); // SetHeader, Split, To inside the split (twice: one per fragment), To at the end. hits.Should().Be(5); await ctx.Mock("mock://parts").ExpectMessageCount(2).AssertIsSatisfiedAsync(Wait); } [Fact] public async Task Intercept_When_GatesTheInterceptSteps() { await using var ctx = new RouteContext().AddRoutes(b => b .From("direct://when") .Intercept().When("header.audit").To("mock://audit").EndIntercept() .SetHeader("x", 1) .To("mock://out")); await ctx.Start(); await ctx.SendBodyAndHeader("direct://when", "a", "audit", true); await ctx.Mock("mock://audit").ExpectMessageCount(2).AssertIsSatisfiedAsync(Wait); // one per step await ctx.SendBodyAndHeader("direct://when", "b", "audit", false); await ctx.Mock("mock://audit").ExpectMessageCount(2).AssertIsSatisfiedAsync(Wait); // unchanged await ctx.Mock("mock://out").ExpectMessageCount(2).AssertIsSatisfiedAsync(Wait); } [Fact] public async Task Intercept_Stop_StopsTheExchange() { await using var ctx = new RouteContext().AddRoutes(b => b .From("direct://stop") .Intercept().When("header.block").Stop().EndIntercept() .To("mock://out-stop")); await ctx.Start(); await ctx.SendBodyAndHeader("direct://stop", "a", "block", true); await ctx.SendBodyAndHeader("direct://stop", "b", "block", false); await ctx.Mock("mock://out-stop").ExpectBodies("b").AssertIsSatisfiedAsync(Wait); } [Fact] public async Task BuilderLevel_Intercept_AppliesToEveryRoute() { await using var ctx = new RouteContext().AddRoutes(b => { b.Intercept().SetHeader("seen", true); b.From("direct://r1").To("mock://r1"); b.From("direct://r2").To("mock://r2"); }); await ctx.Start(); await ctx.SendBody("direct://r1", "1"); await ctx.SendBody("direct://r2", "2"); await ctx.Mock("mock://r1").ExpectHeader("seen", true).AssertIsSatisfiedAsync(Wait); await ctx.Mock("mock://r2").ExpectHeader("seen", true).AssertIsSatisfiedAsync(Wait); } [Fact] public async Task InterceptFrom_RunsOncePerMessage_OnlyForMatchingConsumers() { var entries = 0; await using var ctx = new RouteContext().AddRoutes(b => { b.InterceptFrom("direct://orders-*").Process(_ => Interlocked.Increment(ref entries)).SetHeader("entry", true); b.From("direct://orders-in").SetHeader("a", 1).SetHeader("b", 2).To("mock://orders"); b.From("direct://other").To("mock://other"); }); await ctx.Start(); await ctx.SendBody("direct://orders-in", "o"); await ctx.SendBody("direct://other", "x"); entries.Should().Be(1, "InterceptFrom fires on entry, not per step"); await ctx.Mock("mock://orders").ExpectHeader("entry", true).AssertIsSatisfiedAsync(Wait); ctx.Mock("mock://other").ReceivedExchanges[0].In.Headers.Should().NotContainKey("entry"); } [Fact] public async Task InterceptSendToEndpoint_Skip_IsADryRun_TheOriginalEndpointIsNeverResolved() { // kafka:// has no component in this process: a real send would fail. With the intercept the // send is replaced, so the route runs — the plan's "dry run in production" case. await using var ctx = new RouteContext().AddRoutes(b => b .From("direct://dry") .InterceptSendToEndpoint("kafka://*").When("property.dryRun") .To("mock://dry-tap") .SkipSendToOriginalEndpoint() .EndIntercept() .SetProperty("dryRun", e => e.In.Headers.ContainsKey("dry")) .To("kafka://orders") .To("mock://after")); await ctx.Start(); await ctx.SendBodyAndHeader("direct://dry", "o1", "dry", true); await ctx.Mock("mock://dry-tap") .ExpectBodies("o1") .ExpectProperty(ExchangePropertyKeys.ToEndpoint, "kafka://orders") .AssertIsSatisfiedAsync(Wait); await ctx.Mock("mock://after").ExpectMessageCount(1).AssertIsSatisfiedAsync(Wait); var real = () => ctx.SendBody("direct://dry", "o2"); await real.Should().ThrowAsync().WithMessage("*kafka*", "without dryRun the original send runs and there is no kafka component"); } [Fact] public async Task InterceptSendToEndpoint_WithoutSkip_TapsAndSends() { await using var ctx = new RouteContext().AddRoutes(b => b .From("direct://tap") .InterceptSendToEndpoint("mock://orig").To("mock://tap").EndIntercept() .To("mock://orig") .To("mock://untouched")); await ctx.Start(); await ctx.SendBody("direct://tap", "m"); await ctx.Mock("mock://tap").ExpectBodies("m").AssertIsSatisfiedAsync(Wait); await ctx.Mock("mock://orig").ExpectBodies("m").AssertIsSatisfiedAsync(Wait); ctx.Mock("mock://untouched").ReceivedExchanges[0].Properties.Should().ContainKey(ExchangePropertyKeys.ToEndpoint, "the property stays on the exchange after the intercepted send"); } [Fact] public async Task InterceptSendToEndpoint_MatchesDynamicTargets_PerMessage() { await using var ctx = new RouteContext().AddRoutes(b => b .From("direct://dyn") .InterceptSendToEndpoint("mock://dyn-*").SetHeader("tapped", true).EndIntercept() .ToD("mock://${header.target}")); await ctx.Start(); await ctx.SendBodyAndHeader("direct://dyn", "a", "target", "dyn-1"); await ctx.SendBodyAndHeader("direct://dyn", "b", "target", "plain"); await ctx.Mock("mock://dyn-1").ExpectHeader("tapped", true).ExpectProperty(ExchangePropertyKeys.ToEndpoint, "mock://dyn-1").AssertIsSatisfiedAsync(Wait); ctx.Mock("mock://plain").ReceivedExchanges[0].In.Headers.Should().NotContainKey("tapped"); } [Fact] public async Task InterceptBody_IsNotInterceptedItself() { var hits = 0; await using var ctx = new RouteContext().AddRoutes(b => b .From("direct://self") .Intercept().Process(_ => Interlocked.Increment(ref hits)).SetHeader("i", 1).EndIntercept() .To("mock://self-out")); await ctx.Start(); await ctx.SendBody("direct://self", "x"); hits.Should().Be(1, "the intercept's own two steps must not be wrapped by the intercept"); } [Fact] public void SkipSendToOriginalEndpoint_OnPlainIntercept_IsRejected() { var act = () => new RouteBuilderProbe().Probe(); act.Should().Throw().WithMessage("*InterceptSendToEndpoint*"); } private sealed class RouteBuilderProbe : RouteBuilder { public void Probe() => Intercept().SkipSendToOriginalEndpoint(); protected override void Configure() { } } } Path: redb-route/tests/redb.Route.Tests/Eip/OnCompletionModeTests.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/Eip/OnCompletionModeTests.cs ---- using System.Transactions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.TestKit; using redb.Route.Transactions; namespace redb.Route.Tests.Eip; /// /// Where an OnCompletion block runs, as in Apache Camel: in the caller once the route has finished, the caller /// waiting for it, unless ParallelProcessing() or ExecutorService(name) gives it a bounded pool of its /// own. Either way it runs on a copy, detached from the caller's transaction and cancellation, and never changes the /// route's own result. /// public class OnCompletionModeTests { private static async Task Start(RouteContext context, string uri) { await context.Start(); var producer = context.GetEndpoint(uri).CreateProducer(); await producer.Start(); return producer; } [Fact] public async Task ByDefault_TheCallerWaitsForTheBlock() { var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); await using var context = new RouteContext().AddRoutes(b => b .From("direct://oc-sync") .OnCompletion().Process(async (_, _) => { entered.TrySetResult(); await gate.Task; }).EndOnCompletion() .SetBody("reply")); var producer = await Start(context, "direct://oc-sync"); var send = producer.Process(new Exchange(new Message("in"))); await entered.Task.WaitAsync(TimeSpan.FromSeconds(5)); await Task.Delay(100); send.IsCompleted.Should().BeFalse("the caller runs the block and waits for it, as in Camel"); gate.SetResult(); await send.WaitAsync(TimeSpan.FromSeconds(5)); } [Fact] public async Task WithParallelProcessing_TheCallerDoesNotWait() { var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); await using var context = new RouteContext().AddRoutes(b => b .From("direct://oc-parallel") .OnCompletion().ParallelProcessing().Process(async (_, _) => { entered.TrySetResult(); await gate.Task; }).EndOnCompletion() .SetBody("reply")); var producer = await Start(context, "direct://oc-parallel"); await producer.Process(new Exchange(new Message("in"))).WaitAsync(TimeSpan.FromSeconds(5)); await entered.Task.WaitAsync(TimeSpan.FromSeconds(5)); gate.SetResult(); } [Fact] public async Task AFailingBlock_DoesNotChangeTheRoutesResult() { await using var context = new RouteContext().AddRoutes(b => b .From("direct://oc-fails") .OnCompletion().ThrowException("the block fails").EndOnCompletion() .SetBody("reply")); await context.Start(); var reply = await context.RequestBody("direct://oc-fails", "in"); reply.Should().Be("reply", "a failing block is logged and counted, never the caller's result"); } [Fact] public async Task AFailingBlock_AfterAFailedRoute_LeavesTheRoutesOwnException() { await using var context = new RouteContext().AddRoutes(b => b .From("direct://oc-fails-too") .OnCompletion().OnFailureOnly().ThrowException("the block fails").EndOnCompletion() .ThrowException("the route's own failure")); await context.Start(); var act = () => context.SendBody("direct://oc-fails-too", "in"); await act.Should().ThrowAsync().WithMessage("*the route's own failure*"); } [Fact] public async Task TheCallersCancellation_DoesNotCutTheBlockHalfWay() { // An aborted request (its token cancelled once the route has done its work) must not stop an audit or a // cleanup in the middle: the block after the consumer never gets the caller's token. using var aborted = new CancellationTokenSource(); var finished = false; await using var context = new RouteContext().AddRoutes(b => b .From("direct://oc-cancel") .OnCompletion().Process(async (_, ct) => { await Task.Delay(200, ct); finished = true; }).EndOnCompletion() .Process(_ => aborted.Cancel())); var producer = await Start(context, "direct://oc-cancel"); try { await producer.Process(new Exchange(new Message("in")), aborted.Token); } catch (OperationCanceledException) { } finished.Should().BeTrue("the block ran to its end although the caller's token was cancelled"); } /// A database stand-in: a resource enlisted in the ambient transaction that logs its outcome. private sealed class LoggedDatabase(List log) : IEnlistmentNotification { public void Prepare(PreparingEnlistment enlistment) => enlistment.Prepared(); public void Commit(Enlistment enlistment) { lock (log) log.Add("db:commit"); enlistment.Done(); } public void Rollback(Enlistment enlistment) { lock (log) log.Add("db:rollback"); enlistment.Done(); } public void InDoubt(Enlistment enlistment) => enlistment.Done(); } [Theory] [InlineData(true, false)] [InlineData(false, true)] public async Task TheBlock_RunsOutsideTheCallersTransaction_OnACopyWithoutItsSends(bool blockFails, bool mainFails) { // The caller's own transaction (an outer scope, as a transacted route that calls this one) is still open // while the block runs in the caller. var log = new List(); await using var context = new RouteContext().AddRoutes(b => b .From("direct://oc-tx") .OnCompletion().Process(e => { lock (log) { log.Add(Transaction.Current is null ? "block:no-transaction" : "block:in-transaction"); log.Add(e.Properties.ContainsKey(TransactedProcessor.TransactActionPropertyKey) ? "block:has-sends" : "block:no-sends"); } if (blockFails) throw new InvalidOperationException("the block fails"); }).EndOnCompletion() .Transacted() .Process(_ => Transaction.Current!.EnlistVolatile(new LoggedDatabase(log), EnlistmentOptions.None)) .Process(_ => { if (mainFails) throw new InvalidOperationException("the main work fails"); }) .End()); var producer = await Start(context, "direct://oc-tx"); using (var outer = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = new TransactionPolicy().IsolationLevel }, TransactionScopeAsyncFlowOption.Enabled)) { var send = () => producer.Process(new Exchange(new Message("work"))); if (mainFails) await send.Should().ThrowAsync().WithMessage("the main work fails"); else { await send.Should().NotThrowAsync("a failing block never fails the route"); outer.Complete(); } } lock (log) { log.Should().Contain("block:no-transaction", "the block is detached from the caller's transaction"); log.Should().Contain("block:no-sends", "the copy does not carry the caller's deferred sends"); log.Should().Contain(mainFails ? "db:rollback" : "db:commit", mainFails ? "the main work rolls back although the block ran" : "the main work commits although the block failed"); } } [Fact] public async Task AnUnknownExecutorService_FailsTheRouteBuild_NamingIt() { await using var context = new RouteContext().AddRoutes(b => b .From("direct://oc-unknown") .OnCompletion().ExecutorService("no-such-pool").To("mock://never").EndOnCompletion() .SetBody("x")); var act = () => context.Start(); await act.Should().ThrowAsync().Where(e => Mentions(e, "no-such-pool")); } [Fact] public async Task AParallelBlock_StillRunning_IsWaitedForWhenTheContextStops() { var finished = false; var context = new RouteContext().AddRoutes(b => b .From("direct://oc-drain") .OnCompletion().ParallelProcessing().Process(async (_, _) => { await Task.Delay(300); finished = true; }).EndOnCompletion() .SetBody("x")); var producer = await Start(context, "direct://oc-drain"); await producer.Process(new Exchange(new Message("in"))); await context.Stop(); finished.Should().BeTrue("the block's pool drains when the consumers have stopped"); await context.DisposeAsync(); } private static bool Mentions(Exception? e, string text) { for (; e is not null; e = e.InnerException) if (e.Message.Contains(text, StringComparison.Ordinal)) return true; return false; } } Path: redb-route/tests/redb.Route.Tests/Eip/OnCompletionReviewTests.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/Eip/OnCompletionReviewTests.cs ---- using System.Transactions; using redb.Route.Core; using redb.Route.TestKit; namespace redb.Route.Tests.Eip; /// /// Defects from the 2026-09-01 code review. The copy an /// OnCompletion block receives shares its body with the live exchange, so releasing the copy must never /// close that body; the detached block runs with the caller's transaction suppressed, like WireTap; and /// a failing When can not change the route's own result. /// public class OnCompletionReviewTests { private static readonly TimeSpan Wait = TimeSpan.FromSeconds(2); // The stream tests send a caller-owned exchange through a ProducerTemplate: the TestKit helpers // create and dispose their own exchange (closing the body themselves), which would hide who did it. [Fact] public async Task FalseWhen_DoesNotDisposeTheLiveStreamBody() { await using var ctx = new RouteContext().AddRoutes(b => b .From("direct://stream-when") .OnCompletion().When("header.audit").To("mock://never").EndOnCompletion() .To("mock://out")); await ctx.Start(); using var template = new ProducerTemplate(ctx); template.Start(); var body = new MemoryStream("payload"u8.ToArray()); var message = new Message(body); message.Headers["audit"] = false; await template.SendAsync("direct://stream-when", Exchange.Create(message, null)); body.CanRead.Should().BeTrue("the completion copy shares the body with the live exchange; releasing the copy must not close it"); await ctx.Mock("mock://out").ExpectMessageCount(1).AssertIsSatisfiedAsync(Wait); } [Fact] public async Task AsyncBlock_DoesNotDisposeTheLiveStreamBody() { await using var ctx = new RouteContext().AddRoutes(b => b .From("direct://stream-async") .OnCompletion().To("mock://done").EndOnCompletion() .To("mock://out2")); await ctx.Start(); using var template = new ProducerTemplate(ctx); template.Start(); var body = new MemoryStream("payload"u8.ToArray()); await template.SendAsync("direct://stream-async", Exchange.Create(new Message(body), null)); await ctx.Mock("mock://done").ExpectMessageCount(1).AssertIsSatisfiedAsync(Wait); await Task.Delay(100); // the block's teardown runs after the mock saw the message body.CanRead.Should().BeTrue(); } [Fact] public async Task ThrowingWhen_DoesNotTurnASuccessIntoAFailure() { await using var ctx = new RouteContext().AddRoutes(b => b .From("direct://bad-when") .OnCompletion().When(_ => throw new InvalidOperationException("predicate broke")).To("mock://never2").EndOnCompletion() .SetBody("reply")); await ctx.Start(); var reply = await ctx.RequestBody("direct://bad-when", "in"); reply.Should().Be("reply", "OnCompletion never changes the route's own result"); } [Fact] public async Task ThrowingWhen_OnFailure_KeepsTheRoutesOwnException() { await using var ctx = new RouteContext().AddRoutes(b => b .From("direct://bad-when-fail") .OnCompletion().OnFailureOnly().When(_ => throw new InvalidOperationException("predicate broke")).To("mock://never3").EndOnCompletion() .ThrowException("the route's own failure")); await ctx.Start(); var act = () => ctx.SendBody("direct://bad-when-fail", "in"); await act.Should().ThrowAsync().WithMessage("*the route's own failure*"); } [Fact] public async Task AsyncBlock_RunsWithTheAmbientTransactionSuppressed() { Transaction? txInBlock = null; var tcs = new TaskCompletionSource(); await using var ctx = new RouteContext().AddRoutes(b => b .From("direct://tx") .OnCompletion().Process(_ => { txInBlock = Transaction.Current; tcs.TrySetResult(); }).EndOnCompletion() .SetBody("ok")); await ctx.Start(); using (var scope = new TransactionScope(TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Enabled)) { await ctx.SendBody("direct://tx", "in"); // The block runs while the caller's scope is still open — the case where a flowed ambient // transaction would be completed underneath it (.NET clears the flowed data on scope disposal, // so waiting outside the scope would hide the leak). await tcs.Task.WaitAsync(TimeSpan.FromSeconds(5)); scope.Complete(); } txInBlock.Should().BeNull("the completion block is detached from the originating transaction, like WireTap"); } /// Second batch: OnCompletion bodies compile inside the route's compile frame, so a checkpoint inside one knows its route. [Fact] public async Task Body_MayDeclareAReplayableCheckpoint() { await using var ctx = new RouteContext().AddRoutes(b => b .From("direct://cp") .OnCompletion().Replayable("after", r => r.SetHeader("checkpointed", true)).To("mock://cp").EndOnCompletion() .SetBody("ok")); var act = () => ctx.Start(); await act.Should().NotThrowAsync(); await ctx.SendBody("direct://cp", "x"); await ctx.Mock("mock://cp").ExpectMessageCount(1).AssertIsSatisfiedAsync(Wait); } } Path: redb-route/tests/redb.Route.Tests/Eip/OnCompletionTests.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/Eip/OnCompletionTests.cs ---- using redb.Route.Core; using redb.Route.TestKit; namespace redb.Route.Tests.Eip; /// OnCompletion(): after the route, on a copy, outside error handling. public class OnCompletionTests { private static readonly TimeSpan Wait = TimeSpan.FromSeconds(2); [Fact] public async Task Default_RunsAfterTheRoute_OnACopy_WithoutChangingTheReply() { await using var ctx = new RouteContext().AddRoutes(b => b .From("direct://done") .OnCompletion().SetHeader("completed", true).To("mock://done").EndOnCompletion() .SetBody("reply")); await ctx.Start(); var reply = await ctx.RequestBody("direct://done", "in"); reply.Should().Be("reply"); await ctx.Mock("mock://done").ExpectBodies("reply").ExpectHeader("completed", true).AssertIsSatisfiedAsync(Wait); } [Fact] public async Task OnFailureOnly_SeesTheException_AndSkipsSuccess() { string? captured = null; await using var ctx = new RouteContext().AddRoutes(b => b .From("direct://fail") .OnCompletion().OnFailureOnly().Process(e => captured = e.Exception?.Message).To("mock://failed").EndOnCompletion() .Filter(e => Equals(e.In.Body, "boom")).ThrowException("boom").EndFilter() .To("mock://ok")); await ctx.Start(); var act = () => ctx.SendBody("direct://fail", "boom"); await act.Should().ThrowAsync(); await ctx.Mock("mock://failed").ExpectMessageCount(1).AssertIsSatisfiedAsync(Wait); captured.Should().Be("boom"); await ctx.SendBody("direct://fail", "fine"); await ctx.Mock("mock://ok").ExpectMessageCount(1).AssertIsSatisfiedAsync(Wait); await ctx.Mock("mock://failed").ExpectMessageCount(1).AssertIsSatisfiedAsync(Wait); } [Fact] public async Task OnCompleteOnly_WithWhen() { await using var ctx = new RouteContext().AddRoutes(b => b .From("direct://audit") .OnCompletion().OnCompleteOnly().When("header.audit").To("mock://audited").EndOnCompletion() .To("mock://out")); await ctx.Start(); await ctx.SendBodyAndHeader("direct://audit", "a", "audit", true); await ctx.SendBodyAndHeader("direct://audit", "b", "audit", false); await ctx.Mock("mock://out").ExpectMessageCount(2).AssertIsSatisfiedAsync(Wait); await ctx.Mock("mock://audited").ExpectBodies("a").AssertIsSatisfiedAsync(Wait); await Task.Delay(200); ctx.Mock("mock://audited").ReceivedCount.Should().Be(1, "audit=false must not trigger the block, even asynchronously"); } [Fact] public async Task ModeBeforeConsumer_RunsBeforeTheCallerGetsTheReply() { await using var ctx = new RouteContext().AddRoutes(b => b .From("direct://sync") .OnCompletion().ModeBeforeConsumer().To("mock://sync").EndOnCompletion() .SetBody("x")); await ctx.Start(); await ctx.SendBody("direct://sync", "in"); ctx.Mock("mock://sync").ReceivedCount.Should().Be(1, "no waiting: the block ran before the send returned"); } [Fact] public async Task HandledException_IsACompletion_NotAFailure() { await using var ctx = new RouteContext().AddRoutes(b => { b.OnException().Handled(); b.From("direct://handled") .OnCompletion().OnFailureOnly().ModeBeforeConsumer().To("mock://h-failed").EndOnCompletion() .OnCompletion().OnCompleteOnly().ModeBeforeConsumer().To("mock://h-complete").EndOnCompletion() .ThrowException("handled"); }); await ctx.Start(); await ctx.SendBody("direct://handled", "x"); ctx.Mock("mock://h-complete").ReceivedCount.Should().Be(1); ctx.Mock("mock://h-failed").ReceivedCount.Should().Be(0); } [Fact] public async Task CompletionMutations_DoNotLeakIntoTheRouteResult() { await using var ctx = new RouteContext().AddRoutes(b => b .From("direct://copy") .OnCompletion().ModeBeforeConsumer().SetBody("mutated").SetHeader("h", "mutated").EndOnCompletion() .SetBody("reply")); await ctx.Start(); var reply = await ctx.RequestBodyAndHeaders("direct://copy", "in", new Dictionary { ["h"] = "orig" }); reply.Should().Be("reply"); } [Fact] public async Task BuilderLevel_OnCompletion_AppliesToEveryRoute() { await using var ctx = new RouteContext().AddRoutes(b => { b.OnCompletion().ModeBeforeConsumer().To("mock://all-done"); b.From("direct://c1").SetBody("1"); b.From("direct://c2").SetBody("2"); }); await ctx.Start(); await ctx.SendBody("direct://c1", "x"); await ctx.SendBody("direct://c2", "x"); await ctx.Mock("mock://all-done").ExpectBodies("1", "2").AssertIsSatisfiedAsync(Wait); } [Fact] public async Task FailingCompletionBlock_IsLogged_NotThrown() { await using var ctx = new RouteContext().AddRoutes(b => b .From("direct://bad-block") .OnCompletion().ModeBeforeConsumer().ThrowException("block failed").EndOnCompletion() .SetBody("reply")); await ctx.Start(); (await ctx.RequestBody("direct://bad-block", "in")).Should().Be("reply"); } } Path: redb-route/tests/redb.Route.Tests/Eip/RouteSugarReviewTests.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/Eip/RouteSugarReviewTests.cs ---- using redb.Route.Core; using redb.Route.TestKit; namespace redb.Route.Tests.Eip; /// Code review 2026-09-01: a wildcard property mask must not touch the framework's own DI-scope bookkeeping. public class RouteSugarReviewTests { [Fact] public async Task RemoveProperties_Wildcard_KeepsTheServiceScopeProperties() { bool? scopeKept = null; bool? userGone = null; await using var ctx = new RouteContext().AddRoutes(b => b .From("direct://rp-all") .SetProperty("tmp", 1) .SetProperty("__redb_scope:test", "scope-marker") .RemoveProperties("*") .Process(e => { scopeKept = e.Properties.ContainsKey("__redb_scope:test"); userGone = !e.Properties.ContainsKey("tmp"); })); await ctx.Start(); await ctx.SendBody("direct://rp-all", "x"); userGone.Should().BeTrue(); scopeKept.Should().BeTrue("scope bookkeeping is not user data; losing it leaks the DI scopes ReleaseScopes would dispose"); } } Path: redb-route/tests/redb.Route.Tests/Eip/RouteSugarTests.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/Eip/RouteSugarTests.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Definitions; using redb.Route.Expressions; using redb.Route.TestKit; namespace redb.Route.Tests.Eip; /// SetHeaders, RemoveHeaders(pattern), RemoveProperties(pattern), Sort. public class RouteSugarTests { private static readonly TimeSpan Wait = TimeSpan.FromSeconds(2); [Fact] public async Task SetHeaders_Constant_Expression_And_Func_InOneStep() { await using var ctx = new RouteContext().AddRoutes(b => b .From("direct://sh") .SetHeaders( ("a", 1), ("b", new StringExpression("header.a + 1")), ("c", (Func)(e => $"{e.In.Body}!"))) .To("mock://sh")); await ctx.Start(); await ctx.SendBody("direct://sh", "x"); await ctx.Mock("mock://sh").ExpectHeader("a", 1).ExpectHeader("b", 2).ExpectHeader("c", "x!").AssertIsSatisfiedAsync(Wait); } [Fact] public async Task SetProperties_Constant_Expression_And_Func_InOneStep_InOrder() { await using var ctx = new RouteContext().AddRoutes(b => b .From("direct://sp") .SetProperties( ("a", 1), ("b", new StringExpression("property.a + 1")), ("c", (Func)(e => $"{e.In.Body}!"))) .To("mock://sp")); await ctx.Start(); await ctx.SendBody("direct://sp", "x"); var properties = ctx.Mock("mock://sp").ReceivedExchanges[0].Properties; properties["a"].Should().Be(1); properties["b"].Should().Be(2, "a later property reads an earlier one of the same step"); properties["c"].Should().Be("x!"); } [Fact] public void SetProperties_WithoutProperties_IsRejected() { var act = () => new SetPropertiesDefinition([]); act.Should().Throw(); } [Fact] public async Task RemoveHeaders_ByMask_WithExceptions() { await using var ctx = new RouteContext().AddRoutes(b => b .From("direct://rh").RemoveHeaders("X-Internal-*", "X-Internal-Keep").To("mock://rh")); await ctx.Start(); await ctx.SendBodyAndHeaders("direct://rh", "x", new Dictionary { ["X-Internal-A"] = 1, ["X-Internal-B"] = 2, ["X-Internal-Keep"] = 3, ["Public"] = 4, }); var headers = ctx.Mock("mock://rh").ReceivedExchanges[0].In.Headers; headers.Keys.Should().BeEquivalentTo("X-Internal-Keep", "Public"); } [Fact] public async Task RemoveProperties_ByRegex() { await using var ctx = new RouteContext().AddRoutes(b => b .From("direct://rp") .SetProperty("tmp.a", 1).SetProperty("tmp.b", 2).SetProperty("keep", 3) .RemoveProperties("regex:^tmp\\..*") .To("mock://rp")); await ctx.Start(); await ctx.SendBody("direct://rp", "x"); var props = ctx.Mock("mock://rp").ReceivedExchanges[0].Properties; props.Should().ContainKey("keep").And.NotContainKey("tmp.a").And.NotContainKey("tmp.b"); } [Fact] public async Task Sort_StringForm_ByKeyExpression_ElementIsBody() { await using var ctx = new RouteContext().AddRoutes(b => b .From("direct://sort").Sort("body", "body.priority").To("mock://sorted")); await ctx.Start(); await ctx.SendBody("direct://sort", new List { new { name = "c", priority = 3 }, new { name = "a", priority = 1 }, new { name = "b", priority = 2 }, }); var sorted = (List)ctx.Mock("mock://sorted").ReceivedExchanges[0].In.Body!; sorted.Select(o => (string)o!.GetType().GetProperty("name")!.GetValue(o)!).Should().Equal("a", "b", "c"); } [Fact] public async Task Sort_Generic_Descending_ProducesTypedList() { await using var ctx = new RouteContext().AddRoutes(b => b .From("direct://sort-g").Sort(e => (IEnumerable)e.In.Body!, descending: true).To("mock://sorted-g")); await ctx.Start(); await ctx.SendBody("direct://sort-g", new[] { 2, 3, 1 }); ctx.Mock("mock://sorted-g").ReceivedExchanges[0].In.Body.Should().BeOfType>().Which.Should().Equal(3, 2, 1); } [Fact] public async Task Sort_MixedNumbersAndNulls() { await using var ctx = new RouteContext().AddRoutes(b => b .From("direct://sort-m").Sort("body").To("mock://sorted-m")); await ctx.Start(); await ctx.SendBody("direct://sort-m", new List { 3, null, 1.5m, 2L }); ((List)ctx.Mock("mock://sorted-m").ReceivedExchanges[0].In.Body!).Should().Equal(null, 1.5m, 2L, 3); } [Fact] public async Task Sort_OnAString_Fails() { await using var ctx = new RouteContext().AddRoutes(b => b.From("direct://sort-s").Sort("body")); await ctx.Start(); var act = () => ctx.SendBody("direct://sort-s", "not a list"); await act.Should().ThrowAsync().WithMessage("Sort:*"); } } Path: redb-route/tests/redb.Route.Tests/ErrorHandling/DeadLetterProcessorTests.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/ErrorHandling/DeadLetterProcessorTests.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.ErrorHandling; using redb.Route.Processors; namespace redb.Route.Tests.ErrorHandling; /// /// Tests for . /// public class DeadLetterProcessorTests { [Fact] public async Task Success_PassesThrough_NoDlc() { IExchange? captured = null; var inner = new DelegateProcessor(ex => ex.In.Body = "processed"); var dlcTarget = new DelegateProcessor(ex => captured = ex); var sut = new DeadLetterProcessor(inner, dlcTarget); var exchange = new Exchange(new Message { Body = "original" }); await sut.Process(exchange); exchange.In.Body.Should().Be("processed"); captured.Should().BeNull("dead letter target should not be called on success"); } [Fact] public async Task Failure_RoutesToDeadLetter() { IExchange? capturedDlc = null; var inner = new DelegateProcessor(async (_, _) => { throw new InvalidOperationException("boom"); }); var dlcTarget = new DelegateProcessor(ex => capturedDlc = ex); var sut = new DeadLetterProcessor(inner, dlcTarget); var exchange = new Exchange(new Message { Body = "original" }); await sut.Process(exchange); // Exchange should be routed to DLC, not re-thrown capturedDlc.Should().NotBeNull(); exchange.ExceptionHandled.Should().BeTrue(); exchange.Exception.Should().BeOfType(); } [Fact] public async Task Failure_StampsDeadLetterHeaders() { var inner = new DelegateProcessor(async (_, _) => { throw new ArgumentException("bad input"); }); var dlcTarget = new DelegateProcessor(_ => { }); var sut = new DeadLetterProcessor(inner, dlcTarget); var exchange = new Exchange(new Message { Body = "data" }); await sut.Process(exchange); exchange.In.Headers.Should().ContainKey("CamelDeadLetterReason"); exchange.In.Headers["CamelDeadLetterReason"].Should().Be("bad input"); exchange.In.Headers.Should().ContainKey("CamelDeadLetterExceptionType"); exchange.In.Headers["CamelDeadLetterExceptionType"].Should().Be(typeof(ArgumentException).FullName); exchange.In.Headers.Should().ContainKey("CamelDeadLetterTimestamp"); } [Fact] public async Task CallerCancellation_IsNotCaughtByDlc() { var inner = new DelegateProcessor(async (_, _) => { throw new OperationCanceledException(); }); var dlcTarget = new DelegateProcessor(_ => { }); var sut = new DeadLetterProcessor(inner, dlcTarget); var exchange = new Exchange(new Message { Body = "data" }); using var cts = new CancellationTokenSource(); cts.Cancel(); var act = () => sut.Process(exchange, cts.Token); await act.Should().ThrowAsync(); } [Fact] public async Task Timeout_IsDeadLetteredAsTimeoutException() { // A timeout is a failure: it reaches the dead letter channel named a TimeoutException, instead of // being rethrown as a cancellation the DLC would skip. var inner = new DelegateProcessor(async (_, _) => throw new TaskCanceledException("downstream deadline")); TimeoutException? seen = null; var dlcTarget = new DelegateProcessor(ex => seen = ex.Exception as TimeoutException); var sut = new DeadLetterProcessor(inner, dlcTarget); var exchange = new Exchange(new Message { Body = "data" }); await sut.Process(exchange); seen.Should().NotBeNull("the timeout is a failure and reaches the dead letter channel"); exchange.In.Headers["CamelDeadLetterExceptionType"].Should().Be(typeof(TimeoutException).FullName); exchange.ExceptionHandled.Should().BeTrue(); } // ── B9: DLC with RetryPolicy ── [Fact] public async Task RetryPolicy_RetriesBeforeDeadLettering() { var callCount = 0; var inner = new DelegateProcessor(async (_, _) => { callCount++; if (callCount < 3) throw new InvalidOperationException("transient"); }); var dlcTarget = new DelegateProcessor(_ => { }); var policy = RetryPolicy.Fixed(5, TimeSpan.FromMilliseconds(1)); var sut = new DeadLetterProcessor(inner, dlcTarget, policy); var exchange = new Exchange(new Message { Body = "data" }); await sut.Process(exchange); callCount.Should().Be(3, "should succeed on 3rd attempt"); exchange.ExceptionHandled.Should().BeFalse("no DLQ needed — success"); } [Fact] public async Task RetryPolicy_ExhaustedThenDeadLetters() { IExchange? captured = null; var inner = new DelegateProcessor(async (_, _) => { throw new InvalidOperationException("always fails"); }); var dlcTarget = new DelegateProcessor(ex => captured = ex); var policy = RetryPolicy.Fixed(2, TimeSpan.FromMilliseconds(1)); var sut = new DeadLetterProcessor(inner, dlcTarget, policy); var exchange = new Exchange(new Message { Body = "data" }); await sut.Process(exchange); captured.Should().NotBeNull("should route to DLQ after retries exhausted"); exchange.ExceptionHandled.Should().BeTrue(); exchange.In.Headers.Should().ContainKey("CamelDeadLetterRedeliveryCount"); exchange.In.Headers["CamelDeadLetterRedeliveryCount"].Should().Be(2); } [Fact] public async Task RetryPolicy_RespectsRetryableExceptionPredicate() { var callCount = 0; IExchange? captured = null; var inner = new DelegateProcessor(async (_, _) => { callCount++; throw new ArgumentException("not retryable"); }); var dlcTarget = new DelegateProcessor(ex => captured = ex); var policy = new RetryPolicy { MaxRetries = 5, InitialDelay = TimeSpan.FromMilliseconds(1), RetryableExceptionPredicate = ex => ex is InvalidOperationException // only IOE is retryable }; var sut = new DeadLetterProcessor(inner, dlcTarget, policy); var exchange = new Exchange(new Message { Body = "data" }); await sut.Process(exchange); callCount.Should().Be(1, "ArgumentException is not retryable — no retries"); captured.Should().NotBeNull(); } } Path: redb-route/tests/redb.Route.Tests/ErrorHandling/RetryDelayTests.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/ErrorHandling/RetryDelayTests.cs ---- using AwesomeAssertions; using Microsoft.Extensions.Logging; using redb.Route.Core; using redb.Route.ErrorHandling; using redb.Route.Processors; namespace redb.Route.Tests.ErrorHandling; /// /// The retry waits the delay its policy computes — jitter only when the policy asks for it /// (, off by default as Camel's collision avoidance), capped by /// . The processor used to add ±15% of its own on top: jitter twice when the policy /// already had some, jitter nobody configured when it had none, and a wait past the cap. /// public class RetryDelayTests { private sealed class DelayLog : ILogger { public List Delays { get; } = []; 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 (state is IReadOnlyList> values && values.FirstOrDefault(v => v.Key == "Delay").Value is double delay) Delays.Add(delay); } } private static async Task> WaitsOf(RetryPolicy policy) { var log = new DelayLog(); var processor = new RetryProcessor(new DelegateProcessor(_ => throw new InvalidOperationException("down")), policy, log); var act = () => processor.Process(new Exchange(new Message("x"))); await act.Should().ThrowAsync(); return log.Delays; } [Fact] public async Task Without_jitter_in_the_policy_the_retry_waits_exactly_the_policy_delay() { var policy = new RetryPolicy { MaxRetries = 3, InitialDelay = TimeSpan.FromMilliseconds(10), BackoffMultiplier = 2 }; var waits = await WaitsOf(policy); waits.Should().Equal(policy.GetDelay(0).TotalMilliseconds, policy.GetDelay(1).TotalMilliseconds, policy.GetDelay(2).TotalMilliseconds); } [Fact] public async Task The_wait_never_passes_the_cap() { var policy = new RetryPolicy { MaxRetries = 5, InitialDelay = TimeSpan.FromMilliseconds(20), BackoffMultiplier = 2, MaxDelay = TimeSpan.FromMilliseconds(20), CollisionAvoidanceFactor = 0.15, }; var waits = await WaitsOf(policy); waits.Should().HaveCount(5).And.OnlyContain(w => w <= 20); } } Path: redb-route/tests/redb.Route.Tests/ErrorHandling/RetryTests.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/ErrorHandling/RetryTests.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.ErrorHandling; using redb.Route.Processors; namespace redb.Route.Tests.ErrorHandling; /// /// Tests for . /// public class RetryPolicyTests { [Fact] public void None_HasZeroRetries() { var policy = RetryPolicy.None; policy.MaxRetries.Should().Be(0); } [Fact] public void Fixed_HasConstantDelay() { var delay = TimeSpan.FromMilliseconds(200); var policy = RetryPolicy.Fixed(3, delay); policy.MaxRetries.Should().Be(3); policy.GetDelay(0).Should().Be(delay); policy.GetDelay(1).Should().Be(delay); policy.GetDelay(2).Should().Be(delay); } [Fact] public void Exponential_IncreasesDelay() { var policy = RetryPolicy.Exponential(5, TimeSpan.FromMilliseconds(100)); var d0 = policy.GetDelay(0); var d1 = policy.GetDelay(1); var d2 = policy.GetDelay(2); d0.TotalMilliseconds.Should().Be(100); d1.TotalMilliseconds.Should().Be(200); d2.TotalMilliseconds.Should().Be(400); } [Fact] public void Exponential_RespectsMaxDelay() { var policy = RetryPolicy.Exponential( 10, TimeSpan.FromSeconds(1), maxDelay: TimeSpan.FromSeconds(5)); // After enough attempts, delay should be capped var d5 = policy.GetDelay(5); // 1 * 2^5 = 32s → capped at 5s d5.TotalSeconds.Should().Be(5); } [Fact] public void ShouldRetry_DefaultRetryAllExceptions() { var policy = RetryPolicy.Fixed(3, TimeSpan.FromMilliseconds(10)); policy.ShouldRetry(new InvalidOperationException()).Should().BeTrue(); policy.ShouldRetry(new TimeoutException()).Should().BeTrue(); } [Fact] public void ShouldRetry_RespectsCustomPredicate() { var policy = new RetryPolicy { MaxRetries = 3, InitialDelay = TimeSpan.FromMilliseconds(10), RetryableExceptionPredicate = ex => ex is TimeoutException }; policy.ShouldRetry(new TimeoutException()).Should().BeTrue(); policy.ShouldRetry(new InvalidOperationException()).Should().BeFalse(); } // ── B1: CollisionAvoidanceFactor (jitter) ── [Fact] public void Jitter_ZeroFactor_NoDelta() { var policy = new RetryPolicy { MaxRetries = 3, InitialDelay = TimeSpan.FromMilliseconds(100), BackoffMultiplier = 1.0, CollisionAvoidanceFactor = 0.0 }; // With zero jitter, delay is deterministic policy.GetDelay(0).TotalMilliseconds.Should().Be(100); policy.GetDelay(1).TotalMilliseconds.Should().Be(100); } [Fact] public void Jitter_WithFactor_ProducesVariation() { var policy = new RetryPolicy { MaxRetries = 100, InitialDelay = TimeSpan.FromMilliseconds(1000), BackoffMultiplier = 1.0, MaxDelay = TimeSpan.FromSeconds(60), CollisionAvoidanceFactor = 0.15 }; // Run many times — at least one should differ from the base 1000ms var delays = Enumerable.Range(0, 50).Select(i => policy.GetDelay(0).TotalMilliseconds).ToList(); delays.Should().Contain(d => d != 1000, "jitter should produce variation"); // All should be within ±15% (850..1150) delays.Should().OnlyContain(d => d >= 850 && d <= 1150); } // ── B2: DelayPattern ── [Fact] public void DelayPattern_OverridesExponential() { var policy = new RetryPolicy { MaxRetries = 10, InitialDelay = TimeSpan.FromMilliseconds(100), BackoffMultiplier = 2.0, DelayPattern = "1:500;3:2000;7:10000" }; // Attempt 0 → 1-based=1, matches key "1" → 500ms policy.GetDelay(0).TotalMilliseconds.Should().Be(500); // Attempt 1 → 1-based=2, highest key ≤ 2 is "1" → 500ms policy.GetDelay(1).TotalMilliseconds.Should().Be(500); // Attempt 2 → 1-based=3, matches key "3" → 2000ms policy.GetDelay(2).TotalMilliseconds.Should().Be(2000); // Attempt 5 → 1-based=6, highest key ≤ 6 is "3" → 2000ms policy.GetDelay(5).TotalMilliseconds.Should().Be(2000); // Attempt 6 → 1-based=7, matches key "7" → 10000ms policy.GetDelay(6).TotalMilliseconds.Should().Be(10000); } [Fact] public void DelayPattern_NoMatchFallsBackToStandard() { // Pattern starts at attempt 5, so attempts 0-3 use standard calculation var policy = new RetryPolicy { MaxRetries = 10, InitialDelay = TimeSpan.FromMilliseconds(100), BackoffMultiplier = 1.0, DelayPattern = "5:9999" }; // 1-based=1, no key ≤ 1 in pattern → standard calc → 100ms policy.GetDelay(0).TotalMilliseconds.Should().Be(100); // 1-based=5, matches → 9999ms policy.GetDelay(4).TotalMilliseconds.Should().Be(9999); } } /// /// Tests for . /// public class RetryProcessorTests { [Fact] public async Task Succeeds_OnFirstAttempt_NoRetry() { var callCount = 0; var inner = new DelegateProcessor(_ => callCount++); var sut = new RetryProcessor(inner, RetryPolicy.Fixed(3, TimeSpan.FromMilliseconds(1))); var exchange = new Exchange(new Message { Body = "test" }); await sut.Process(exchange); callCount.Should().Be(1); } [Fact] public async Task Retries_OnFailure_ThenSucceeds() { var callCount = 0; var inner = new DelegateProcessor(async (_, _) => { callCount++; if (callCount < 3) throw new InvalidOperationException("transient"); }); var sut = new RetryProcessor(inner, RetryPolicy.Fixed(5, TimeSpan.FromMilliseconds(1))); var exchange = new Exchange(new Message { Body = "test" }); await sut.Process(exchange); callCount.Should().Be(3); exchange.Exception.Should().BeNull(); } [Fact] public async Task Throws_WhenRetriesExhausted() { var inner = new DelegateProcessor(async (_, _) => { throw new InvalidOperationException("permanent"); }); var sut = new RetryProcessor(inner, RetryPolicy.Fixed(2, TimeSpan.FromMilliseconds(1))); var exchange = new Exchange(new Message { Body = "test" }); var act = () => sut.Process(exchange); await act.Should().ThrowAsync() .WithMessage("permanent"); } [Fact] public async Task DoesNotRetry_CallerCancellation() { var callCount = 0; var inner = new DelegateProcessor(async (_, _) => { callCount++; throw new OperationCanceledException(); }); var sut = new RetryProcessor(inner, RetryPolicy.Fixed(5, TimeSpan.FromMilliseconds(1))); var exchange = new Exchange(new Message { Body = "test" }); using var cts = new CancellationTokenSource(); cts.Cancel(); var act = () => sut.Process(exchange, cts.Token); await act.Should().ThrowAsync(); callCount.Should().Be(1); } [Fact] public async Task Retries_Timeout() { // A timeout is an OperationCanceledException with our token still live — a failure, so the policy // sees it as a TimeoutException and Retry retries it instead of passing it through as cancellation. var callCount = 0; var inner = new DelegateProcessor(async (_, _) => { callCount++; if (callCount < 3) throw new TaskCanceledException("downstream deadline"); }); var sut = new RetryProcessor(inner, RetryPolicy.Fixed(5, TimeSpan.FromMilliseconds(1))); await sut.Process(new Exchange(new Message { Body = "test" })); callCount.Should().Be(3, "a timeout is a failure and the retry policy retries it"); } [Fact] public async Task DoesNotRetry_WhenPredicateRejects() { var callCount = 0; var inner = new DelegateProcessor(async (_, _) => { callCount++; throw new ArgumentException("bad"); }); var policy = new RetryPolicy { MaxRetries = 5, InitialDelay = TimeSpan.FromMilliseconds(1), RetryableExceptionPredicate = ex => ex is TimeoutException // Only retry timeouts }; var sut = new RetryProcessor(inner, policy); var exchange = new Exchange(new Message { Body = "test" }); var act = () => sut.Process(exchange); await act.Should().ThrowAsync(); callCount.Should().Be(1); } } Path: redb-route/tests/redb.Route.Tests/Expressions/BareTextTests.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/Expressions/BareTextTests.cs ---- using AwesomeAssertions; using redb.Route.Core; using redb.Route.Expressions; using redb.Route.Predicates; namespace redb.Route.Tests.Expressions; /// /// Bare text in a value or condition (findings register row 29): a text without an arithmetic operator is what it was /// (a lookup, a literal, or the text itself, as in Apache Camel); a text with one must be whole arithmetic, else a /// positioned error. The old compiler used to compute pieces: 1 + gave 1, header.a+b gave /// 2b, header.a * x gave xx. /// public sealed class BareTextTests { private static Exchange Message() { var exchange = new Exchange(new Message("x")); exchange.In.Headers["a"] = 2; exchange.In.Headers["b"] = 3; exchange.In.Headers["Content-Type"] = "text/xml"; return exchange; } private static object? Value(string expression) => ExpressionResolver.GetCompiledValueExpression(expression)(Message()); [Theory] [InlineData("hello")] [InlineData("plain text")] [InlineData("Hello World")] [InlineData("key=value")] [InlineData("((((")] [InlineData("~~~INVALID~~~")] [InlineData("dGVzdC1zZWNyZXQ=")] [InlineData("${}")] [InlineData("'unterminated")] public void TextWithoutArithmetic_IsTheText(string text) { // Every value expression is the AST's since row 28; the row 29 rule keeps these as the text itself there too. Value(text).Should().Be(text); PredicateFactory.FromString(text).Matches(Message()).Should().BeTrue("non-empty text is true"); } [Fact] public void ABareExceptionMessage_ReadsTheException() { // Row 28: the old compiler returned the text "exception.Message"; the AST reads the root, as ${...} does. var failed = Message(); failed.Exception = new InvalidOperationException("boom"); ExpressionResolver.GetCompiledValueExpression("exception.Message")(failed).Should().Be("boom"); ExpressionResolver.GetCompiledValueExpression("exception.Message")(Message()).Should().BeNull(); } [Theory] [InlineData("direct://cat-all-2")] [InlineData("direct://a,direct://b")] [InlineData("kafka:orders/eu")] public void AnEndpointUri_IsNotArithmetic(string uri) { // A destination named in an expression () keeps compiling. var act = () => ExpressionResolver.GetCompiledValueExpression(uri); act.Should().NotThrow(); } [Theory] [InlineData("header.a + 1", 3)] [InlineData("header.a+header.b", 5)] [InlineData("header.a * 2", 4)] [InlineData("10 / header.a", 5)] public void WholeArithmetic_IsComputedAsBefore(string expression, int expected) { System.Convert.ToInt32(Value(expression)).Should().Be(expected); } [Fact] public void TextPlusANumber_IsConcatenatedAsBefore() { Value("body + 1").Should().Be("x1"); } [Theory] [InlineData("1 +", "the expression ends after '+' at position 3, where a value is expected within the expression \"1 +\".")] [InlineData("header.a +", "the expression ends after '+' at position 10, where a value is expected within the expression \"header.a +\".")] [InlineData("1 + 2 3", "unexpected '3' at position 7 within the expression \"1 + 2 3\".")] [InlineData("header.a+b", "'b' at position 10 is not a value: write header.b, property.b or the text 'b' in quotes within the expression \"header.a+b\".")] [InlineData("header.a * x", "'x' at position 12 is not a value: write header.x, property.x or the text 'x' in quotes within the expression \"header.a * x\".")] [InlineData("application/json", "'application' at position 1 is not a value: write header.application, property.application or the text 'application' in quotes within the expression \"application/json\".")] [InlineData("header.Content-Type", "'header.Content-Type' at position 1 reads as a subtraction: a name with a dash is written ${header.Content-Type} within the expression \"header.Content-Type\".")] [InlineData("header.X-Request-Id", "'header.X-Request-Id' at position 1 reads as a subtraction: a name with a dash is written ${header.X-Request-Id} within the expression \"header.X-Request-Id\".")] public void ArithmeticThatBreaksOff_IsAPositionedError(string expression, string message) { var act = () => ExpressionResolver.GetCompiledValueExpression(expression); act.Should().Throw().WithMessage(message); } [Fact] public void InACondition_TheSameError() { var act = () => PredicateFactory.FromString("header.a+b"); act.Should().Throw().WithMessage("'b' at position 10 is not a value*"); } [Fact] public void ADashedNameInAPlaceholder_StillReadsTheHeader() { new StringExpression("${header.Content-Type}").Evaluate(Message()).Should().Be("text/xml"); } } Path: redb-route/tests/redb.Route.Tests/Expressions/BeanFunctionTests.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/Expressions/BeanFunctionTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Expressions; using redb.Route.Predicates; namespace redb.Route.Tests.Expressions; /// A bean the expression function calls. public class PricingRules { public int Calls; public double Gross(int qty, double price) { Calls++; return qty * price; } public bool IsGold(string? name) => name == "ann"; public string Stamp(IExchange exchange, string mark) => $"{mark}:{exchange.In.Body}"; public string Name { get; set; } = "rules"; public Task CheckAsync(string name) => Task.FromResult(name == "ann"); public ValueTask CountAsync() => ValueTask.FromResult(1); } /// /// The bean: function of the expression language (stage 2 step d): the bean from the exchange's context /// registry, the method bound by the bean: URI rules, synchronous only, refused under the sandbox, resolved once /// per context. Used the same way in templates, bare conditions, C# routes and XML routes. /// public sealed class BeanFunctionTests : IAsyncLifetime { private readonly RouteContext _context = new(); private readonly PricingRules _rules = new(); public Task InitializeAsync() { _context.AddToRegistry("rules", _rules); _context.AddToRegistry("pricing-rules", _rules); return Task.CompletedTask; } public async Task DisposeAsync() => await _context.DisposeAsync(); private Exchange Message(object? body = null, params (string Key, object? Value)[] headers) { var exchange = new Exchange(new Message(body ?? "payload")) { Context = _context }; foreach (var (key, value) in headers) exchange.In.Headers[key] = value; return exchange; } [Theory] [InlineData("${bean:rules.Gross(header.qty, header.price)}")] [InlineData("${bean:rules.Gross(${header.qty}, ${header.price})}")] [InlineData("${bean:pricing-rules.Gross(header.qty, 2.5)}")] public void ATemplateHole_CallsTheBean_AndKeepsTheType(string template) { new StringExpression(template).Evaluate(Message(null, ("qty", 3), ("price", 2.5))).Should().Be(7.5); } [Fact] public void InText_TheResultIsRendered() { ExpressionResolver.ProcessTemplate("total ${bean:rules.Gross(header.qty, 2)} EUR", Message(null, ("qty", 4))) .Should().Be("total 8 EUR"); } [Fact] public void AmbientExchange_AndAStringLiteral_Bind() { new StringExpression("${bean:rules.Stamp('x')}").Evaluate(Message("body")).Should().Be("x:body"); } [Fact] public void AMethodWithoutParentheses_IsCalledWithoutArguments() { new StringExpression("${bean:rules.CountAsync}").Invoking(e => e.Evaluate(Message())) .Should().Throw().WithMessage("*synchronous*"); } [Theory] [InlineData("bean:rules.IsGold(header.name)", "ann", true)] [InlineData("bean:rules.IsGold(header.name)", "bob", false)] [InlineData("header.vip == true && bean:rules.IsGold(header.name)", "ann", true)] [InlineData("${bean:rules.IsGold(header.name)}", "ann", true)] public void AsACondition_BareAndTemplated(string condition, string name, bool expected) { PredicateFactory.FromString(condition).Matches(Message(null, ("name", name), ("vip", true))).Should().Be(expected); } [Fact] public void AMissingBean_NamesTheReference() { var act = () => new StringExpression("${bean:absent.Gross(1, 2)}").Evaluate(Message()); act.Should().Throw() .WithMessage("bean:absent.Gross: 'absent' is not in the context registry. Register it with AddToRegistry or a declaration."); } [Theory] [InlineData("${bean:rules.Missing(1)}", "*'#rules' has no public method 'Missing' taking 1 argument(s)*")] [InlineData("${bean:rules.Gross(1)}", "*'#rules' has no public method 'Gross' taking 1 argument(s)*")] public void AWrongMethodOrArity_IsTheBindingError(string template, string message) { var act = () => new StringExpression(template).Evaluate(Message()); act.Should().Throw().WithMessage(message); } [Theory] [InlineData("${bean:rules.CheckAsync(header.name)}", "Task`1")] [InlineData("${bean:rules.CountAsync()}", "ValueTask`1")] public void AnAsyncMethod_IsRefused_PointingToTheStep(string template, string returnType) { var act = () => new StringExpression(template).Evaluate(Message(null, ("name", "ann"))); act.Should().Throw() .WithMessage($"*returns {returnType}: a bean: call in an expression is synchronous. Call an asynchronous method as a step: expression.Evaluate(Message()); act.Should().Throw(); _rules.Calls.Should().Be(0, "nothing ran"); } [Fact] public void WithoutAContext_TheErrorSaysWhy() { var act = () => new StringExpression("${bean:rules.Gross(1, 2)}").Evaluate(new Exchange()); act.Should().Throw().WithMessage("*has no route context*"); } [Fact] public async Task EachContext_ResolvesItsOwnBean_ThroughOneCompiledExpression() { await using var other = new RouteContext(); var otherRules = new PricingRules(); other.AddToRegistry("rules", otherRules); var expression = new StringExpression("${bean:rules.Gross(1, 1)}"); expression.Evaluate(Message()); expression.Evaluate(new Exchange(new Message("x")) { Context = other }); _rules.Calls.Should().Be(1); otherRules.Calls.Should().Be(1); } [Fact] public async Task InACSharpRoute_FilterAndSetBody() { var seen = new List(); _context.AddRoutes(r => r.From("direct://bean-fn") .Filter("bean:rules.IsGold(header.name)") .SetBody(new StringExpression("${bean:rules.Gross(header.qty, 2)}")) .Process(e => seen.Add(e.In.Body)) .EndFilter()); await _context.Start(); var producer = _context.GetEndpoint("direct://bean-fn").CreateProducer(); await producer.Start(); foreach (var name in new[] { "ann", "bob" }) { var exchange = new Exchange(new Message("in")); exchange.In.Headers["name"] = name; exchange.In.Headers["qty"] = 5; await producer.Process(exchange); } seen.Should().Equal(10.0); } } Path: redb-route/tests/redb.Route.Tests/Expressions/BeanMethodExpressionTests.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/Expressions/BeanMethodExpressionTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Expressions; using redb.Route.Predicates; namespace redb.Route.Tests.Expressions; /// A bean whose conditions and values Method() calls, sync and async. public class MembershipRules { public bool IsGold(string? name) => name == "ann"; public double Gross(int qty, double price) => qty * price; public async Task IsGoldAsync(string? name) { await Task.Yield(); return name == "ann"; } } /// /// Method(reference, spec), Camel's method(ref, "name") (stage 2 step f): a registry bean's method as an /// expression and a condition, through the binding and resolution of the bean: function; in a condition a /// Task<bool> method is awaited, in a value position the call is synchronous. /// public sealed class BeanMethodExpressionTests : IAsyncLifetime { private readonly RouteContext _context = new(); public Task InitializeAsync() { _context.AddToRegistry("rules", new MembershipRules()); return Task.CompletedTask; } public async Task DisposeAsync() => await _context.DisposeAsync(); private Exchange Message(params (string Key, object? Value)[] headers) { var exchange = new Exchange(new Message("in")) { Context = _context }; foreach (var (key, value) in headers) exchange.In.Headers[key] = value; return exchange; } private async Task> Run(Action routes, string from, params string[] names) { var seen = new List(); _context.AddToRegistry("seen", seen); _context.AddRoutes(routes); await _context.Start(); var producer = _context.GetEndpoint(from).CreateProducer(); await producer.Start(); foreach (var name in names) { var exchange = new Exchange(new Message(name)); exchange.In.Headers["name"] = name; exchange.In.Headers["qty"] = 4; await producer.Process(exchange); if (exchange.Properties.TryGetValue("hit", out var hit)) seen.Add($"{name}:{hit}"); } return seen; } [Fact] public async Task Filter_TakesMethod_WithoutAmbiguity() { var seen = await Run(r => r.From("direct://m-filter") .Filter(RouteBuilder.Method("#rules", "IsGold(${header.name})")) .Process(e => e.Properties["hit"] = "gold") .EndFilter(), "direct://m-filter", "ann", "bob"); seen.Should().Equal("ann:gold"); } [Fact] public async Task Filter_AwaitsATaskReturningCondition() { var seen = await Run(r => r.From("direct://m-async") .Filter(RouteBuilder.Method("rules", "IsGoldAsync(${header.name})")) .Process(e => e.Properties["hit"] = "gold") .EndFilter(), "direct://m-async", "ann", "bob"); seen.Should().Equal("ann:gold"); } [Fact] public async Task ChoiceWhen_TakesMethod() { var seen = await Run(r => r.From("direct://m-choice") .Choice() .When(RouteBuilder.Method("#rules", "IsGold(${header.name})")).Process(e => e.Properties["hit"] = "gold") .Otherwise().Process(e => e.Properties["hit"] = "std") .EndChoice(), "direct://m-choice", "ann", "bob"); seen.Should().Equal("ann:gold", "bob:std"); } private async Task> Validated(Func validate, string from) { var outcomes = new List(); _context.AddRoutes(r => validate(r.From(from)).Process(e => e.Properties["hit"] = "valid")); await _context.Start(); var producer = _context.GetEndpoint(from).CreateProducer(); await producer.Start(); foreach (var name in new[] { "ann", "bob" }) { var exchange = new Exchange(new Message(name)); exchange.In.Headers["name"] = name; string? error = null; try { await producer.Process(exchange); } catch (redb.Route.Validation.ValidationException ex) { error = ex.Message; } outcomes.Add($"{name}:{(exchange.Properties.ContainsKey("hit") ? "valid" : error ?? exchange.Exception?.Message ?? "stopped")}"); } return outcomes; } [Fact] public async Task Validate_TakesMethod_AndAwaitsATaskReturningCondition() { var outcomes = await Validated(r => r.Validate(RouteBuilder.Method("#rules", "IsGoldAsync(${header.name})"), "not gold"), "direct://m-validate-async"); outcomes[0].Should().Be("ann:valid"); outcomes[1].Should().StartWith("bob:").And.Contain("not gold"); } [Fact] public async Task Validate_TakesAnExpressionCondition() { var outcomes = await Validated(r => r.Validate(RouteBuilder.Expr("header.name == 'ann'"), "not ann"), "direct://m-validate-expr"); outcomes[0].Should().Be("ann:valid"); outcomes[1].Should().StartWith("bob:").And.Contain("not ann"); } [Fact] public async Task Validate_WithAPredicate_IsUnchanged() { var outcomes = await Validated(r => r.Validate(PredicateFactory.FromString("header.name == 'ann'"), "not ann"), "direct://m-validate-predicate"); outcomes[0].Should().Be("ann:valid"); outcomes[1].Should().StartWith("bob:").And.Contain("not ann"); } [Fact] public async Task SetBody_TakesTheValue_WithItsType() { object? body = null; _context.AddRoutes(r => r.From("direct://m-value") .SetBody(RouteBuilder.Method("#rules", "Gross(${header.qty}, 2.5)")) .Process(e => body = e.In.Body)); await _context.Start(); var producer = _context.GetEndpoint("direct://m-value").CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("x")); exchange.In.Headers["qty"] = 4; await producer.Process(exchange); body.Should().Be(10.0); } [Fact] public void AValuePosition_RefusesATaskReturningMethod_AsTheFunctionDoes() { var expression = RouteBuilder.Method("#rules", "IsGoldAsync(${header.name})"); expression.Invoking(e => e.Evaluate(Message(("name", "ann")))) .Should().Throw() .WithMessage("bean:rules.IsGoldAsync returns Task`1: a bean: call in an expression is synchronous*"); expression.Invoking(e => e.Matches(Message(("name", "ann")))) .Should().Throw().WithMessage("*synchronous*"); } [Fact] public async Task TheConditionPath_IsTheAsyncPredicate() { var predicate = PredicateFactory.FromExpression(RouteBuilder.Method("#rules", "IsGoldAsync(${header.name})")); (await predicate.MatchesAsync(Message(("name", "ann")))).Should().BeTrue(); (await predicate.MatchesAsync(Message(("name", "bob")))).Should().BeFalse(); } [Theory] [InlineData("Acme.Rules, Acme")] [InlineData("Acme.Rules")] public void TheTypeForm_IsRefused(string reference) { var act = () => RouteBuilder.Method(reference, "IsGold(body)"); act.Should().Throw().WithMessage("*in an expression the bean is a registry name*"); } [Fact] public void ItsTemplate_IsTheSameCall() { var method = RouteBuilder.Method("#rules", "Gross(${header.qty}, 2.5)"); method.ToTemplateString().Should().Be("${bean:rules.Gross(${header.qty}, 2.5)}"); new StringExpression(method.ToTemplateString()).Evaluate(Message(("qty", 2))).Should().Be(5.0); } [Fact] public void AMissingBeanOrMethod_IsTheCallsError() { RouteBuilder.Method("#absent", "IsGold(body)").Invoking(e => e.Evaluate(Message())) .Should().Throw().WithMessage("bean:absent.IsGold: 'absent' is not in the context registry*"); RouteBuilder.Method("#rules", "IsGold(body, body)").Invoking(e => e.Evaluate(Message())) .Should().Throw().WithMessage("*'#rules' has no public method 'IsGold' taking 2 argument(s)*"); } } Path: redb-route/tests/redb.Route.Tests/Expressions/ContextPrefixResolverTests.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/Expressions/ContextPrefixResolverTests.cs ---- using redb.Route.Core; using redb.Route.Expressions; using redb.Route.Extensions; namespace redb.Route.Tests.Expressions; /// /// A ${prefix.rest} resolver registered on a route context serves the expressions of that context's exchanges /// only, and goes with the context: nothing of it is left in the process-wide resolvers. /// public sealed class ContextPrefixResolverTests { private static Exchange On(RouteContext context) => new(new Message("body")) { Context = context }; [Fact] public void An_exchange_of_the_context_resolves_the_prefix_through_the_context() { using var context = new RouteContext(); context.RegisterPrefixResolver("order.", (_, rest) => $"order:{rest}"); ExpressionResolver.ProcessTemplate("${order.id}", On(context)).Should().Be("order:id"); } [Fact] public void An_exchange_of_another_context_does_not_see_the_prefix() { using var owner = new RouteContext(); using var other = new RouteContext(); owner.RegisterPrefixResolver("tenant.", (_, _) => "owner"); var exchange = On(other); exchange.Properties["tenant.name"] = "plain property"; ExpressionResolver.ProcessTemplate("${tenant.name}", exchange).Should().Be("plain property"); } [Fact] public void The_context_prefix_wins_over_a_process_wide_one_and_leaves_it_in_place() { var prefix = $"shadow{Guid.NewGuid():N}."; ExpressionResolver.RegisterPrefixResolver(prefix, (_, _) => "process"); try { using var context = new RouteContext(); context.RegisterPrefixResolver(prefix, (_, _) => "context"); ExpressionResolver.ProcessTemplate($"${{{prefix}x}}", On(context)).Should().Be("context"); ExpressionResolver.ProcessTemplate($"${{{prefix}x}}", new Exchange(new Message("b"))).Should().Be("process"); } finally { ExpressionResolver.UnregisterPrefixResolver(prefix); } } [Fact] public void The_resolvers_are_a_service_of_the_context_and_one_per_context() { using var context = new RouteContext(); var first = ExpressionPrefixResolvers.For(context); ExpressionPrefixResolvers.For(context).Should().BeSameAs(first); context.GetService().Should().BeSameAs(first); var bad = () => first.Register("noDot", (_, _) => null); bad.Should().Throw(); } } Path: redb-route/tests/redb.Route.Tests/Expressions/DottedPathArgumentTests.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/Expressions/DottedPathArgumentTests.cs ---- using AwesomeAssertions; using redb.Route.Core; using redb.Route.Expressions; namespace redb.Route.Tests.Expressions; /// /// A dotted path splits at its separators only (findings register row 33): a dot inside a method's parentheses, in a /// quoted argument or in square brackets belongs to the argument, so list.contains(5.0) is one method call. /// public sealed class DottedPathArgumentTests { private static Exchange Message() { var exchange = new Exchange(new Message("x")); exchange.In.Headers["ints"] = new List { 3 }; exchange.In.Headers["doubles"] = new List { 2.5 }; exchange.In.Headers["names"] = new List { "a.b" }; exchange.In.Headers["s"] = "x.a.b"; return exchange; } [Theory] [InlineData("${header.ints.contains(3.0)}", true)] [InlineData("${header.ints.contains(5.0)}", false)] [InlineData("${header.doubles.contains(2.5)}", true)] [InlineData("${header.doubles.contains(7.5)}", false)] [InlineData("${header.names.contains('a.b')}", true)] [InlineData("${header.names.contains('a.c')}", false)] [InlineData("${header.s.contains('a.b')}", true)] [InlineData("${header.s.contains(\"a.c\")}", false)] public void AMethodArgument_KeepsItsDots(string template, bool expected) { new StringExpression(template).Evaluate(Message()).Should().Be(expected); } [Fact] public void ThePathStillSplitsAtItsSeparators() { var exchange = Message(); exchange.In.Headers["user"] = new Dictionary { ["Name"] = "Ann" }; new StringExpression("${header.user.Name.length()}").Evaluate(exchange).Should().Be(3); } } Path: redb-route/tests/redb.Route.Tests/Expressions/DottedPropertyNameTests.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/Expressions/DottedPropertyNameTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Expressions; namespace redb.Route.Tests.Expressions; /// /// A property whose name contains a dot (omni.PollInterval, the shape a module uses to /// namespace its settings). Reported 2026-09-24: written bare — property.omni.PollInterval in /// a delay or a setProperty — it read as empty, while the same name inside /// ${...}, in a comparison, and any dotted header resolved fine. The bare value path /// went straight to nested access, so it looked for a property named omni and a member /// PollInterval on it; every other path asks for the literal name first. /// [Collection("ExpressionResolver")] public class DottedPropertyNameTests : IDisposable { public DottedPropertyNameTests() => ExpressionResolver.ClearAllCaches(); public void Dispose() { ExpressionResolver.ClearAllCaches(); GC.SuppressFinalize(this); } private static IExchange WithProperty(string name, object? value) { var exchange = new Exchange(new Message("body")); exchange.Properties[name] = value; return exchange; } private sealed class Settings { public int PollInterval { get; set; } } [Fact] public void A_bare_expression_reads_a_property_whose_name_holds_a_dot() { var exchange = WithProperty("omni.PollInterval", 5000); new StringExpression("property.omni.PollInterval").Evaluate(exchange).Should().Be(5000); } [Fact] public void The_template_form_reads_the_same_property() { var exchange = WithProperty("omni.PollInterval", 5000); // Already worked — kept so the two forms are asserted side by side and stay in step. new StringExpression("${property.omni.PollInterval}").Evaluate(exchange).Should().Be("5000"); } [Fact] public void A_nested_member_is_still_read_when_no_property_carries_the_literal_name() { var exchange = WithProperty("omni", new Settings { PollInterval = 700 }); new StringExpression("property.omni.PollInterval").Evaluate(exchange).Should().Be(700); } [Fact] public void The_literal_name_wins_over_a_nested_member_of_the_same_shape() { var exchange = WithProperty("omni", new Settings { PollInterval = 700 }); exchange.Properties["omni.PollInterval"] = 5000; // The rule the smart resolver has always followed for headers and for templates: a property // written with that exact name is what the author meant. new StringExpression("property.omni.PollInterval").Evaluate(exchange).Should().Be(5000); } [Fact] public void A_name_that_matches_nothing_is_null_rather_than_a_throw() { var exchange = WithProperty("other", 1); new StringExpression("property.omni.PollInterval").Evaluate(exchange).Should().BeNull(); } [Fact] public void A_dotted_header_keeps_reading_the_literal_name() { var exchange = new Exchange(new Message("body")); exchange.In.Headers["omni.PollInterval"] = 5000; new StringExpression("header.omni.PollInterval").Evaluate(exchange).Should().Be(5000); } } Path: redb-route/tests/redb.Route.Tests/Expressions/EnvNamespaceTests.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/Expressions/EnvNamespaceTests.cs ---- using AwesomeAssertions; using redb.Route.Core; using redb.Route.Expressions; using redb.Route.Expressions.Ast; using redb.Route.Predicates; namespace redb.Route.Tests.Expressions; /// /// env:NAME (findings register row 34 point 1, closing row 35): the OS environment variable, as Apache Camel's /// ${env:NAME}; null when it is not set; read on every evaluation; refused under the template sandbox. /// Until 4.7.0 the engine rendered ${env:NAME} empty, so an HTTP AuthToken = "${env:BILLING_TOKEN}" sent an /// empty bearer token. /// public sealed class EnvNamespaceTests : IDisposable { private readonly string _name = "REDB_ENV_TEST_" + Guid.NewGuid().ToString("N"); public EnvNamespaceTests() => Environment.SetEnvironmentVariable(_name, "from-env"); public void Dispose() => Environment.SetEnvironmentVariable(_name, null); private static Exchange Message() => new(new Message("x")); [Fact] public void AWholePlaceholder_IsTheValue() { new StringExpression("${env:" + _name + "}").Evaluate(Message()).Should().Be("from-env"); } [Fact] public void InText_TheValueIsRendered() { ExpressionResolver.ProcessTemplate("Bearer ${env:" + _name + "}", Message()).Should().Be("Bearer from-env"); } [Fact] public void AMissingVariable_IsNull_AndRendersEmpty() { var missing = "REDB_ENV_MISSING_" + Guid.NewGuid().ToString("N"); new StringExpression("${env:" + missing + "}").Evaluate(Message()).Should().BeNull(); ExpressionResolver.ProcessTemplate("[${env:" + missing + "}]", Message()).Should().Be("[]"); } [Fact] public void InACondition() { PredicateFactory.FromString("env:" + _name + " == 'from-env'").Matches(Message()).Should().BeTrue(); } [Fact] public void IsReadOnEveryEvaluation() { var expression = new StringExpression("${env:" + _name + "}"); expression.Evaluate(Message()).Should().Be("from-env"); Environment.SetEnvironmentVariable(_name, "changed"); expression.Evaluate(Message()).Should().Be("changed"); } [Fact] public void UnderTheSandbox_IsRefused() { var expression = new StringExpression("${env:" + _name + "}"); using var sandbox = ExpressionSandbox.Enter(); var act = () => expression.Evaluate(Message()); act.Should().Throw().WithMessage($"'env:{_name}' cannot be read here: the expression runs in a sandbox*"); } [Fact] public void AParenthesis_IsAnError() { var act = () => new Parser(new Tokenizer("env:PATH()").GetAllTokens()).Parse(); act.Should().Throw().WithMessage("env:PATH names an environment variable and calls nothing (position 1 within the expression)."); } [Fact] public void Ternary_WithSpaces_ReadsAsBefore() { new Tokenizer("flag ? env : other").GetAllTokens().Where(t => t.Type != TokenType.Eof).Select(t => t.Type) .Should().Equal(TokenType.Identifier, TokenType.Operator, TokenType.Identifier, TokenType.Colon, TokenType.Identifier); } [Fact] public void AnHttpStyleTokenExpression_NowCarriesTheValue() { // What HttpConnectionFactory.AuthToken does with a ${...} value: a StringExpression resolved per request. new StringExpression("${env:" + _name + "}").Evaluate(Message()).Should().Be("from-env"); } } Path: redb-route/tests/redb.Route.Tests/Expressions/EqualsIgnoreCaseAndRangeTests.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/Expressions/EqualsIgnoreCaseAndRangeTests.cs ---- using AwesomeAssertions; using redb.Route.Core; using redb.Route.Expressions; using redb.Route.Expressions.Ast; using redb.Route.Predicates; namespace redb.Route.Tests.Expressions; /// /// The comparison operators of Apache Camel's Simple: =~ (equals ignoring case: two strings ignore case, any /// other pair is ==) and range / not range over a quoted 'from..to' literal of two /// numbers, inclusive, read at compile time. range is an operator only right after an operand. /// public sealed class EqualsIgnoreCaseAndRangeTests { private static Exchange Message() { var exchange = new Exchange(new Message("payload")); exchange.In.Headers["s"] = "Hello"; exchange.In.Headers["n"] = 7; exchange.In.Headers["d"] = 2.5; exchange.In.Headers["m"] = 10m; exchange.In.Headers["t"] = "12"; exchange.In.Headers["word"] = "abc"; exchange.In.Headers["nothing"] = null; exchange.In.Headers["range"] = "a header named range"; return exchange; } private static bool Condition(string condition) => PredicateFactory.FromString(condition).Matches(Message()); private static AstNode Parse(string expression) => new Parser(new Tokenizer(expression).GetAllTokens()).Parse(); [Theory] [InlineData("header.s =~ 'hello'", true)] [InlineData("header.s =~ 'HELLO'", true)] [InlineData("header.s =~ 'help'", false)] [InlineData("header.s=~'hello'", true)] [InlineData("header.s == 'hello'", false)] [InlineData("header.n =~ 7", true)] [InlineData("header.n =~ '7'", true)] [InlineData("header.n =~ 8", false)] [InlineData("header.nothing =~ null", true)] [InlineData("header.nothing =~ 'x'", false)] [InlineData("!(header.s =~ 'hello')", false)] [InlineData("${header.s =~ 'HELLO'}", true)] public void EqualsIgnoreCase(string condition, bool expected) { Condition(condition).Should().Be(expected); } [Theory] [InlineData("header.n range '1..10'", true)] [InlineData("header.n range '7..7'", true)] [InlineData("header.n range '8..10'", false)] [InlineData("header.n range '1..6'", false)] [InlineData("header.n RANGE '1..10'", true)] [InlineData("header.d range '2.5..3'", true)] [InlineData("header.d range '1.5..2.4'", false)] [InlineData("header.m range '-5..10'", true)] [InlineData("header.t range '10..20'", true)] [InlineData("header.n range ' 1 .. 10 '", true)] [InlineData("header.n + 5 range '10..12'", true)] [InlineData("header.n not range '1..10'", false)] [InlineData("header.n NOT RANGE '8..10'", true)] [InlineData("header.nothing range '1..10'", false)] [InlineData("header.nothing not range '1..10'", true)] [InlineData("header.n range '1..10' && header.s =~ 'hello'", true)] [InlineData("${header.n range '1..10'}", true)] public void Range(string condition, bool expected) { Condition(condition).Should().Be(expected); } [Fact] public void Range_ATextThatIsNotANumber_IsAnErrorNamingIt() { var act = () => Condition("header.word range '1..10'"); act.Should().Throw() .WithMessage("header.word range '1..10': the value 'abc' (String) is not a number."); } [Theory] [InlineData("header.n range 5", "range takes a quoted 'from..to' literal, as in header.n range '1..10' (position 16 within the expression).")] [InlineData("header.n range", "range takes a quoted 'from..to' literal, as in header.n range '1..10' (position 15 within the expression).")] [InlineData("header.n range '1-10'", "range '1-10' is not 'from..to' with two numbers, as in '1..10' (position 16 within the expression).")] [InlineData("header.n range 'a..b'", "range 'a..b' is not 'from..to' with two numbers, as in '1..10' (position 16 within the expression).")] [InlineData("header.n range '10..1'", "range '10..1' starts above its end: write the smaller number first (position 16 within the expression).")] public void Range_AMalformedLiteral_IsAnErrorAtCompile(string expression, string message) { var act = () => Parse(expression); act.Should().Throw().WithMessage(message); } [Fact] public void Range_IsANameEverywhereElse() { Parse("header.range").Should().BeOfType(); Parse("range").Should().BeOfType(); new StringExpression("${header.range}").Evaluate(Message()).Should().Be("a header named range"); Parse("not range").Should().NotBeOfType(); } [Fact] public void Range_ReadsItsEndsOnce() { Parse("header.n not range '1.5..20'").Should().BeOfType() .Which.Should().Match(r => r.From == 1.5m && r.To == 20m && r.Negated); } [Theory] [InlineData("header.s =~ 'x'")] [InlineData("header.n range '1..2'")] [InlineData("header.n not range '1..2'")] public void TheDetector_SeesTheOperators(string expression) { ExpressionResolver.ContainsComparisonOrWordLogicOperator(expression).Should().BeTrue(); } [Theory] [InlineData("header.range")] [InlineData("'a range b'")] public void TheDetector_LeavesNamesAndLiterals(string expression) { ExpressionResolver.ContainsComparisonOrWordLogicOperator(expression).Should().BeFalse(); } } Path: redb-route/tests/redb.Route.Tests/Expressions/ExpressionCorpus.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/Expressions/ExpressionCorpus.cs ---- using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Tests.Expressions; /// /// The shared corpus of expression forms used by the characterisation net. One list of forms, run /// through every position of the language, so a difference between positions is visible as a row /// rather than having to be remembered. /// /// Adding a form here is cheap and is the right reflex: the snapshot records what it does today, /// and any later change to the expression system shows up as a diff on that snapshot. /// /// internal static class ExpressionCorpus { /// A person, used to exercise member access behind a header, a property and the body. internal sealed class Person { public string Name { get; init; } = "ann"; public int Age { get; init; } = 30; public bool Active { get; init; } = true; public Person? Manager { get; init; } /// A public field, not a property: member access has to read both alike. public int Level = 3; } /// Which exchange a form is evaluated against. internal enum Fixture { /// Body is a ; the default. Object, /// Body is a plain string. Text, /// Body is a JSON document. Json, /// Body is an XML document. Xml } /// One form of the language, with the fixture it is meaningful against. /// The expression text exactly as an author would write it. /// Section heading in the snapshot, so the file reads as a document. /// Which exchange to evaluate it against. /// /// True when the form already carries its own ${...}, as the Apache Camel idiom does by /// putting the operator outside the placeholder. Wrapping such a form again would only measure /// nonsense, so the template column is skipped for it. /// internal readonly record struct Entry( string Form, string Group, Fixture Fixture = Fixture.Object, bool Templated = false); internal static IExchange CreateExchange(Fixture fixture) { object body = fixture switch { Fixture.Text => "payload", Fixture.Json => "{\"order\":{\"id\":7,\"total\":150.5,\"tags\":[\"a\",\"b\"]}}", Fixture.Xml => "7150.5", _ => new Person { Name = "ann", Age = 30, Active = true, Manager = new Person { Name = "bob", Age = 51 } } }; var exchange = new Exchange(new Message(body)); exchange.In.Headers["a"] = 42; exchange.In.Headers["b"] = 3; exchange.In.Headers["zero"] = 0; exchange.In.Headers["neg"] = -7; exchange.In.Headers["dbl"] = 2.5; exchange.In.Headers["flag"] = true; exchange.In.Headers["off"] = false; exchange.In.Headers["s"] = "hello"; exchange.In.Headers["empty"] = ""; exchange.In.Headers["quoted"] = "a > b"; exchange.In.Headers["worded"] = "x AND y"; exchange.In.Headers["ct"] = "application/json"; exchange.In.Headers["dotted.key"] = "literal-dot"; exchange.In.Headers["Content-Type"] = "text/xml"; exchange.In.Headers["X-Request-Id"] = "req-1"; exchange.In.Headers["a+b"] = "plus-name"; exchange.In.Headers["user"] = new Person(); exchange.In.Headers["list"] = new List { 1, 2, 3, 4, 5 }; exchange.Properties["count"] = 7; exchange.Properties["zero"] = 0; exchange.Properties["flag"] = false; exchange.Properties["name"] = "abcd"; exchange.Properties["items"] = new List { "p", "q", "r" }; exchange.Properties["cfg"] = new Dictionary { ["enabled"] = true, ["limit"] = 5 }; exchange.Properties["user"] = new Person(); exchange.Exception = new InvalidOperationException("boom"); return exchange; } internal static IReadOnlyList Entries { get; } = Build(); private static Entry[] Build() => [ // ── literals ────────────────────────────────────────────────────────── new("42", "literals"), new("-7", "literals"), new("2.5", "literals"), new("true", "literals"), new("false", "literals"), new("'hello'", "literals"), new("\"hello\"", "literals"), new("'a > b'", "literals"), new("'x AND y'", "literals"), new("hello", "literals"), new("plain text", "literals"), // ── strings that look like operators but are configuration ──────────── new("a>b", "config-shaped literals"), new("x", "config-shaped literals"), new("", "config-shaped literals"), new("key=value", "config-shaped literals"), new("application/json", "config-shaped literals"), new("text/plain; charset=utf-8", "config-shaped literals"), new("some/path/file.txt", "config-shaped literals"), new("https://example.com/a?b=c", "config-shaped literals"), new("2026-08-28", "config-shaped literals"), new("black and white", "config-shaped literals"), new("yes or no", "config-shaped literals"), new("BLACK AND WHITE", "config-shaped literals"), // ── accessors ───────────────────────────────────────────────────────── new("header.a", "accessors"), new("header.zero", "accessors"), new("header.neg", "accessors"), new("header.flag", "accessors"), new("header.off", "accessors"), new("header.s", "accessors"), new("header.empty", "accessors"), new("header.missing", "accessors"), new("header.dotted.key", "accessors"), new("header.Content-Type", "accessors"), new("header.X-Request-Id", "accessors"), new("header.a+b", "accessors"), new("property.count", "accessors"), new("property.zero", "accessors"), new("property.flag", "accessors"), new("property.missing", "accessors"), new("body", "accessors", Fixture.Text), new("body", "accessors"), new("exception.Message", "accessors"), new("contentType", "accessors"), // ── member access behind an accessor ────────────────────────────────── new("header.user.Name", "member access"), new("header.user.Age", "member access"), new("header.user.Active", "member access"), new("header.user.Manager", "member access"), new("header.list.Count", "member access"), new("header.s.Length", "member access"), new("property.user.Name", "member access"), new("property.cfg.enabled", "member access"), new("property.cfg.limit", "member access"), new("property.items.Count", "member access"), new("body.Name", "member access"), new("body.Age", "member access"), new("body.Manager.Name", "member access"), // a public field, read through every root the same way as a property new("header.user.Level", "member access"), new("property.user.Level", "member access"), new("body.Level", "member access"), new("body.Manager.Level", "member access"), // ── comparison, spaced ──────────────────────────────────────────────── new("header.a > 10", "comparison spaced"), new("header.a < 10", "comparison spaced"), new("header.a >= 42", "comparison spaced"), new("header.a <= 42", "comparison spaced"), new("header.a == 42", "comparison spaced"), new("header.a != 42", "comparison spaced"), new("header.s == 'hello'", "comparison spaced"), new("header.s != 'hello'", "comparison spaced"), new("header.missing == null", "comparison spaced"), new("header.a != null", "comparison spaced"), new("1 > 0", "comparison spaced"), // ── comparison, whitespace variations ───────────────────────────────── new("header.a>10", "comparison whitespace"), new("header.a>=42", "comparison whitespace"), new("header.a<=42", "comparison whitespace"), new("header.a==42", "comparison whitespace"), new("header.a!=42", "comparison whitespace"), new("header.a > 10", "comparison whitespace"), new("header.a\t>\t10", "comparison whitespace"), new("header.a\n>\n10", "comparison whitespace"), new(" header.a>10 ", "comparison whitespace"), new("header.a >10", "comparison whitespace"), new("header.a> 10", "comparison whitespace"), new("1>0", "comparison whitespace"), // ── comparison against member access ────────────────────────────────── new("header.user.Age > 18", "comparison member"), new("header.user.Age>18", "comparison member"), new("header.list.Count > 3", "comparison member"), new("property.cfg.limit > 3", "comparison member"), new("property.cfg.limit>3", "comparison member"), new("property.items.Count > 2", "comparison member"), new("header.s.Length > 3", "comparison member"), new("body.Age > 18", "comparison member"), new("body.Age>18", "comparison member"), // ── operators inside quoted literals ────────────────────────────────── new("header.quoted == 'a > b'", "quoted operators"), new("header.quoted=='a > b'", "quoted operators"), new("header.quoted == 'a < b'", "quoted operators"), new("header.worded == 'x AND y'", "quoted operators"), new("header.worded == 'x OR y'", "quoted operators"), new("header.ct == 'application/json'", "quoted operators"), new("header.ct=='application/json'", "quoted operators"), // ── word logic ──────────────────────────────────────────────────────── new("header.a > 10 AND header.b < 5", "word logic"), new("header.a>10 AND header.b<5", "word logic"), new("header.a>10 AND header.b<5", "word logic"), new("header.a>10\tAND\theader.b<5", "word logic"), new("header.a>10 and header.b<5", "word logic"), new("header.a > 10 OR header.b > 100", "word logic"), new("header.a > 10 XOR header.b > 100", "word logic"), new("property.count > 5 OR property.flag", "word logic"), new("NOT header.flag", "word logic"), new("!header.flag", "word logic"), new("header.a > 10 AND NOT header.off", "word logic"), new("header.a > 10 AND !header.off", "word logic"), new("header.a AND header.b", "word logic"), // ── parentheses ─────────────────────────────────────────────────────── new("(header.a > 10)", "parentheses"), new("(header.a > 10) AND (header.b < 5)", "parentheses"), new("(header.a>10) AND (header.b<5)", "parentheses"), new("(header.a > 10 AND header.b < 5)", "parentheses"), new("(header.a > 100) OR (header.b < 5)", "parentheses"), new("((header.a > 10))", "parentheses"), new("(header.a + header.b) * 2", "parentheses"), // ── arithmetic ──────────────────────────────────────────────────────── new("header.a + header.b", "arithmetic"), new("header.a+header.b", "arithmetic"), new("header.a - 2", "arithmetic"), new("header.a-2", "arithmetic"), new("header.a * 2", "arithmetic"), new("header.a*2", "arithmetic"), new("header.a / 2", "arithmetic"), new("header.a/2", "arithmetic"), new("header.a + header.b * 2", "arithmetic"), new("header.dbl * 2", "arithmetic"), new("-header.a", "arithmetic"), new("header.a + header.b > 40", "arithmetic"), new("header.a+header.b>40", "arithmetic"), // Modulo, in every spacing, with negatives, by zero, and as a condition. new("header.a % 5", "arithmetic"), new("header.a%5", "arithmetic"), new("header.neg % 3", "arithmetic"), new("header.dbl % 2", "arithmetic"), new("header.a % header.zero", "arithmetic"), new("header.a % 2 == 0", "arithmetic"), new("header.a%2==0", "arithmetic"), // ── functions ───────────────────────────────────────────────────────── new("count(property.items)", "functions"), new("count(property.items) > 2", "functions"), new("count(property.items)>2", "functions"), new("length(property.name)", "functions"), new("length(property.name) > 3", "functions"), new("contains(header.s, 'ell')", "functions"), new("upper(header.s)", "functions"), new("lower(header.s)", "functions"), new("logical(header.a > 10)", "functions"), new("logical(header.a>10)", "functions"), // The forms where the two compilers disagree. In the template position these still go // through the hand-written branch, which answers wrongly; the AST answers correctly, and // these lines are what will move when the second compiler is removed. new("logical(header.a > 100)", "functions"), new("logical((header.a > 10) AND (header.b < 5))", "functions"), new("logical(header.a + header.b > 40)", "functions"), new("logical(header.worded == 'x AND y')", "functions"), new("jpath($.order.id)", "functions", Fixture.Json), new("xpath(/order/id)", "functions", Fixture.Xml), // Datediff over literal dates (deterministic; uuid() is impure and is // pinned by LanguageAdditionsF15Tests instead of the snapshot). new("datediff('2026-01-03', '2026-01-01', 'days')", "functions"), new("datediff('2026-01-01', '2026-01-03', 'hours')", "functions"), new("datediff('2026-01-01T06:00:00', '2026-01-01T00:00:00', 'days')", "functions"), new("datediff('2026-01-02', '2026-01-01', 'fortnights')", "functions"), // ── increments: on headers and on properties, prefix and postfix ───── new("header.a++", "increments"), new("++header.a", "increments"), new("header.a--", "increments"), new("--header.a", "increments"), new("property.count++", "increments"), new("++property.count", "increments"), // ── min / max: two scalars or one collection ────────────────────────── new("min(header.a, header.b)", "min max"), new("max(header.a, header.b)", "min max"), new("min(header.list)", "min max"), new("max(header.list)", "min max"), new("min(property.items)", "min max"), new("max(property.missing)", "min max"), // ── decimal literals inside function arguments (parsed culture-invariantly) ─── new("max(2.5, 1)", "decimal literals"), new("round(2.567, 2)", "decimal literals"), new("abs(-2.5)", "decimal literals"), new("2.5 + 1", "decimal literals"), // ── ternary and null coalescing ─────────────────────────────────────── new("header.a > 10 ? 'big' : 'small'", "ternary"), new("header.a>10 ? 'big' : 'small'", "ternary"), new("header.a > 100 ? 'big' : 'small'", "ternary"), new("length(property.name) > 3 ? true : false", "ternary"), new("header.missing ?? 5", "ternary"), new("header.a ?? 5", "ternary"), new("header.missing ?? 'dflt'", "ternary"), // ── index access ────────────────────────────────────────────────────── new("property.items[0]", "index access"), new("header.list[1]", "index access"), new("property.items[0] == 'p'", "index access"), // ── a whole-string placeholder, the historical way to write a condition ─── // The value is rendered to text and read back, so a comparison arrives as "True"/"False" // and RouteTruthiness parses it. Correct, but worth pinning: before the placeholder learned // to evaluate comparisons every one of these was the empty string, which made // Filter("${header.a > 10}") always false whatever the comparison said. new("${header.flag}", "whole-string placeholder", Templated: true), new("${header.off}", "whole-string placeholder", Templated: true), new("${header.zero}", "whole-string placeholder", Templated: true), new("${header.empty}", "whole-string placeholder", Templated: true), new("${header.missing}", "whole-string placeholder", Templated: true), new("${header.a > 10}", "whole-string placeholder", Templated: true), new("${header.a > 100}", "whole-string placeholder", Templated: true), new("${header.a>100}", "whole-string placeholder", Templated: true), new("${header.s == 'hello'}", "whole-string placeholder", Templated: true), new("${header.s == 'nope'}", "whole-string placeholder", Templated: true), new("${header.a > 10 AND header.b < 5}", "whole-string placeholder", Templated: true), // ── Apache Camel idioms: the operator lives outside the placeholder ─── new("${header.a} > 10", "camel idioms", Templated: true), new("${header.a} > 100", "camel idioms", Templated: true), new("${header.a} == 42", "camel idioms", Templated: true), new("${header.s} == 'hello'", "camel idioms", Templated: true), new("${header.s} == 'nope'", "camel idioms", Templated: true), new("${header.a} > 10 && ${header.b} < 5", "camel idioms", Templated: true), new("${header[Content-Type]}", "camel idioms", Templated: true), new("${headers.Content-Type}", "camel idioms", Templated: true), new("${headers[Content-Type]}", "camel idioms", Templated: true), new("${exchangeProperty.count}", "camel idioms", Templated: true), new("${property.count}", "camel idioms", Templated: true), new("${body}", "camel idioms", Fixture.Text, Templated: true), // ── truthiness: the one rule, §1.1 of the catalog ───────────────────── new("0", "truthiness"), new("1", "truthiness"), new("'0'", "truthiness"), new("'1'", "truthiness"), new("'no'", "truthiness"), new("'yes'", "truthiness"), new("'off'", "truthiness"), // Foreign words for yes/no are not boolean words: the set is English-only by design. new("'oui'", "truthiness"), new("'nein'", "truthiness"), new("'anything else'", "truthiness"), new("header.dbl", "truthiness"), new("header.zero AND header.a", "truthiness"), new("header.zero OR header.a", "truthiness"), new("logical(header.zero)", "truthiness"), new("logical(header.a)", "truthiness"), new("NOT header.zero", "truthiness"), // ── malformed ───────────────────────────────────────────────────────── new("header.a >", "malformed"), new("> 10", "malformed"), new("((((", "malformed"), new("1 +", "malformed"), new("~~~INVALID~~~", "malformed"), new("header.", "malformed"), new("count(", "malformed"), new("'unterminated", "malformed"), ]; } Path: redb-route/tests/redb.Route.Tests/Expressions/ExpressionDslIntegrationTests.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/Expressions/ExpressionDslIntegrationTests.cs ---- using AwesomeAssertions; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; using static redb.Route.Core.RouteBuilder; using redb.Route.Definitions; using redb.Route.Expressions; using redb.Route.Predicates; using redb.Route.Processors; namespace redb.Route.Tests.Expressions; /// /// Integration tests verifying that Expression/Predicate system is fully wired into DSL, /// OldRouteCompiler, and RouteContext end-to-end. /// [Collection("ExpressionResolver")] public class ExpressionDslIntegrationTests : IAsyncLifetime { private readonly RouteContext _context = new(); public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { await _context.DisposeAsync(); GC.SuppressFinalize(this); } // ─── Filter with IPredicate ─── [Fact] public async Task Filter_WithPredicate_MatchingExchange_PassesThrough() { object? captured = null; _context.AddRoutes(r => { r.From("direct://filter-pred-match") .Filter(new HeaderExpression("amount").isGreaterThan(100)) .Process(e => captured = e.In.Body); }); await _context.Start(); var exchange = new Exchange(new Message { Body = "high-value" }); exchange.In.Headers["amount"] = 200; var producer = _context.GetEndpoint("direct://filter-pred-match").CreateProducer(); await producer.Start(); await producer.Process(exchange); captured.Should().Be("high-value"); } [Fact] public async Task Filter_WithPredicate_NonMatchingExchange_Stops() { object? captured = null; _context.AddRoutes(r => { r.From("direct://filter-pred-no") .Filter(new HeaderExpression("amount").isGreaterThan(100)) .Process(e => captured = e.In.Body); }); await _context.Start(); var exchange = new Exchange(new Message { Body = "low-value" }); exchange.In.Headers["amount"] = 50; var producer = _context.GetEndpoint("direct://filter-pred-no").CreateProducer(); await producer.Start(); await producer.Process(exchange); captured.Should().BeNull(); } [Fact] public async Task Filter_WithStringExpression_MatchesTrue() { object? captured = null; _context.AddRoutes(r => { r.From("direct://filter-expr-yes") .Filter("${header.enabled}") .Process(e => captured = e.In.Body); }); await _context.Start(); var exchange = new Exchange(new Message { Body = "yes" }); exchange.In.Headers["enabled"] = "true"; var producer = _context.GetEndpoint("direct://filter-expr-yes").CreateProducer(); await producer.Start(); await producer.Process(exchange); captured.Should().Be("yes"); } [Fact] public async Task Filter_WithStringExpression_FiltersFalse() { object? captured = null; _context.AddRoutes(r => { r.From("direct://filter-expr-no") .Filter("${header.enabled}") .Process(e => captured = e.In.Body); }); await _context.Start(); var exchange = new Exchange(new Message { Body = "no" }); exchange.In.Headers["enabled"] = "false"; var producer = _context.GetEndpoint("direct://filter-expr-no").CreateProducer(); await producer.Start(); await producer.Process(exchange); captured.Should().BeNull(); } // ─── SetBody with IExpression ─── [Fact] public async Task SetBody_WithExpression_SetsBodyFromHeader() { object? captured = null; _context.AddRoutes(r => { r.From("direct://setbody-expr") .SetBody(new HeaderExpression("source")) .Process(e => captured = e.In.Body); }); await _context.Start(); var exchange = new Exchange(new Message { Body = "original" }); exchange.In.Headers["source"] = "from-header"; var producer = _context.GetEndpoint("direct://setbody-expr").CreateProducer(); await producer.Start(); await producer.Process(exchange); captured.Should().Be("from-header"); } [Fact] public async Task SetBody_WithStringExpression_ResolvesTemplate() { object? captured = null; _context.AddRoutes(r => { r.From("direct://setbody-str") .SetBody(Expr("${header.greeting} ${header.name}")) .Process(e => captured = e.In.Body); }); await _context.Start(); var exchange = new Exchange(new Message { Body = "ignored" }); exchange.In.Headers["greeting"] = "Hello"; exchange.In.Headers["name"] = "World"; var producer = _context.GetEndpoint("direct://setbody-str").CreateProducer(); await producer.Start(); await producer.Process(exchange); captured.Should().Be("Hello World"); } // ─── SetHeader with IExpression ─── [Fact] public async Task SetHeader_WithExpression_SetsHeaderFromBody() { object? capturedHeader = null; _context.AddRoutes(r => { r.From("direct://setheader-expr") .SetHeader("derived", new BodyExpression()) .Process(e => capturedHeader = e.In.Headers["derived"]); }); await _context.Start(); var exchange = new Exchange(new Message { Body = "body-value" }); var producer = _context.GetEndpoint("direct://setheader-expr").CreateProducer(); await producer.Start(); await producer.Process(exchange); capturedHeader.Should().Be("body-value"); } [Fact] public async Task SetHeader_WithStringExpression_ResolvesTemplate() { object? capturedHeader = null; _context.AddRoutes(r => { r.From("direct://setheader-str") .SetHeader("fullName", Expr("${header.first} ${header.last}")) .Process(e => capturedHeader = e.In.Headers["fullName"]); }); await _context.Start(); var exchange = new Exchange(new Message { Body = "ignored" }); exchange.In.Headers["first"] = "John"; exchange.In.Headers["last"] = "Doe"; var producer = _context.GetEndpoint("direct://setheader-str").CreateProducer(); await producer.Start(); await producer.Process(exchange); capturedHeader.Should().Be("John Doe"); } // ─── Transform with IExpression ─── [Fact] public async Task Transform_WithExpression_TransformsBody() { object? captured = null; _context.AddRoutes(r => { r.From("direct://transform-expr") .Transform(new DelegateExpression(e => $"Transformed: {e.In.Body}")) .Process(e => captured = e.In.Body); }); await _context.Start(); var exchange = new Exchange(new Message { Body = "data" }); var producer = _context.GetEndpoint("direct://transform-expr").CreateProducer(); await producer.Start(); await producer.Process(exchange); captured.Should().Be("Transformed: data"); } [Fact] public async Task Transform_WithStringExpression_ResolvesTemplate() { object? captured = null; _context.AddRoutes(r => { r.From("direct://transform-str") .Transform(Expr("${header.prefix}-${body}")) .Process(e => captured = e.In.Body); }); await _context.Start(); var exchange = new Exchange(new Message { Body = "payload" }); exchange.In.Headers["prefix"] = "MSG"; var producer = _context.GetEndpoint("direct://transform-str").CreateProducer(); await producer.Start(); await producer.Process(exchange); captured.Should().Be("MSG-payload"); } // ─── Choice with IPredicate ─── [Fact] public async Task Choice_WithPredicateWhen_RoutesToCorrectBranch() { object? captured = null; _context.AddRoutes(r => { r.From("direct://choice-pred") .Choice() .When(new HeaderExpression("priority").isGreaterThan(5)) .Process(e => captured = "HIGH") .When(new HeaderExpression("priority").isEqualTo(5)) .Process(e => captured = "MEDIUM") .Otherwise() .Process(e => captured = "LOW") .End(); }); await _context.Start(); var producer = _context.GetEndpoint("direct://choice-pred").CreateProducer(); await producer.Start(); // High priority var ex1 = new Exchange(new Message { Body = "order" }); ex1.In.Headers["priority"] = 8; await producer.Process(ex1); captured.Should().Be("HIGH"); // Medium priority var ex2 = new Exchange(new Message { Body = "order" }); ex2.In.Headers["priority"] = 5; await producer.Process(ex2); captured.Should().Be("MEDIUM"); // Low priority var ex3 = new Exchange(new Message { Body = "order" }); ex3.In.Headers["priority"] = 2; await producer.Process(ex3); captured.Should().Be("LOW"); } [Fact] public async Task Choice_WithExpressionWhen_RoutesToCorrectBranch() { object? captured = null; _context.AddRoutes(r => { r.From("direct://choice-expr") .Choice() .When("${header.type}") .Process(e => captured = "TYPED") .Otherwise() .Process(e => captured = "DEFAULT") .End(); }); await _context.Start(); var producer = _context.GetEndpoint("direct://choice-expr").CreateProducer(); await producer.Start(); // type header truthy var ex1 = new Exchange(new Message { Body = "order" }); ex1.In.Headers["type"] = "true"; await producer.Process(ex1); captured.Should().Be("TYPED"); // type header falsy var ex2 = new Exchange(new Message { Body = "unknown" }); ex2.In.Headers["type"] = "false"; await producer.Process(ex2); captured.Should().Be("DEFAULT"); } // ─── Log with ${} templates ─── [Fact] public async Task Log_WithTemplatePlaceholders_ResolvesAndDoesNotThrow() { var processed = false; _context.AddRoutes(r => { r.From("direct://logtemplate") .Log("Processing order ${header.orderId} body: ${body}") .Process(e => processed = true); }); await _context.Start(); var exchange = new Exchange(new Message { Body = "test-body" }); exchange.In.Headers["orderId"] = "ORD-123"; var producer = _context.GetEndpoint("direct://logtemplate").CreateProducer(); await producer.Start(); await producer.Process(exchange); processed.Should().BeTrue(); } [Fact] public async Task Log_WithTemplateAndLogLevel_Compiles() { _context.AddRoutes(r => { r.From("direct://logtemplate-debug") .Log("Debug: ${body}", LogLevel.Debug); }); await _context.Start(); var exchange = new Exchange(new Message { Body = "debug-data" }); var producer = _context.GetEndpoint("direct://logtemplate-debug").CreateProducer(); await producer.Start(); await producer.Process(exchange); // No assertion needed — verifies compilation/execution without exceptions } // ─── Split with IExpression ─── [Fact] public async Task Split_WithExpression_SplitsBody() { var items = new List(); _context.AddRoutes(r => { r.From("direct://split-expr") .Split(new BodyExpression()) .Process(e => { lock (items) { items.Add(e.In.Body); } }) .End(); }); await _context.Start(); var exchange = new Exchange(new Message { Body = new[] { "A", "B", "C" } }); var producer = _context.GetEndpoint("direct://split-expr").CreateProducer(); await producer.Start(); await producer.Process(exchange); items.Should().BeEquivalentTo(new[] { "A", "B", "C" }); } // ─── Combined predicates (And / Or / Not) ─── [Fact] public async Task Filter_WithAndPredicate_RequiresBothConditions() { object? captured = null; // AndPredicate(IExpression, IPredicate): left expr must be truthy AND predicate must match var predicate = new AndPredicate( new HeaderExpression("enabled"), new HeaderExpression("currency").isEqualTo("USD")); _context.AddRoutes(r => { r.From("direct://filter-and") .Filter(predicate) .Process(e => captured = e.In.Body); }); await _context.Start(); var producer = _context.GetEndpoint("direct://filter-and").CreateProducer(); await producer.Start(); // Both match: enabled=true, currency=USD var ex1 = new Exchange(new Message { Body = "pass" }); ex1.In.Headers["enabled"] = true; ex1.In.Headers["currency"] = "USD"; await producer.Process(ex1); captured.Should().Be("pass"); // Expression true but predicate false captured = null; var ex2 = new Exchange(new Message { Body = "fail" }); ex2.In.Headers["enabled"] = true; ex2.In.Headers["currency"] = "EUR"; await producer.Process(ex2); captured.Should().BeNull(); // Expression false but predicate true captured = null; var ex3 = new Exchange(new Message { Body = "fail2" }); ex3.In.Headers["enabled"] = false; ex3.In.Headers["currency"] = "USD"; await producer.Process(ex3); captured.Should().BeNull(); } [Fact] public async Task Filter_WithOrPredicate_RequiresEitherCondition() { object? captured = null; // OrPredicate(IExpression, IPredicate): expr truthy OR predicate matches var predicate = new OrPredicate( new HeaderExpression("vip"), new HeaderExpression("status").isEqualTo("NEW")); _context.AddRoutes(r => { r.From("direct://filter-or") .Filter(predicate) .Process(e => captured = e.In.Body); }); await _context.Start(); var producer = _context.GetEndpoint("direct://filter-or").CreateProducer(); await producer.Start(); // Expression true (vip=true) var ex1 = new Exchange(new Message { Body = "vip-order" }); ex1.In.Headers["vip"] = true; ex1.In.Headers["status"] = "OLD"; await producer.Process(ex1); captured.Should().Be("vip-order"); // Predicate matches (status=NEW) captured = null; var ex2 = new Exchange(new Message { Body = "new-order" }); ex2.In.Headers["vip"] = false; ex2.In.Headers["status"] = "NEW"; await producer.Process(ex2); captured.Should().Be("new-order"); // Neither matches captured = null; var ex3 = new Exchange(new Message { Body = "done" }); ex3.In.Headers["vip"] = false; ex3.In.Headers["status"] = "DONE"; await producer.Process(ex3); captured.Should().BeNull(); } [Fact] public async Task Filter_WithNotPredicate_InvertsPredicate() { object? captured = null; // NotPredicate(IExpression): negates expression's boolean result var predicate = new NotPredicate( new HeaderExpression("skip")); _context.AddRoutes(r => { r.From("direct://filter-not") .Filter(predicate) .Process(e => captured = e.In.Body); }); await _context.Start(); var producer = _context.GetEndpoint("direct://filter-not").CreateProducer(); await producer.Start(); // skip=true → NOT true = false → stop var ex1 = new Exchange(new Message { Body = "skipped" }); ex1.In.Headers["skip"] = true; await producer.Process(ex1); captured.Should().BeNull(); // skip=false → NOT false = true → passes var ex2 = new Exchange(new Message { Body = "kept" }); ex2.In.Headers["skip"] = false; await producer.Process(ex2); captured.Should().Be("kept"); } // ─── Mixed DSL: expression + lambda steps ─── [Fact] public async Task MixedPipeline_ExpressionAndLambda_WorkTogether() { object? captured = null; _context.AddRoutes(r => { r.From("direct://mixed") .RouteId("mixed-pipeline") .SetHeader("processed", new ConstantExpression(true)) .Filter(new IsNotNullPredicate(new HeaderExpression("source"))) .Transform(e => $"[{e.In.Headers["source"]}] {e.In.Body}") .SetHeader("label", Expr("${header.source}-processed")) .Process(e => captured = $"{e.In.Headers["label"]}: {e.In.Body}"); }); await _context.Start(); var exchange = new Exchange(new Message { Body = "data" }); exchange.In.Headers["source"] = "API"; var producer = _context.GetEndpoint("direct://mixed").CreateProducer(); await producer.Start(); await producer.Process(exchange); captured.Should().Be("API-processed: [API] data"); } // ─── Processor unit tests (no engine needed) ─── [Fact] public async Task ExpressionBodyProcessor_SetsBodyFromExpression() { var processor = new ExpressionBodyProcessor(new ConstantExpression(42)); var exchange = new Exchange(new Message { Body = "old" }); await processor.Process(exchange); exchange.In.Body.Should().Be(42); } [Fact] public async Task ExpressionBodyProcessor_ResolvesATemplateExpression() { // 4.0: the separate string-template processor is gone; a ${...} template is an expression. var processor = new ExpressionBodyProcessor(new StringExpression("${header.x}")); var exchange = new Exchange(new Message()); exchange.In.Headers["x"] = "resolved"; await processor.Process(exchange); exchange.In.Body.Should().Be("resolved"); } [Fact] public async Task ExpressionHeaderProcessor_SetsHeaderFromExpression() { var processor = new ExpressionHeaderProcessor("derived", new BodyExpression()); var exchange = new Exchange(new Message { Body = "body-val" }); await processor.Process(exchange); exchange.In.Headers["derived"].Should().Be("body-val"); } [Fact] public async Task ExpressionHeaderProcessor_ResolvesATemplateExpression() { var processor = new ExpressionHeaderProcessor("full", new StringExpression("${header.a}-${header.b}")); var exchange = new Exchange(new Message()); exchange.In.Headers["a"] = "X"; exchange.In.Headers["b"] = "Y"; await processor.Process(exchange); exchange.In.Headers["full"].Should().Be("X-Y"); } [Fact] public async Task TemplateLogProcessor_DoesNotThrow() { var processor = new TemplateLogProcessor("Order ${header.id} body=${body}", LogLevel.Information); var exchange = new Exchange(new Message { Body = "test" }); exchange.In.Headers["id"] = "123"; var act = () => processor.Process(exchange); await act.Should().NotThrowAsync(); } // ─── Expression fluent API on IExpression ─── [Fact] public async Task Expression_isEqualTo_WorksInFilter() { object? captured = null; _context.AddRoutes(r => { r.From("direct://eq-filter") .Filter(new HeaderExpression("type").isEqualTo("ORDER")) .Process(e => captured = e.In.Body); }); await _context.Start(); var producer = _context.GetEndpoint("direct://eq-filter").CreateProducer(); await producer.Start(); var ex1 = new Exchange(new Message { Body = "match" }); ex1.In.Headers["type"] = "ORDER"; await producer.Process(ex1); captured.Should().Be("match"); captured = null; var ex2 = new Exchange(new Message { Body = "no-match" }); ex2.In.Headers["type"] = "PAYMENT"; await producer.Process(ex2); captured.Should().BeNull(); } [Fact] public async Task Expression_contains_WorksInFilter() { object? captured = null; _context.AddRoutes(r => { r.From("direct://contains-filter") .Filter(new BodyExpression().contains("important")) .Process(e => captured = e.In.Body); }); await _context.Start(); var producer = _context.GetEndpoint("direct://contains-filter").CreateProducer(); await producer.Start(); var ex1 = new Exchange(new Message { Body = "this is important data" }); await producer.Process(ex1); captured.Should().Be("this is important data"); captured = null; var ex2 = new Exchange(new Message { Body = "nothing special" }); await producer.Process(ex2); captured.Should().BeNull(); } [Fact] public async Task Expression_isNull_WorksInChoice() { object? captured = null; _context.AddRoutes(r => { r.From("direct://null-choice") .Choice() .When(new HeaderExpression("optional").isNull()) .Process(e => captured = "MISSING") .Otherwise() .Process(e => captured = "PRESENT") .End(); }); await _context.Start(); var producer = _context.GetEndpoint("direct://null-choice").CreateProducer(); await producer.Start(); // Header not set → null → predicate matches var ex1 = new Exchange(new Message { Body = "test" }); await producer.Process(ex1); captured.Should().Be("MISSING"); // Header set → predicate does not match var ex2 = new Exchange(new Message { Body = "test" }); ex2.In.Headers["optional"] = "value"; await producer.Process(ex2); captured.Should().Be("PRESENT"); } [Fact] public async Task RouteDefinition_RecordsExpressionSteps() { var def = new RouteDefinition(); def.From("direct://test") .SetBody(new ConstantExpression(42)) .SetBody(Expr("${body}")) .SetHeader("h", new BodyExpression()) .SetHeader("h2", Expr("${header.h}")) .Transform(new DelegateExpression(e => "x")) .Transform(Expr("${body}")) .Filter(new IsNotNullPredicate(new BodyExpression())).EndFilter() .Filter("${header.flag}").EndFilter() .Split(new BodyExpression()).End() .Log("Test ${body}") .Choice() .When(new BodyExpression().isEqualTo("x")) .SetBody("matched") .When("${header.cond}") .SetBody("expr-matched") .End(); // Verify outputs (live IProcessorDefinition tree) — the live scope graph after CRTP refactor. def.Outputs.Should().HaveCountGreaterThan(10); def.Outputs.OfType().Should().NotBeEmpty(); def.Outputs.OfType().Should().NotBeEmpty(); def.Outputs.OfType().Should().NotBeEmpty(); def.Outputs.OfType().Should().HaveCountGreaterThanOrEqualTo(2); def.Outputs.OfType().Should().HaveCount(1); def.Outputs.OfType().Should().HaveCount(1); var choice = def.Outputs.OfType().Single(); choice.Whens.Should().HaveCount(2); } } Path: redb-route/tests/redb.Route.Tests/Expressions/ExpressionDslPhase1Tests.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/Expressions/ExpressionDslPhase1Tests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using static redb.Route.Core.RouteBuilder; using redb.Route.Expressions; using redb.Route.Definitions; namespace redb.Route.Tests.Expressions; /// /// Tests for the expression DSL: string forms of Loop / Delay / Throttle and the Expr(...) forms of /// SetProperty / SetBody / SetHeader / Transform. /// public class ExpressionDslPhase1Tests : IAsyncLifetime { private readonly RouteContext _context = new(); public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { await _context.DisposeAsync(); GC.SuppressFinalize(this); } // ─── SetProperty(Expr(...)) ─── [Fact] public async Task SetPropertyExpr_ResolvesFromHeader() { object? captured = null; _context.AddRoutes(r => { r.From("direct://set-prop-expr") .SetProperty("greeting", Expr("${header.name}")) .Process(e => captured = e.Properties["greeting"]); }); await _context.Start(); var exchange = new Exchange(new Message { Body = "test" }); exchange.In.Headers["name"] = "Alice"; var producer = _context.GetEndpoint("direct://set-prop-expr").CreateProducer(); await producer.Start(); await producer.Process(exchange); captured.Should().Be("Alice"); } [Fact] public async Task SetPropertyExpr_ResolvesTemplate() { object? captured = null; _context.AddRoutes(r => { r.From("direct://set-prop-tmpl") .SetProperty("msg", Expr("Hello ${header.name}!")) .Process(e => captured = e.Properties["msg"]); }); await _context.Start(); var exchange = new Exchange(new Message { Body = "test" }); exchange.In.Headers["name"] = "Bob"; var producer = _context.GetEndpoint("direct://set-prop-tmpl").CreateProducer(); await producer.Start(); await producer.Process(exchange); captured.Should().Be("Hello Bob!"); } // ─── LoopExpression ─── [Fact] public async Task LoopExpression_CountFromHeader() { int counter = 0; _context.AddRoutes(r => { r.From("direct://loop-expr") .LoopExpression(new StringExpression("${header.count}"), sub => { sub.Process(_ => Interlocked.Increment(ref counter)); }); }); await _context.Start(); var exchange = new Exchange(new Message { Body = "test" }); exchange.In.Headers["count"] = 5; var producer = _context.GetEndpoint("direct://loop-expr").CreateProducer(); await producer.Start(); await producer.Process(exchange); counter.Should().Be(5); } [Fact] public async Task LoopExpression_CountFromStringHeader() { int counter = 0; _context.AddRoutes(r => { r.From("direct://loop-expr-str") .LoopExpression(new StringExpression("${header.count}"), sub => { sub.Process(_ => Interlocked.Increment(ref counter)); }); }); await _context.Start(); var exchange = new Exchange(new Message { Body = "test" }); exchange.In.Headers["count"] = "3"; var producer = _context.GetEndpoint("direct://loop-expr-str").CreateProducer(); await producer.Start(); await producer.Process(exchange); counter.Should().Be(3); } [Fact] public async Task LoopExpression_WithCopy_BodyPreserved() { string? lastBody = null; _context.AddRoutes(r => { r.From("direct://loop-expr-copy") .LoopExpression(new StringExpression("${header.count}"), sub => { sub.Process(e => { lastBody = e.In.Body?.ToString(); e.In.Body = "modified"; }); }, copy: true); }); await _context.Start(); var exchange = new Exchange(new Message { Body = "original" }); exchange.In.Headers["count"] = 3; var producer = _context.GetEndpoint("direct://loop-expr-copy").CreateProducer(); await producer.Start(); await producer.Process(exchange); // With copy, each iteration starts from the original lastBody.Should().Be("original"); } // ─── DelayExpression ─── [Fact] public async Task DelayExpression_DelaysFromHeader() { object? captured = null; _context.AddRoutes(r => { r.From("direct://delay-expr") .Delay("${header.delayMs}") .Process(e => captured = e.In.Body); }); await _context.Start(); var exchange = new Exchange(new Message { Body = "delayed" }); exchange.In.Headers["delayMs"] = 50; var producer = _context.GetEndpoint("direct://delay-expr").CreateProducer(); await producer.Start(); var sw = System.Diagnostics.Stopwatch.StartNew(); await producer.Process(exchange); sw.Stop(); captured.Should().Be("delayed"); sw.ElapsedMilliseconds.Should().BeGreaterThanOrEqualTo(30); // ~50ms with some tolerance } // ─── ThrottleExpression ─── [Fact] public async Task ThrottleExpression_ResolvesFromHeader() { int count = 0; _context.AddRoutes(r => { r.From("direct://throttle-expr") .Throttle("${header.rate}", TimeSpan.FromSeconds(1)) .Process(_ => Interlocked.Increment(ref count)); }); await _context.Start(); var producer = _context.GetEndpoint("direct://throttle-expr").CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message { Body = "test" }); exchange.In.Headers["rate"] = 100; await producer.Process(exchange); count.Should().Be(1); } // ─── SetBody(Expr(...)) ─── [Fact] public async Task SetBodyExpr_ResolvesTemplate() { object? captured = null; _context.AddRoutes(r => { r.From("direct://setbody-expr") .SetBody(Expr("${header.greeting} ${header.name}")) .Process(e => captured = e.In.Body); }); await _context.Start(); var exchange = new Exchange(new Message { Body = "original" }); exchange.In.Headers["greeting"] = "Hello"; exchange.In.Headers["name"] = "World"; var producer = _context.GetEndpoint("direct://setbody-expr").CreateProducer(); await producer.Start(); await producer.Process(exchange); captured.Should().Be("Hello World"); } // ─── Transform(Expr(...)) ─── [Fact] public async Task TransformExpr_ResolvesTemplate() { object? captured = null; _context.AddRoutes(r => { r.From("direct://transform-expr") .Transform(Expr("Processed: ${body}")) .Process(e => captured = e.In.Body); }); await _context.Start(); var exchange = new Exchange(new Message { Body = "data" }); var producer = _context.GetEndpoint("direct://transform-expr").CreateProducer(); await producer.Start(); await producer.Process(exchange); captured.Should().Be("Processed: data"); } // ─── SetHeader(Expr(...)) ─── [Fact] public async Task SetHeaderExpr_ResolvesFromBody() { object? captured = null; _context.AddRoutes(r => { r.From("direct://sethdr-expr") .SetHeader("bodyRef", Expr("${body}")) .Process(e => captured = e.In.Headers["bodyRef"]); }); await _context.Start(); var exchange = new Exchange(new Message { Body = "my-data" }); var producer = _context.GetEndpoint("direct://sethdr-expr").CreateProducer(); await producer.Start(); await producer.Process(exchange); captured.Should().Be("my-data"); } } Path: redb-route/tests/redb.Route.Tests/Expressions/ExpressionLanguageSnapshot.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/Expressions/ExpressionLanguageSnapshot.cs ---- namespace redb.Route.Tests.Expressions; /// /// The recorded behaviour of the expression language, one line per form of /// , four columns for the four positions a string can occupy. /// /// This is a characterisation record, not a wish list: it says what the language does today, /// including where it is wrong. Its job is to make any change to expression handling visible as a /// diff. A line that moves must be explained before this file is updated — that is the whole /// point of keeping it. /// /// /// To regenerate: run ExpressionLanguageSnapshotTests, read the reported differences, and /// when they are all intended copy in the fresh snapshot the failure message points to. /// /// internal static class ExpressionLanguageSnapshot { internal const string Expected = """ # Characterisation of the redb.Route expression language. # # One line per form of the corpus, four columns, one per position: # value — StringExpression(form), what SetBody / SetHeader / a connector option does # condition — PredicateFactory.FromString(form), what Filter / When / LoopWhile / Validate does # template — StringExpression("${form}"), the interpolated form # # This file records what the language does TODAY, right or wrong. A diff here means # behaviour moved; every moved line has to be explained before the snapshot is updated. ## literals 42 | value=42:Int32 | condition=true | template=42:Int32 -7 | value=-7:Double | condition=true | template=-7:Double 2.5 | value=2.5:Double | condition=true | template=2.5:Double true | value=true | condition=true | template=true false | value=false | condition=false | template=false 'hello' | value="hello" | condition=true | template="hello" "hello" | value="hello" | condition=true | template="hello" 'a > b' | value="a > b" | condition=true | template="a > b" 'x AND y' | value="x AND y" | condition=true | template="x AND y" hello | value="hello" | condition=true | template=null plain text | value="plain text" | condition=true | template=!ExpressionCompilationException ## config-shaped literals a>b | value=false | condition=false | template=false x | value=!ExpressionCompilationException | condition=!ExpressionCompilationException | template=!ExpressionCompilationException | value=!ExpressionCompilationException | condition=!ExpressionCompilationException | template=!ExpressionCompilationException key=value | value="key=value" | condition=true | template=!ExpressionCompilationException application/json | value=!BrokenExpressionException | condition=!BrokenExpressionException | template=null text/plain; charset=utf-8 | value=!BrokenExpressionException | condition=!BrokenExpressionException | template=!ExpressionCompilationException some/path/file.txt | value=!BrokenExpressionException | condition=!BrokenExpressionException | template=null https://example.com/a?b=c | value=!ExpressionCompilationException | condition=!ExpressionCompilationException | template=!ExpressionCompilationException 2026-08-28 | value=1990:Int32 | condition=true | template=1990:Int32 black and white | value=false | condition=false | template=false yes or no | value=false | condition=false | template=false BLACK AND WHITE | value=false | condition=false | template=false ## accessors header.a | value=42:Int32 | condition=true | template=42:Int32 header.zero | value=0:Int32 | condition=false | template=0:Int32 header.neg | value=-7:Int32 | condition=true | template=-7:Int32 header.flag | value=true | condition=true | template=true header.off | value=false | condition=false | template=false header.s | value="hello" | condition=true | template="hello" header.empty | value="" | condition=false | template="" header.missing | value=null | condition=false | template=null header.dotted.key | value="literal-dot" | condition=true | template="literal-dot" header.Content-Type | value=!BrokenExpressionException | condition=!BrokenExpressionException | template="text/xml" header.X-Request-Id | value=!BrokenExpressionException | condition=!BrokenExpressionException | template="req-1" header.a+b | value=!BrokenExpressionException | condition=!BrokenExpressionException | template="plus-name" property.count | value=7:Int32 | condition=true | template=7:Int32 property.zero | value=0:Int32 | condition=false | template=0:Int32 property.flag | value=false | condition=false | template=false property.missing | value=null | condition=false | template=null body @Text | value="payload" | condition=true | template="payload" body | value= | condition=true | template= exception.Message | value="boom" | condition=true | template="boom" contentType | value=null | condition=false | template=null ## member access header.user.Name | value="ann" | condition=true | template="ann" header.user.Age | value=30:Int32 | condition=true | template=30:Int32 header.user.Active | value=true | condition=true | template=true header.user.Manager | value=null | condition=false | template=null header.list.Count | value=5:Int32 | condition=true | template=5:Int32 header.s.Length | value=5:Int32 | condition=true | template=5:Int32 property.user.Name | value="ann" | condition=true | template="ann" property.cfg.enabled | value=true | condition=true | template=true property.cfg.limit | value=5:Int32 | condition=true | template=5:Int32 property.items.Count | value=3:Int32 | condition=true | template=3:Int32 body.Name | value="ann" | condition=true | template="ann" body.Age | value=30:Int32 | condition=true | template=30:Int32 body.Manager.Name | value="bob" | condition=true | template="bob" header.user.Level | value=3:Int32 | condition=true | template=3:Int32 property.user.Level | value=3:Int32 | condition=true | template=3:Int32 body.Level | value=3:Int32 | condition=true | template=3:Int32 body.Manager.Level | value=3:Int32 | condition=true | template=3:Int32 ## comparison spaced header.a > 10 | value=true | condition=true | template=true header.a < 10 | value=false | condition=false | template=false header.a >= 42 | value=true | condition=true | template=true header.a <= 42 | value=true | condition=true | template=true header.a == 42 | value=true | condition=true | template=true header.a != 42 | value=false | condition=false | template=false header.s == 'hello' | value=true | condition=true | template=true header.s != 'hello' | value=false | condition=false | template=false header.missing == null | value=true | condition=true | template=true header.a != null | value=true | condition=true | template=true 1 > 0 | value=true | condition=true | template=true ## comparison whitespace header.a>10 | value=true | condition=true | template=true header.a>=42 | value=true | condition=true | template=true header.a<=42 | value=true | condition=true | template=true header.a==42 | value=true | condition=true | template=true header.a!=42 | value=false | condition=false | template=false header.a > 10 | value=true | condition=true | template=true header.a\t>\t10 | value=true | condition=true | template=true header.a\n>\n10 | value=true | condition=true | template=true header.a>10 | value=true | condition=true | template=true header.a >10 | value=true | condition=true | template=true header.a> 10 | value=true | condition=true | template=true 1>0 | value=true | condition=true | template=true ## comparison member header.user.Age > 18 | value=true | condition=true | template=true header.user.Age>18 | value=true | condition=true | template=true header.list.Count > 3 | value=true | condition=true | template=true property.cfg.limit > 3 | value=true | condition=true | template=true property.cfg.limit>3 | value=true | condition=true | template=true property.items.Count > 2 | value=true | condition=true | template=true header.s.Length > 3 | value=true | condition=true | template=true body.Age > 18 | value=true | condition=true | template=true body.Age>18 | value=true | condition=true | template=true ## quoted operators header.quoted == 'a > b' | value=true | condition=true | template=true header.quoted=='a > b' | value=true | condition=true | template=true header.quoted == 'a < b' | value=false | condition=false | template=false header.worded == 'x AND y' | value=true | condition=true | template=true header.worded == 'x OR y' | value=false | condition=false | template=false header.ct == 'application/json' | value=true | condition=true | template=true header.ct=='application/json' | value=true | condition=true | template=true ## word logic header.a > 10 AND header.b < 5 | value=true | condition=true | template=true header.a>10 AND header.b<5 | value=true | condition=true | template=true header.a>10 AND header.b<5 | value=true | condition=true | template=true header.a>10\tAND\theader.b<5 | value=true | condition=true | template=true header.a>10 and header.b<5 | value=true | condition=true | template=true header.a > 10 OR header.b > 100 | value=true | condition=true | template=true header.a > 10 XOR header.b > 100 | value=true | condition=true | template=true property.count > 5 OR property.flag | value=true | condition=true | template=true NOT header.flag | value=false | condition=false | template=false !header.flag | value=false | condition=false | template=false header.a > 10 AND NOT header.off | value=true | condition=true | template=true header.a > 10 AND !header.off | value=true | condition=true | template=true header.a AND header.b | value=true | condition=true | template=true ## parentheses (header.a > 10) | value=true | condition=true | template=true (header.a > 10) AND (header.b < 5) | value=true | condition=true | template=true (header.a>10) AND (header.b<5) | value=true | condition=true | template=true (header.a > 10 AND header.b < 5) | value=true | condition=true | template=true (header.a > 100) OR (header.b < 5) | value=true | condition=true | template=true ((header.a > 10)) | value=true | condition=true | template=true (header.a + header.b) * 2 | value=90:Int32 | condition=true | template=90:Int32 ## arithmetic header.a + header.b | value=45:Int32 | condition=true | template=45:Int32 header.a+header.b | value=45:Int32 | condition=true | template=45:Int32 header.a - 2 | value=40:Int32 | condition=true | template=40:Int32 header.a-2 | value=40:Int32 | condition=true | template=40:Int32 header.a * 2 | value=84:Int32 | condition=true | template=84:Int32 header.a*2 | value=84:Int32 | condition=true | template=84:Int32 header.a / 2 | value=21:Int32 | condition=true | template=21:Int32 header.a/2 | value=21:Int32 | condition=true | template=21:Int32 header.a + header.b * 2 | value=48:Int32 | condition=true | template=48:Int32 header.dbl * 2 | value=5:Int32 | condition=true | template=5:Int32 -header.a | value=-42:Double | condition=true | template=-42:Double header.a + header.b > 40 | value=true | condition=true | template=true header.a+header.b>40 | value=true | condition=true | template=true header.a % 5 | value=2:Int32 | condition=true | template=2:Int32 header.a%5 | value=2:Int32 | condition=true | template=2:Int32 header.neg % 3 | value=-1:Int32 | condition=true | template=-1:Int32 header.dbl % 2 | value=0.5:Double | condition=true | template=0.5:Double header.a % header.zero | value=null | condition=false | template=null header.a % 2 == 0 | value=true | condition=true | template=true header.a%2==0 | value=true | condition=true | template=true ## functions count(property.items) | value=3:Int32 | condition=true | template=3:Int32 count(property.items) > 2 | value=true | condition=true | template=true count(property.items)>2 | value=true | condition=true | template=true length(property.name) | value=4:Int32 | condition=true | template=4:Int32 length(property.name) > 3 | value=true | condition=true | template=true contains(header.s, 'ell') | value=true | condition=true | template=true upper(header.s) | value="HELLO" | condition=true | template="HELLO" lower(header.s) | value="hello" | condition=true | template="hello" logical(header.a > 10) | value=true | condition=true | template=true logical(header.a>10) | value=true | condition=true | template=true logical(header.a > 100) | value=false | condition=false | template=false logical((header.a > 10) AND (header.b < 5)) | value=true | condition=true | template=true logical(header.a + header.b > 40) | value=true | condition=true | template=true logical(header.worded == 'x AND y') | value=true | condition=true | template=true jpath($.order.id) @Json | value=!ExpressionCompilationException | condition=!ExpressionCompilationException | template=7:Int64 xpath(/order/id) @Xml | value=!ExpressionCompilationException | condition=!ExpressionCompilationException | template=7:Int32 datediff('2026-01-03', '2026-01-01', 'days') | value=2:Int32 | condition=true | template=2:Int32 datediff('2026-01-01', '2026-01-03', 'hours') | value=-48:Int32 | condition=true | template=-48:Int32 datediff('2026-01-01T06:00:00', '2026-01-01T00:00:00', 'days') | value=0.25:Double | condition=true | template=0.25:Double datediff('2026-01-02', '2026-01-01', 'fortnights') | value=null | condition=false | template=null ## increments header.a++ | value=42:Int32 | condition=true | template=42:Int32 ++header.a | value=43:Int32 | condition=true | template=43:Int32 header.a-- | value=42:Int32 | condition=true | template=42:Int32 --header.a | value=41:Int32 | condition=true | template=41:Int32 property.count++ | value=7:Int32 | condition=true | template=7:Int32 ++property.count | value=8:Int32 | condition=true | template=8:Int32 ## min max min(header.a, header.b) | value=3:Double | condition=true | template=3:Double max(header.a, header.b) | value=42:Double | condition=true | template=42:Double min(header.list) | value=1:Double | condition=true | template=1:Double max(header.list) | value=5:Double | condition=true | template=5:Double min(property.items) | value=null | condition=false | template=null max(property.missing) | value=null | condition=false | template=null ## decimal literals max(2.5, 1) | value=2.5:Double | condition=true | template=2.5:Double round(2.567, 2) | value=2.57:Double | condition=true | template=2.57:Double abs(-2.5) | value=2.5:Double | condition=true | template=2.5:Double 2.5 + 1 | value=3.5:Double | condition=true | template=3.5:Double ## ternary header.a > 10 ? 'big' : 'small' | value="big" | condition=true | template="big" header.a>10 ? 'big' : 'small' | value="big" | condition=true | template="big" header.a > 100 ? 'big' : 'small' | value="small" | condition=true | template="small" length(property.name) > 3 ? true : false | value=true | condition=true | template=true header.missing ?? 5 | value=5:Int32 | condition=true | template=5:Int32 header.a ?? 5 | value=42:Int32 | condition=true | template=42:Int32 header.missing ?? 'dflt' | value="dflt" | condition=true | template="dflt" ## index access property.items[0] | value="p" | condition=true | template="p" header.list[1] | value=2:Int32 | condition=true | template=2:Int32 property.items[0] == 'p' | value=true | condition=true | template=true ## whole-string placeholder ${header.flag} | value=true | condition=true | template=- ${header.off} | value=false | condition=false | template=- ${header.zero} | value=0:Int32 | condition=false | template=- ${header.empty} | value="" | condition=false | template=- ${header.missing} | value=null | condition=false | template=- ${header.a > 10} | value=true | condition=true | template=- ${header.a > 100} | value=false | condition=false | template=- ${header.a>100} | value=false | condition=false | template=- ${header.s == 'hello'} | value=true | condition=true | template=- ${header.s == 'nope'} | value=false | condition=false | template=- ${header.a > 10 AND header.b < 5} | value=true | condition=true | template=- ## camel idioms ${header.a} > 10 | value="42 > 10" | condition=true | template=- ${header.a} > 100 | value="42 > 100" | condition=true | template=- ${header.a} == 42 | value="42 == 42" | condition=true | template=- ${header.s} == 'hello' | value="hello == 'hello'" | condition=true | template=- ${header.s} == 'nope' | value="hello == 'nope'" | condition=true | template=- ${header.a} > 10 && ${header.b} < 5 | value="42 > 10 && 3 < 5" | condition=true | template=- ${header[Content-Type]} | value=null | condition=false | template=- ${headers.Content-Type} | value=null | condition=false | template=- ${headers[Content-Type]} | value=null | condition=false | template=- ${exchangeProperty.count} | value=null | condition=false | template=- ${property.count} | value=7:Int32 | condition=true | template=- ${body} @Text | value="payload" | condition=true | template=- ## truthiness 0 | value=0:Int32 | condition=false | template=0:Int32 1 | value=1:Int32 | condition=true | template=1:Int32 '0' | value="0" | condition=false | template="0" '1' | value="1" | condition=true | template="1" 'no' | value="no" | condition=false | template="no" 'yes' | value="yes" | condition=true | template="yes" 'off' | value="off" | condition=false | template="off" 'oui' | value="oui" | condition=true | template="oui" 'nein' | value="nein" | condition=true | template="nein" 'anything else' | value="anything else" | condition=true | template="anything else" header.dbl | value=2.5:Double | condition=true | template=2.5:Double header.zero AND header.a | value=false | condition=false | template=false header.zero OR header.a | value=true | condition=true | template=true logical(header.zero) | value=false | condition=false | template=false logical(header.a) | value=true | condition=true | template=true NOT header.zero | value=true | condition=true | template=true ## malformed header.a > | value=!ExpressionCompilationException | condition=!ExpressionCompilationException | template=!ExpressionCompilationException > 10 | value=!ExpressionCompilationException | condition=!ExpressionCompilationException | template=!ExpressionCompilationException (((( | value="((((" | condition=true | template=!ExpressionCompilationException 1 + | value=!BrokenExpressionException | condition=!BrokenExpressionException | template=!ExpressionCompilationException ~~~INVALID~~~ | value="~~~INVALID~~~" | condition=true | template=!ExpressionCompilationException header. | value=null | condition=false | template=null count( | value=!ExpressionCompilationException | condition=!ExpressionCompilationException | template=!ExpressionCompilationException 'unterminated | value="'unterminated" | condition=true | template=!ExpressionCompilationException """; } Path: redb-route/tests/redb.Route.Tests/Expressions/ExpressionLanguageSnapshotTests.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/Expressions/ExpressionLanguageSnapshotTests.cs ---- using System.Globalization; using System.Text; using AwesomeAssertions; using redb.Route.Expressions; namespace redb.Route.Tests.Expressions; /// /// The characterisation net over the expression language. Every form of /// is evaluated in all four positions and compared against /// . /// /// A failure here does not mean the code is wrong; it means behaviour moved. Read the reported /// lines, decide whether the move is the intended one, and only then update the snapshot. That /// discipline is what makes a change to the expression system safe to attempt at all: without it /// a fix in one position silently rearranges the other three. /// /// [Collection("ExpressionResolver")] public class ExpressionLanguageSnapshotTests { [Fact] public void TheLanguageBehavesExactlyAsRecorded() { var actual = Normalise(ExpressionPositions.RenderSnapshot()); var expected = Normalise(ExpressionLanguageSnapshot.Expected); if (actual == expected) return; // Written out so regenerating the snapshot is a copy, not a retyping exercise. var fresh = Path.Combine(Path.GetTempPath(), "expression-language.snapshot.txt"); File.WriteAllText(fresh, actual); Assert.Fail($"{BuildReport(expected, actual)}{Environment.NewLine}Fresh snapshot written to {fresh}."); } /// /// The corpus has to keep covering every position; an entry that silently stops being /// evaluated would leave a hole the snapshot cannot show. /// [Fact] public void EveryFormIsRecordedInEveryPosition() { var lines = Normalise(ExpressionLanguageSnapshot.Expected) .Split('\n') .Where(line => line.Contains(" | value=", StringComparison.Ordinal)) .ToList(); lines.Should().HaveCount(ExpressionCorpus.Entries.Count); lines.Should().OnlyContain(line => line.Contains(" | value=", StringComparison.Ordinal) && line.Contains(" | condition=", StringComparison.Ordinal) && line.Contains(" | template=", StringComparison.Ordinal)); } /// /// Template interpolation formats numbers with the ambient culture, so the same route emits /// 2.5 or 2,5 depending on where it runs. Recorded here rather than hidden: /// the snapshot itself is generated under the invariant culture so it stays portable, which /// would otherwise make this dependency invisible. /// [Fact] public void TemplateNumberFormatting_IsInvariant_OnEveryMachine() { // V4 (phase 09): a ${...} template renders numbers and dates culture-invariant; before, ru-RU gave "2,5". var exchange = ExpressionCorpus.CreateExchange(ExpressionCorpus.Fixture.Object); exchange.In.Headers["price"] = 2.5; exchange.In.Headers["when"] = new DateTime(2026, 9, 1, 10, 30, 0, DateTimeKind.Utc); Render("en-US").Should().Be("2.5"); Render("ru-RU").Should().Be("2,5".Replace(',', '.')); new StringExpression("${header.when}").Evaluate(exchange).Should().Be("2026-09-01T10:30:00.0000000Z"); string Render(string culture) { var previous = CultureInfo.CurrentCulture; CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo(culture); try { return new StringExpression("${header.price}").Evaluate(exchange); } finally { CultureInfo.CurrentCulture = previous; } } } /// /// Source text is culture-invariant: a decimal literal inside a function argument must parse /// on every machine. Until 2026-08-29 the parser used the ambient culture, so /// max(2.5, 1) compiled on en-US and threw on ru-RU. /// [Theory] [InlineData("en-US")] [InlineData("ru-RU")] [InlineData("de-DE")] public void DecimalLiterals_ParseUnderAnyCulture(string culture) { var previous = CultureInfo.CurrentCulture; CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo(culture); try { var exchange = ExpressionCorpus.CreateExchange(ExpressionCorpus.Fixture.Object); new StringExpression("max(2.5, 1)").Evaluate(exchange).Should().Be(2.5); new StringExpression("round(2.567, 2)").Evaluate(exchange).Should().Be(2.57); new StringExpression("2.5 + 1").Evaluate(exchange).Should().Be(3.5); } finally { CultureInfo.CurrentCulture = previous; } } private static string Normalise(string text) => text.Replace("\r\n", "\n").TrimEnd('\n'); /// /// Compares by the form each line describes rather than by line number, so adding a form to the /// corpus does not cascade into every line below it and drown the real difference. /// private static string BuildReport(string expected, string actual) { var before = IndexByForm(expected); var after = IndexByForm(actual); var report = new StringBuilder(); report.AppendLine("The expression language no longer behaves as recorded."); report.AppendLine("Each entry below is a form whose outcome moved. Decide whether the move is intended,"); report.AppendLine("note it in the changelog, then regenerate ExpressionLanguageSnapshot.Expected."); report.AppendLine(); var moved = 0; foreach (var form in before.Keys.Concat(after.Keys).Distinct()) { var was = before.GetValueOrDefault(form, "
"); var now = after.GetValueOrDefault(form, ""); if (was == now) continue; moved++; if (moved > 40) { report.AppendLine("... further differences omitted."); break; } report.AppendLine($" form: {form}"); report.AppendLine($" was: {was}"); report.AppendLine($" now: {now}"); report.AppendLine(); } if (moved == 0) report.AppendLine("No form changed; only the layout of the snapshot differs."); else report.AppendLine($"{moved} form(s) moved out of {before.Count} recorded."); return report.ToString(); } private static Dictionary IndexByForm(string snapshot) { var index = new Dictionary(StringComparer.Ordinal); foreach (var line in snapshot.Split('\n')) { var separator = line.IndexOf(" | value=", StringComparison.Ordinal); if (separator < 0) continue; index[line[..separator]] = line[(separator + 3)..]; } return index; } } Path: redb-route/tests/redb.Route.Tests/Expressions/ExpressionPerformanceBenchmarkTests.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/Expressions/ExpressionPerformanceBenchmarkTests.cs ---- using System.Diagnostics; using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Expressions; namespace redb.Route.Tests.Expressions; /// /// Performance benchmarks for the expression compilation and evaluation engine. /// Measures cache hit throughput, AST compilation, and template processing performance. /// The thresholds are absolute operations per second, so a slow or shared machine fails them without any defect: /// Category=Performance lets such a run leave them out. /// [Trait("Category", "Performance")] [Collection("ExpressionResolver")] public class ExpressionPerformanceBenchmarkTests : IDisposable { private const int WarmupIterations = 100; private const int BenchmarkIterations = 10_000; public ExpressionPerformanceBenchmarkTests() { ExpressionResolver.ClearAllCaches(); } public void Dispose() { ExpressionResolver.ClearAllCaches(); } private static IExchange CreateExchange() { var exchange = new Exchange(new Message("test body")); exchange.In.Headers["name"] = "Alice"; exchange.In.Headers["count"] = "42"; exchange.Properties["x"] = 10; exchange.Properties["y"] = 20; exchange.Properties["flag"] = true; exchange.Properties["items"] = new List { "alpha", "beta", "gamma" }; exchange.Properties["label"] = "test"; return exchange; } [Fact] public void Benchmark_SimpleTemplateProcessing() { var exchange = CreateExchange(); // Warmup for (int i = 0; i < WarmupIterations; i++) ExpressionResolver.ProcessTemplate("Hello ${header.name}!", exchange); var sw = Stopwatch.StartNew(); for (int i = 0; i < BenchmarkIterations; i++) ExpressionResolver.ProcessTemplate("Hello ${header.name}!", exchange); sw.Stop(); var opsPerSecond = BenchmarkIterations / sw.Elapsed.TotalSeconds; opsPerSecond.Should().BeGreaterThan(20_000, $"Simple template processing should be fast (was {opsPerSecond:N0} ops/s in {sw.ElapsedMilliseconds}ms)"); } [Fact] public void Benchmark_ArithmeticExpression() { var exchange = CreateExchange(); for (int i = 0; i < WarmupIterations; i++) ExpressionResolver.ResolveExpression("x + y", exchange); var sw = Stopwatch.StartNew(); for (int i = 0; i < BenchmarkIterations; i++) ExpressionResolver.ResolveExpression("x + y", exchange); sw.Stop(); var opsPerSecond = BenchmarkIterations / sw.Elapsed.TotalSeconds; opsPerSecond.Should().BeGreaterThan(10_000, $"Arithmetic expression should be fast (was {opsPerSecond:N0} ops/s in {sw.ElapsedMilliseconds}ms)"); } [Fact] public void Benchmark_NullCoalescing() { var exchange = CreateExchange(); for (int i = 0; i < WarmupIterations; i++) ExpressionResolver.ResolveExpression("label ?? 'default'", exchange); var sw = Stopwatch.StartNew(); for (int i = 0; i < BenchmarkIterations; i++) ExpressionResolver.ResolveExpression("label ?? 'default'", exchange); sw.Stop(); var opsPerSecond = BenchmarkIterations / sw.Elapsed.TotalSeconds; opsPerSecond.Should().BeGreaterThan(10_000, $"Null-coalescing should be fast (was {opsPerSecond:N0} ops/s in {sw.ElapsedMilliseconds}ms)"); } [Fact] public void Benchmark_TernaryExpression() { var exchange = CreateExchange(); for (int i = 0; i < WarmupIterations; i++) ExpressionResolver.ResolveExpression("flag ? 'yes' : 'no'", exchange); var sw = Stopwatch.StartNew(); for (int i = 0; i < BenchmarkIterations; i++) ExpressionResolver.ResolveExpression("flag ? 'yes' : 'no'", exchange); sw.Stop(); var opsPerSecond = BenchmarkIterations / sw.Elapsed.TotalSeconds; opsPerSecond.Should().BeGreaterThan(10_000, $"Ternary expression should be fast (was {opsPerSecond:N0} ops/s in {sw.ElapsedMilliseconds}ms)"); } [Fact] public void Benchmark_ConcatFunction() { var exchange = CreateExchange(); for (int i = 0; i < WarmupIterations; i++) ExpressionResolver.ResolveExpression("concat(label, ' ', label)", exchange); var sw = Stopwatch.StartNew(); for (int i = 0; i < BenchmarkIterations; i++) ExpressionResolver.ResolveExpression("concat(label, ' ', label)", exchange); sw.Stop(); var opsPerSecond = BenchmarkIterations / sw.Elapsed.TotalSeconds; opsPerSecond.Should().BeGreaterThan(10_000, $"concat() should be fast (was {opsPerSecond:N0} ops/s in {sw.ElapsedMilliseconds}ms)"); } [Fact] public void Benchmark_IndexAccess() { var exchange = CreateExchange(); for (int i = 0; i < WarmupIterations; i++) ExpressionResolver.ResolveExpression("items[0]", exchange); var sw = Stopwatch.StartNew(); for (int i = 0; i < BenchmarkIterations; i++) ExpressionResolver.ResolveExpression("items[0]", exchange); sw.Stop(); var opsPerSecond = BenchmarkIterations / sw.Elapsed.TotalSeconds; opsPerSecond.Should().BeGreaterThan(10_000, $"Index access should be fast (was {opsPerSecond:N0} ops/s in {sw.ElapsedMilliseconds}ms)"); } [Fact] public void Benchmark_ComplexTemplate() { var exchange = CreateExchange(); var template = "Name: ${header.name}, Sum: ${x + y}, First: ${items[0]}"; for (int i = 0; i < WarmupIterations; i++) ExpressionResolver.ProcessTemplate(template, exchange); var sw = Stopwatch.StartNew(); for (int i = 0; i < BenchmarkIterations; i++) ExpressionResolver.ProcessTemplate(template, exchange); sw.Stop(); var opsPerSecond = BenchmarkIterations / sw.Elapsed.TotalSeconds; opsPerSecond.Should().BeGreaterThan(2_000, $"Complex template should be reasonable (was {opsPerSecond:N0} ops/s in {sw.ElapsedMilliseconds}ms)"); } [Fact] public void Benchmark_CacheHitRate() { var exchange = CreateExchange(); var expressions = new[] { "x + y", "label ?? 'def'", "flag ? 'a' : 'b'", "items[0]", "concat('a', 'b')" }; // Warmup — populate cache foreach (var expr in expressions) ExpressionResolver.ResolveExpression(expr, exchange); // Measure cached access var sw = Stopwatch.StartNew(); for (int i = 0; i < BenchmarkIterations; i++) { var expr = expressions[i % expressions.Length]; ExpressionResolver.ResolveExpression(expr, exchange); } sw.Stop(); var opsPerSecond = BenchmarkIterations / sw.Elapsed.TotalSeconds; opsPerSecond.Should().BeGreaterThan(10_000, $"Mixed cached access should be fast (was {opsPerSecond:N0} ops/s in {sw.ElapsedMilliseconds}ms)"); } } Path: redb-route/tests/redb.Route.Tests/Expressions/ExpressionPhase2Tests.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/Expressions/ExpressionPhase2Tests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Expressions; using redb.Route.Expressions.Ast; namespace redb.Route.Tests.Expressions; /// /// Tests for Expression Language Phase 2 features: /// null-coalescing (??), ternary (? :), concat() function, and index access ([n]). /// [Collection("ExpressionResolver")] public class ExpressionPhase2Tests : IDisposable { public ExpressionPhase2Tests() { ExpressionResolver.ClearAllCaches(); } public void Dispose() { ExpressionResolver.ClearAllCaches(); } private static IExchange CreateExchange(object? body = null) => new Exchange(new Message(body)); // ═══════════════════════════════════════════════════ // NULL-COALESCING (??) // ═══════════════════════════════════════════════════ #region Null-coalescing (??) [Fact] public void NullCoalescing_LeftNotNull_ReturnsLeft() { var exchange = CreateExchange(); exchange.Properties["name"] = "Alice"; var result = ExpressionResolver.ResolveExpression("name ?? 'default'", exchange); result.Should().Be("Alice"); } [Fact] public void NullCoalescing_LeftNull_ReturnsRight() { var exchange = CreateExchange(); var result = ExpressionResolver.ResolveExpression("missing ?? 'fallback'", exchange); result.Should().Be("fallback"); } [Fact] public void NullCoalescing_ChainedMultiple() { var exchange = CreateExchange(); exchange.Properties["c"] = "third"; var result = ExpressionResolver.ResolveExpression("a ?? b ?? c", exchange); result.Should().Be("third"); } [Fact] public void NullCoalescing_WithNumericFallback() { var exchange = CreateExchange(); var result = ExpressionResolver.ResolveExpression("count ?? 0", exchange); result.Should().Be(0); } [Fact] public void NullCoalescing_InTemplate_LeftPresent() { var exchange = CreateExchange(); exchange.Properties["name"] = "Bob"; var result = ExpressionResolver.ProcessTemplate("Hello ${name ?? 'World'}!", exchange); result.Should().Be("Hello Bob!"); } [Fact] public void NullCoalescing_InTemplate_LeftMissing() { var exchange = CreateExchange(); var result = ExpressionResolver.ProcessTemplate("Hello ${name ?? 'World'}!", exchange); result.Should().Be("Hello World!"); } [Fact] public void NullCoalescing_BothNotNull_ReturnsLeft() { var exchange = CreateExchange(); exchange.Properties["a"] = "first"; exchange.Properties["b"] = "second"; var result = ExpressionResolver.ResolveExpression("a ?? b", exchange); result.Should().Be("first"); } [Fact] public void NullCoalescing_NullFallthroughToLiteral() { var exchange = CreateExchange(); var result = ExpressionResolver.ResolveExpression("x ?? 'default_value'", exchange); result.Should().Be("default_value"); } #endregion // ═══════════════════════════════════════════════════ // TERNARY (? :) // ═══════════════════════════════════════════════════ #region Ternary (? :) [Fact] public void Ternary_TrueCondition_ReturnsIfTrue() { var exchange = CreateExchange(); exchange.Properties["flag"] = true; var result = ExpressionResolver.ResolveExpression("flag ? 'yes' : 'no'", exchange); result.Should().Be("yes"); } [Fact] public void Ternary_FalseCondition_ReturnsIfFalse() { var exchange = CreateExchange(); exchange.Properties["flag"] = false; var result = ExpressionResolver.ResolveExpression("flag ? 'yes' : 'no'", exchange); result.Should().Be("no"); } [Fact] public void Ternary_NullCondition_ReturnsIfFalse() { var exchange = CreateExchange(); var result = ExpressionResolver.ResolveExpression("missing ? 'found' : 'not found'", exchange); result.Should().Be("not found"); } [Fact] public void Ternary_NumericCondition_NonZeroIsTrue() { var exchange = CreateExchange(); exchange.Properties["count"] = 5; var result = ExpressionResolver.ResolveExpression("count ? 'has items' : 'empty'", exchange); result.Should().Be("has items"); } [Fact] public void Ternary_ComparisonCondition() { var exchange = CreateExchange(); exchange.Properties["age"] = 25; var result = ExpressionResolver.ResolveExpression("age > 18 ? 'adult' : 'minor'", exchange); result.Should().Be("adult"); } [Fact] public void Ternary_WithExpressionBranches() { var exchange = CreateExchange(); exchange.Properties["x"] = 10; exchange.Properties["y"] = 20; exchange.Properties["useX"] = true; var result = ExpressionResolver.ResolveExpression("useX ? x : y", exchange); result.Should().Be(10); } [Fact] public void Ternary_InTemplate() { var exchange = CreateExchange(); exchange.Properties["isVip"] = true; var result = ExpressionResolver.ProcessTemplate("Status: ${isVip ? 'VIP' : 'Regular'}", exchange); result.Should().Be("Status: VIP"); } [Fact] public void Ternary_InTemplate_FalsePath() { var exchange = CreateExchange(); exchange.Properties["isVip"] = false; var result = ExpressionResolver.ProcessTemplate("Status: ${isVip ? 'VIP' : 'Regular'}", exchange); result.Should().Be("Status: Regular"); } [Fact] public void Ternary_NestedTernary() { var exchange = CreateExchange(); exchange.Properties["level"] = 3; // level > 2 ? 'high' : (level > 1 ? 'medium' : 'low') var result = ExpressionResolver.ResolveExpression("level > 2 ? 'high' : level > 1 ? 'medium' : 'low'", exchange); result.Should().Be("high"); } [Fact] public void Ternary_StringCondition_NonEmptyIsTrue() { var exchange = CreateExchange(); exchange.Properties["name"] = "Alice"; var result = ExpressionResolver.ResolveExpression("name ? 'named' : 'anonymous'", exchange); result.Should().Be("named"); } #endregion // ═══════════════════════════════════════════════════ // CONCAT() FUNCTION // ═══════════════════════════════════════════════════ #region concat() function [Fact] public void Concat_TwoStrings() { var exchange = CreateExchange(); var result = ExpressionResolver.ResolveExpression("concat('Hello', ' World')", exchange); result.Should().Be("Hello World"); } [Fact] public void Concat_MultipleArguments() { var exchange = CreateExchange(); var result = ExpressionResolver.ResolveExpression("concat('a', 'b', 'c', 'd')", exchange); result.Should().Be("abcd"); } [Fact] public void Concat_WithProperties() { var exchange = CreateExchange(); exchange.Properties["first"] = "John"; exchange.Properties["last"] = "Doe"; var result = ExpressionResolver.ResolveExpression("concat(first, ' ', last)", exchange); result.Should().Be("John Doe"); } [Fact] public void Concat_WithNulls() { var exchange = CreateExchange(); exchange.Properties["name"] = "Alice"; var result = ExpressionResolver.ResolveExpression("concat(name, missing, '!')", exchange); result.Should().Be("Alice!"); } [Fact] public void Concat_WithNumbers() { var exchange = CreateExchange(); exchange.Properties["count"] = 42; var result = ExpressionResolver.ResolveExpression("concat('Count: ', count)", exchange); result.Should().Be("Count: 42"); } [Fact] public void Concat_InTemplate() { var exchange = CreateExchange(); exchange.Properties["first"] = "Jane"; exchange.Properties["last"] = "Smith"; var result = ExpressionResolver.ProcessTemplate("Name: ${concat(first, ' ', last)}", exchange); result.Should().Be("Name: Jane Smith"); } [Fact] public void Concat_SingleArgument() { var exchange = CreateExchange(); var result = ExpressionResolver.ResolveExpression("concat('solo')", exchange); result.Should().Be("solo"); } #endregion // ═══════════════════════════════════════════════════ // INDEX ACCESS ([n]) // ═══════════════════════════════════════════════════ #region Index access ([n]) [Fact] public void IndexAccess_ListByIndex() { var exchange = CreateExchange(); exchange.Properties["items"] = new List { "alpha", "beta", "gamma" }; var result = ExpressionResolver.ResolveExpression("items[0]", exchange); result.Should().Be("alpha"); } [Fact] public void IndexAccess_ListByIndex_SecondElement() { var exchange = CreateExchange(); exchange.Properties["items"] = new List { "alpha", "beta", "gamma" }; var result = ExpressionResolver.ResolveExpression("items[1]", exchange); result.Should().Be("beta"); } [Fact] public void IndexAccess_ListByIndex_LastElement() { var exchange = CreateExchange(); exchange.Properties["items"] = new List { "alpha", "beta", "gamma" }; var result = ExpressionResolver.ResolveExpression("items[2]", exchange); result.Should().Be("gamma"); } [Fact] public void IndexAccess_OutOfBounds_ReturnsNull() { var exchange = CreateExchange(); exchange.Properties["items"] = new List { "alpha" }; var result = ExpressionResolver.ResolveExpression("items[5]", exchange); result.Should().BeNull(); } [Fact] public void IndexAccess_ArrayType() { var exchange = CreateExchange(); exchange.Properties["arr"] = new[] { 10, 20, 30 }; var result = ExpressionResolver.ResolveExpression("arr[1]", exchange); result.Should().Be(20); } [Fact] public void IndexAccess_DictionaryByStringKey() { var exchange = CreateExchange(); exchange.Properties["dict"] = new Dictionary { ["name"] = "Alice", ["age"] = 30 }; var result = ExpressionResolver.ResolveExpression("dict['name']", exchange); result.Should().Be("Alice"); } [Fact] public void IndexAccess_InTemplate() { var exchange = CreateExchange(); exchange.Properties["colors"] = new List { "red", "green", "blue" }; var result = ExpressionResolver.ProcessTemplate("First: ${colors[0]}", exchange); result.Should().Be("First: red"); } [Fact] public void IndexAccess_ChainedWithPropertyAccess() { var exchange = CreateExchange(); exchange.Properties["users"] = new List { new { Name = "Alice", Age = 30 }, new { Name = "Bob", Age = 25 } }; var result = ExpressionResolver.ResolveExpression("users[0].Name", exchange); result.Should().Be("Alice"); } [Fact] public void IndexAccess_NullObject_ReturnsNull() { var exchange = CreateExchange(); var result = ExpressionResolver.ResolveExpression("missing[0]", exchange); result.Should().BeNull(); } #endregion // ═══════════════════════════════════════════════════ // AST PARSING // ═══════════════════════════════════════════════════ #region AST parsing [Fact] public void Ast_NullCoalescing_Parsed() { var tokenizer = new Tokenizer("a ?? b"); var tokens = tokenizer.GetAllTokens(); var parser = new Parser(tokens); var ast = parser.Parse(); ast.Should().BeOfType(); var bin = (BinaryOperationNode)ast; bin.Operator.Should().Be("??"); bin.Left.Should().BeOfType(); bin.Right.Should().BeOfType(); } [Fact] public void Ast_Ternary_Parsed() { var tokenizer = new Tokenizer("a ? b : c"); var tokens = tokenizer.GetAllTokens(); var parser = new Parser(tokens); var ast = parser.Parse(); ast.Should().BeOfType(); var tern = (TernaryNode)ast; tern.Condition.Should().BeOfType(); tern.IfTrue.Should().BeOfType(); tern.IfFalse.Should().BeOfType(); } [Fact] public void Ast_Concat_Parsed() { var tokenizer = new Tokenizer("concat('a', 'b')"); var tokens = tokenizer.GetAllTokens(); var parser = new Parser(tokens); var ast = parser.Parse(); ast.Should().BeOfType(); var func = (FunctionCallNode)ast; func.Name.Should().Be("concat"); func.Arguments.Should().HaveCount(2); } [Fact] public void Ast_IndexAccess_Parsed() { var tokenizer = new Tokenizer("items[0]"); var tokens = tokenizer.GetAllTokens(); var parser = new Parser(tokens); var ast = parser.Parse(); ast.Should().BeOfType(); var idx = (IndexAccessNode)ast; idx.Object.Should().BeOfType(); idx.Index.Should().BeOfType(); } [Fact] public void Ast_ChainedPropertyAndIndex() { var tokenizer = new Tokenizer("obj.items[0].name"); var tokens = tokenizer.GetAllTokens(); var parser = new Parser(tokens); var ast = parser.Parse(); // Should be PropertyAccessNode(IndexAccessNode(PropertyAccessNode(Identifier, "items"), 0), "name") ast.Should().BeOfType(); var prop = (PropertyAccessNode)ast; prop.PropertyName.Should().Be("name"); prop.Object.Should().BeOfType(); } [Fact] public void Ast_TernaryWithComparison() { var tokenizer = new Tokenizer("x > 0 ? 'positive' : 'non-positive'"); var tokens = tokenizer.GetAllTokens(); var parser = new Parser(tokens); var ast = parser.Parse(); ast.Should().BeOfType(); var tern = (TernaryNode)ast; tern.Condition.Should().BeOfType(); var cond = (BinaryOperationNode)tern.Condition; cond.Operator.Should().Be(">"); } [Fact] public void Ast_NullCoalescingWithTernary() { // a ?? (b ? c : d) — ternary has lower precedence than ?? var tokenizer = new Tokenizer("a ?? b ? 'yes' : 'no'"); var tokens = tokenizer.GetAllTokens(); var parser = new Parser(tokens); var ast = parser.Parse(); // Ternary is lowest precedence, so it wraps the ?? ast.Should().BeOfType(); } #endregion // ═══════════════════════════════════════════════════ // COMBINED FEATURES // ═══════════════════════════════════════════════════ #region Combined features [Fact] public void Combined_TernaryWithNullCoalescing() { var exchange = CreateExchange(); exchange.Properties["value"] = null; // null ? 'yes' : 'no' → false path since null is falsy var result = ExpressionResolver.ResolveExpression("value ? 'present' : 'absent'", exchange); result.Should().Be("absent"); } [Fact] public void Combined_IndexAndTernary() { var exchange = CreateExchange(); exchange.Properties["items"] = new List { 1, 2, 3 }; var result = ExpressionResolver.ResolveExpression("items[0] > 0 ? 'positive' : 'negative'", exchange); result.Should().Be("positive"); } [Fact] public void Combined_ConcatAndTernary() { var exchange = CreateExchange(); exchange.Properties["isAdmin"] = true; exchange.Properties["name"] = "Alice"; var result = ExpressionResolver.ResolveExpression( "isAdmin ? concat(name, ' (Admin)') : name", exchange); result.Should().Be("Alice (Admin)"); } [Fact] public void Combined_AllFeaturesInTemplate() { var exchange = CreateExchange(); exchange.Properties["items"] = new List { "first", "second" }; exchange.Properties["label"] = null; var result = ExpressionResolver.ProcessTemplate( "Item: ${items[0]}, Label: ${label ?? 'none'}", exchange); result.Should().Be("Item: first, Label: none"); } #endregion } Path: redb-route/tests/redb.Route.Tests/Expressions/ExpressionPhase3Tests.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/Expressions/ExpressionPhase3Tests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Expressions; namespace redb.Route.Tests.Expressions; /// /// Tests for Expression Language Phase 3 features: /// Built-in functions (upper, lower, trim, length, substring, abs, round, min, max), /// word-form logical operators (NOT, AND, OR, XOR), and AST routing. /// [Collection("ExpressionResolver")] public class ExpressionPhase3Tests : IDisposable { public ExpressionPhase3Tests() { ExpressionResolver.ClearAllCaches(); } public void Dispose() { ExpressionResolver.ClearAllCaches(); } private static IExchange CreateExchange(object? body = null) => new Exchange(new Message(body)); // ═══════════════════════════════════════════════════ // UPPER() // ═══════════════════════════════════════════════════ #region upper() [Fact] public void Upper_StringLiteral() { var exchange = CreateExchange(); var result = ExpressionResolver.ResolveExpression("upper('hello')", exchange); result.Should().Be("HELLO"); } [Fact] public void Upper_Property() { var exchange = CreateExchange(); exchange.Properties["name"] = "alice"; var result = ExpressionResolver.ResolveExpression("upper(property.name)", exchange); result.Should().Be("ALICE"); } [Fact] public void Upper_NullProperty_ReturnsNull() { var exchange = CreateExchange(); var result = ExpressionResolver.ResolveExpression("upper(property.missing)", exchange); result.Should().BeNull(); } [Fact] public void Upper_InComparison() { var exchange = CreateExchange(); exchange.Properties["name"] = "alice"; var result = ExpressionResolver.ResolveExpression("upper(property.name) == 'ALICE'", exchange); result.Should().Be(true); } [Fact] public void Upper_Template() { var exchange = CreateExchange(); exchange.Properties["name"] = "alice"; var result = ExpressionResolver.ResolveExpression("Hello ${upper(property.name)}!", exchange); result.Should().Be("Hello ALICE!"); } #endregion // ═══════════════════════════════════════════════════ // LOWER() // ═══════════════════════════════════════════════════ #region lower() [Fact] public void Lower_StringLiteral() { var exchange = CreateExchange(); var result = ExpressionResolver.ResolveExpression("lower('HELLO')", exchange); result.Should().Be("hello"); } [Fact] public void Lower_Property() { var exchange = CreateExchange(); exchange.Properties["name"] = "ALICE"; var result = ExpressionResolver.ResolveExpression("lower(property.name)", exchange); result.Should().Be("alice"); } [Fact] public void Lower_NullProperty_ReturnsNull() { var exchange = CreateExchange(); var result = ExpressionResolver.ResolveExpression("lower(property.missing)", exchange); result.Should().BeNull(); } [Fact] public void Lower_InComparison() { var exchange = CreateExchange(); exchange.Properties["name"] = "ALICE"; var result = ExpressionResolver.ResolveExpression("lower(property.name) == 'alice'", exchange); result.Should().Be(true); } #endregion // ═══════════════════════════════════════════════════ // TRIM() // ═══════════════════════════════════════════════════ #region trim() [Fact] public void Trim_StringLiteral() { var exchange = CreateExchange(); var result = ExpressionResolver.ResolveExpression("trim(' hello ')", exchange); result.Should().Be("hello"); } [Fact] public void Trim_Property() { var exchange = CreateExchange(); exchange.Properties["name"] = " alice "; var result = ExpressionResolver.ResolveExpression("trim(property.name)", exchange); result.Should().Be("alice"); } [Fact] public void Trim_NullProperty_ReturnsNull() { var exchange = CreateExchange(); var result = ExpressionResolver.ResolveExpression("trim(property.missing)", exchange); result.Should().BeNull(); } #endregion // ═══════════════════════════════════════════════════ // LENGTH() // ═══════════════════════════════════════════════════ #region length() [Fact] public void Length_StringLiteral() { var exchange = CreateExchange(); var result = ExpressionResolver.ResolveExpression("length('hello')", exchange); result.Should().Be(5); } [Fact] public void Length_Property() { var exchange = CreateExchange(); exchange.Properties["name"] = "alice"; var result = ExpressionResolver.ResolveExpression("length(property.name)", exchange); result.Should().Be(5); } [Fact] public void Length_NullProperty_ReturnsNull() { var exchange = CreateExchange(); var result = ExpressionResolver.ResolveExpression("length(property.missing)", exchange); result.Should().BeNull(); } [Fact] public void Length_InComparison() { var exchange = CreateExchange(); exchange.Properties["name"] = "alice"; var result = ExpressionResolver.ResolveExpression("length(property.name) > 3", exchange); result.Should().Be(true); } [Fact] public void Length_EmptyString() { var exchange = CreateExchange(); exchange.Properties["text"] = ""; var result = ExpressionResolver.ResolveExpression("length(property.text)", exchange); result.Should().Be(0); } #endregion // ═══════════════════════════════════════════════════ // SUBSTRING() // ═══════════════════════════════════════════════════ #region substring() [Fact] public void Substring_TwoArgs() { var exchange = CreateExchange(); var result = ExpressionResolver.ResolveExpression("substring('hello world', 6)", exchange); result.Should().Be("world"); } [Fact] public void Substring_ThreeArgs() { var exchange = CreateExchange(); var result = ExpressionResolver.ResolveExpression("substring('hello world', 0, 5)", exchange); result.Should().Be("hello"); } [Fact] public void Substring_Property() { var exchange = CreateExchange(); exchange.Properties["text"] = "abcdef"; var result = ExpressionResolver.ResolveExpression("substring(property.text, 2, 3)", exchange); result.Should().Be("cde"); } [Fact] public void Substring_NullProperty_ReturnsNull() { var exchange = CreateExchange(); var result = ExpressionResolver.ResolveExpression("substring(property.missing, 0, 3)", exchange); result.Should().BeNull(); } #endregion // ═══════════════════════════════════════════════════ // ABS() // ═══════════════════════════════════════════════════ #region abs() [Fact] public void Abs_Negative() { var exchange = CreateExchange(); exchange.Properties["val"] = -42; var result = ExpressionResolver.ResolveExpression("abs(property.val)", exchange); Convert.ToDouble(result).Should().Be(42); } [Fact] public void Abs_Positive() { var exchange = CreateExchange(); exchange.Properties["val"] = 42; var result = ExpressionResolver.ResolveExpression("abs(property.val)", exchange); Convert.ToDouble(result).Should().Be(42); } [Fact] public void Abs_NullProperty_ReturnsNull() { var exchange = CreateExchange(); var result = ExpressionResolver.ResolveExpression("abs(property.missing)", exchange); result.Should().BeNull(); } [Fact] public void Abs_StringNumber() { var exchange = CreateExchange(); exchange.Properties["val"] = "-7.5"; var result = ExpressionResolver.ResolveExpression("abs(property.val)", exchange); Convert.ToDouble(result).Should().Be(7.5); } #endregion // ═══════════════════════════════════════════════════ // ROUND() // ═══════════════════════════════════════════════════ #region round() [Fact] public void Round_OneArg() { var exchange = CreateExchange(); exchange.Properties["val"] = 3.7; var result = ExpressionResolver.ResolveExpression("round(property.val)", exchange); Convert.ToDouble(result).Should().Be(4); } [Fact] public void Round_TwoArgs() { var exchange = CreateExchange(); exchange.Properties["val"] = 3.14159; var result = ExpressionResolver.ResolveExpression("round(property.val, 2)", exchange); Convert.ToDouble(result).Should().Be(3.14); } [Fact] public void Round_NullProperty_ReturnsNull() { var exchange = CreateExchange(); var result = ExpressionResolver.ResolveExpression("round(property.missing)", exchange); result.Should().BeNull(); } #endregion // ═══════════════════════════════════════════════════ // MIN() / MAX() // ═══════════════════════════════════════════════════ #region min() / max() [Fact] public void Min_TwoValues() { var exchange = CreateExchange(); exchange.Properties["a"] = 10; exchange.Properties["b"] = 20; var result = ExpressionResolver.ResolveExpression("min(property.a, property.b)", exchange); Convert.ToDouble(result).Should().Be(10); } [Fact] public void Min_TwoLiterals() { var exchange = CreateExchange(); var result = ExpressionResolver.ResolveExpression("min(5, 3)", exchange); Convert.ToDouble(result).Should().Be(3); } [Fact] public void Max_TwoValues() { var exchange = CreateExchange(); exchange.Properties["a"] = 10; exchange.Properties["b"] = 20; var result = ExpressionResolver.ResolveExpression("max(property.a, property.b)", exchange); Convert.ToDouble(result).Should().Be(20); } [Fact] public void Max_TwoLiterals() { var exchange = CreateExchange(); var result = ExpressionResolver.ResolveExpression("max(7, 3)", exchange); Convert.ToDouble(result).Should().Be(7); } [Fact] public void Min_NullProperty_ReturnsNull() { var exchange = CreateExchange(); exchange.Properties["a"] = 10; var result = ExpressionResolver.ResolveExpression("min(property.a, property.missing)", exchange); result.Should().BeNull(); } #endregion // ═══════════════════════════════════════════════════ // COMBINED EXPRESSIONS // ═══════════════════════════════════════════════════ #region Combined expressions [Fact] public void Upper_Lower_Nested_Concat() { var exchange = CreateExchange(); exchange.Properties["first"] = "alice"; exchange.Properties["last"] = "SMITH"; var result = ExpressionResolver.ResolveExpression( "concat(upper(property.first), ' ', lower(property.last))", exchange); result.Should().Be("ALICE smith"); } [Fact] public void Length_WithArithmetic() { var exchange = CreateExchange(); exchange.Properties["name"] = "alice"; var result = ExpressionResolver.ResolveExpression("length(property.name) + 10", exchange); Convert.ToDouble(result).Should().Be(15); } [Fact] public void Trim_Upper_Chained() { var exchange = CreateExchange(); exchange.Properties["name"] = " alice "; var result = ExpressionResolver.ResolveExpression("upper(trim(property.name))", exchange); result.Should().Be("ALICE"); } [Fact] public void Abs_InComparison() { var exchange = CreateExchange(); exchange.Properties["val"] = -15; var result = ExpressionResolver.ResolveExpression("abs(property.val) > 10", exchange); result.Should().Be(true); } [Fact] public void Round_InArithmetic() { var exchange = CreateExchange(); exchange.Properties["val"] = 3.7; var result = ExpressionResolver.ResolveExpression("round(property.val) * 2", exchange); Convert.ToDouble(result).Should().Be(8); } [Fact] public void Upper_WithNullCoalescing() { var exchange = CreateExchange(); var result = ExpressionResolver.ResolveExpression("upper(property.missing ?? 'default')", exchange); result.Should().Be("DEFAULT"); } [Fact] public void Length_WithTernary() { var exchange = CreateExchange(); exchange.Properties["name"] = "alice"; var result = ExpressionResolver.ResolveExpression( "length(property.name) > 3 ? 'long' : 'short'", exchange); result.Should().Be("long"); } #endregion // ═══════════════════════════════════════════════════ // WORD-FORM LOGICAL OPERATORS (NOT, AND, OR, XOR) // ═══════════════════════════════════════════════════ #region Word-form logical operators [Fact] public void NOT_TrueProperty_ReturnsFalse() { var exchange = CreateExchange(); exchange.Properties["flag"] = true; var result = ExpressionResolver.ResolveExpression("NOT property.flag", exchange); result.Should().Be(false); } [Fact] public void NOT_FalseProperty_ReturnsTrue() { var exchange = CreateExchange(); exchange.Properties["flag"] = false; var result = ExpressionResolver.ResolveExpression("NOT property.flag", exchange); result.Should().Be(true); } [Fact] public void AND_BothTrue() { var exchange = CreateExchange(); exchange.Properties["a"] = 10; exchange.Properties["b"] = 20; var result = ExpressionResolver.ResolveExpression("property.a > 5 AND property.b > 15", exchange); result.Should().Be(true); } [Fact] public void AND_OneFalse() { var exchange = CreateExchange(); exchange.Properties["a"] = 10; exchange.Properties["b"] = 5; var result = ExpressionResolver.ResolveExpression("property.a > 5 AND property.b > 15", exchange); result.Should().Be(false); } [Fact] public void OR_OneFalse() { var exchange = CreateExchange(); exchange.Properties["a"] = 3; exchange.Properties["b"] = 20; var result = ExpressionResolver.ResolveExpression("property.a > 5 OR property.b > 15", exchange); result.Should().Be(true); } [Fact] public void OR_BothFalse() { var exchange = CreateExchange(); exchange.Properties["a"] = 3; exchange.Properties["b"] = 5; var result = ExpressionResolver.ResolveExpression("property.a > 5 OR property.b > 15", exchange); result.Should().Be(false); } [Fact] public void XOR_OnlyOneTrue() { var exchange = CreateExchange(); exchange.Properties["a"] = 10; exchange.Properties["b"] = 5; var result = ExpressionResolver.ResolveExpression("property.a > 5 XOR property.b > 15", exchange); result.Should().Be(true); } [Fact] public void XOR_BothTrue_ReturnsFalse() { var exchange = CreateExchange(); exchange.Properties["a"] = 10; exchange.Properties["b"] = 20; var result = ExpressionResolver.ResolveExpression("property.a > 5 XOR property.b > 15", exchange); result.Should().Be(false); } [Fact] public void SymbolLogical_AndOr() { var exchange = CreateExchange(); exchange.Properties["a"] = 10; exchange.Properties["b"] = 20; var result = ExpressionResolver.ResolveExpression("property.a > 5 && property.b > 15", exchange); result.Should().Be(true); } [Fact] public void SymbolLogical_Not() { var exchange = CreateExchange(); exchange.Properties["flag"] = true; var result = ExpressionResolver.ResolveExpression("!property.flag", exchange); result.Should().Be(false); } #endregion // ═══════════════════════════════════════════════════ // TEMPLATE INTEGRATION // ═══════════════════════════════════════════════════ #region Template integration [Fact] public void Template_Upper() { var exchange = CreateExchange(); exchange.Properties["name"] = "alice"; var result = ExpressionResolver.ResolveExpression("Name: ${upper(property.name)}", exchange); result.Should().Be("Name: ALICE"); } [Fact] public void Template_Lower() { var exchange = CreateExchange(); exchange.Properties["name"] = "ALICE"; var result = ExpressionResolver.ResolveExpression("Name: ${lower(property.name)}", exchange); result.Should().Be("Name: alice"); } [Fact] public void Template_Trim() { var exchange = CreateExchange(); exchange.Properties["name"] = " alice "; var result = ExpressionResolver.ResolveExpression("Name: ${trim(property.name)}", exchange); result.Should().Be("Name: alice"); } [Fact] public void Template_Length() { var exchange = CreateExchange(); exchange.Properties["name"] = "alice"; var result = ExpressionResolver.ResolveExpression("Length: ${length(property.name)}", exchange); result.Should().Be("Length: 5"); } [Fact] public void Template_MultipleFunctions() { var exchange = CreateExchange(); exchange.Properties["first"] = "alice"; exchange.Properties["last"] = "smith"; var result = ExpressionResolver.ResolveExpression( "${upper(property.first)} ${upper(property.last)}", exchange); result.Should().Be("ALICE SMITH"); } #endregion } Path: redb-route/tests/redb.Route.Tests/Expressions/ExpressionPhase4Tests.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/Expressions/ExpressionPhase4Tests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Expressions; namespace redb.Route.Tests.Expressions; /// /// Tests for Expression Language Phase 4 features: /// String functions (contains, startsWith, endsWith, replace), /// Date functions (now, dateFormat, dateAdd), /// Aggregate functions (sum, avg, count). /// [Collection("ExpressionResolver")] public class ExpressionPhase4Tests : IDisposable { public ExpressionPhase4Tests() { ExpressionResolver.ClearAllCaches(); } public void Dispose() { ExpressionResolver.ClearAllCaches(); } private static IExchange CreateExchange(object? body = null) => new Exchange(new Message(body)); // ═══════════════════════════════════════════════════ // CONTAINS() // ═══════════════════════════════════════════════════ #region contains() [Fact] public void Contains_Found() { var exchange = CreateExchange(); exchange.Properties["text"] = "Hello World"; var result = ExpressionResolver.ResolveExpression("contains(property.text, 'world')", exchange); result.Should().Be(true); } [Fact] public void Contains_NotFound() { var exchange = CreateExchange(); exchange.Properties["text"] = "Hello World"; var result = ExpressionResolver.ResolveExpression("contains(property.text, 'xyz')", exchange); result.Should().Be(false); } [Fact] public void Contains_NullProperty() { var exchange = CreateExchange(); var result = ExpressionResolver.ResolveExpression("contains(property.missing, 'test')", exchange); result.Should().Be(false); } [Fact] public void Contains_CaseInsensitive() { var exchange = CreateExchange(); exchange.Properties["text"] = "Hello World"; var result = ExpressionResolver.ResolveExpression("contains(property.text, 'HELLO')", exchange); result.Should().Be(true); } [Fact] public void Contains_InLogicalExpression() { var exchange = CreateExchange(); exchange.Properties["name"] = "alice.smith"; var result = ExpressionResolver.ResolveExpression("contains(property.name, '.') == true", exchange); result.Should().Be(true); } [Fact] public void Contains_LiteralStrings() { var exchange = CreateExchange(); var result = ExpressionResolver.ResolveExpression("contains('hello world', 'world')", exchange); result.Should().Be(true); } #endregion // ═══════════════════════════════════════════════════ // STARTSWITH() // ═══════════════════════════════════════════════════ #region startsWith() [Fact] public void StartsWith_True() { var exchange = CreateExchange(); exchange.Properties["text"] = "Hello World"; var result = ExpressionResolver.ResolveExpression("startsWith(property.text, 'hello')", exchange); result.Should().Be(true); } [Fact] public void StartsWith_False() { var exchange = CreateExchange(); exchange.Properties["text"] = "Hello World"; var result = ExpressionResolver.ResolveExpression("startsWith(property.text, 'world')", exchange); result.Should().Be(false); } [Fact] public void StartsWith_NullProperty() { var exchange = CreateExchange(); var result = ExpressionResolver.ResolveExpression("startsWith(property.missing, 'test')", exchange); result.Should().Be(false); } #endregion // ═══════════════════════════════════════════════════ // ENDSWITH() // ═══════════════════════════════════════════════════ #region endsWith() [Fact] public void EndsWith_True() { var exchange = CreateExchange(); exchange.Properties["text"] = "Hello World"; var result = ExpressionResolver.ResolveExpression("endsWith(property.text, 'world')", exchange); result.Should().Be(true); } [Fact] public void EndsWith_False() { var exchange = CreateExchange(); exchange.Properties["text"] = "Hello World"; var result = ExpressionResolver.ResolveExpression("endsWith(property.text, 'hello')", exchange); result.Should().Be(false); } [Fact] public void EndsWith_NullProperty() { var exchange = CreateExchange(); var result = ExpressionResolver.ResolveExpression("endsWith(property.missing, 'test')", exchange); result.Should().Be(false); } #endregion // ═══════════════════════════════════════════════════ // REPLACE() // ═══════════════════════════════════════════════════ #region replace() [Fact] public void Replace_Simple() { var exchange = CreateExchange(); exchange.Properties["text"] = "Hello World"; var result = ExpressionResolver.ResolveExpression("replace(property.text, 'World', 'Earth')", exchange); result.Should().Be("Hello Earth"); } [Fact] public void Replace_MultipleOccurrences() { var exchange = CreateExchange(); exchange.Properties["text"] = "aaa-bbb-aaa"; var result = ExpressionResolver.ResolveExpression("replace(property.text, 'aaa', 'xxx')", exchange); result.Should().Be("xxx-bbb-xxx"); } [Fact] public void Replace_NullProperty() { var exchange = CreateExchange(); var result = ExpressionResolver.ResolveExpression("replace(property.missing, 'old', 'new')", exchange); result.Should().BeNull(); } [Fact] public void Replace_InTemplate() { var exchange = CreateExchange(); exchange.Properties["text"] = "Hello World"; var result = ExpressionResolver.ResolveExpression("Result: ${replace(property.text, 'World', 'Earth')}", exchange); result.Should().Be("Result: Hello Earth"); } [Fact] public void Replace_LiteralStrings() { var exchange = CreateExchange(); var result = ExpressionResolver.ResolveExpression("replace('foo-bar-baz', '-', '/')", exchange); result.Should().Be("foo/bar/baz"); } #endregion // ═══════════════════════════════════════════════════ // NOW() // ═══════════════════════════════════════════════════ #region now() [Fact] public void Now_ReturnsDateTime() { var exchange = CreateExchange(); var before = DateTime.UtcNow; var result = ExpressionResolver.ResolveExpression("now()", exchange); var after = DateTime.UtcNow; result.Should().BeOfType(); var dt = (DateTime)result!; dt.Should().BeOnOrAfter(before).And.BeOnOrBefore(after); } [Fact] public void Now_InTemplate() { var exchange = CreateExchange(); var result = ExpressionResolver.ResolveExpression("Time: ${now()}", exchange)?.ToString(); result.Should().StartWith("Time: "); result!.Length.Should().BeGreaterThan(6); } #endregion // ═══════════════════════════════════════════════════ // DATEFORMAT() // ═══════════════════════════════════════════════════ #region dateFormat() [Fact] public void DateFormat_DateTime() { var exchange = CreateExchange(); exchange.Properties["date"] = new DateTime(2026, 3, 6, 14, 30, 0); var result = ExpressionResolver.ResolveExpression("dateFormat(property.date, 'yyyy-MM-dd')", exchange); result.Should().Be("2026-03-06"); } [Fact] public void DateFormat_CustomFormat() { var exchange = CreateExchange(); exchange.Properties["date"] = new DateTime(2026, 3, 6, 14, 30, 0); var result = ExpressionResolver.ResolveExpression("dateFormat(property.date, 'dd.MM.yyyy HH:mm')", exchange); result.Should().Be("06.03.2026 14:30"); } [Fact] public void DateFormat_StringDate() { var exchange = CreateExchange(); exchange.Properties["date"] = "2026-03-06"; var result = ExpressionResolver.ResolveExpression("dateFormat(property.date, 'dd/MM/yyyy')", exchange); result.Should().Be("06/03/2026"); } [Fact] public void DateFormat_InTemplate() { var exchange = CreateExchange(); exchange.Properties["date"] = new DateTime(2026, 3, 6); var result = ExpressionResolver.ResolveExpression("Date: ${dateFormat(property.date, 'yyyy-MM-dd')}", exchange); result.Should().Be("Date: 2026-03-06"); } [Fact] public void DateFormat_DateTimeOffset() { var exchange = CreateExchange(); exchange.Properties["date"] = new DateTimeOffset(2026, 3, 6, 14, 30, 0, TimeSpan.FromHours(3)); var result = ExpressionResolver.ResolveExpression("dateFormat(property.date, 'yyyy-MM-dd')", exchange); result.Should().Be("2026-03-06"); } #endregion // ═══════════════════════════════════════════════════ // DATEADD() // ═══════════════════════════════════════════════════ #region dateAdd() [Fact] public void DateAdd_Days() { var exchange = CreateExchange(); exchange.Properties["date"] = new DateTime(2026, 3, 1); var result = ExpressionResolver.ResolveExpression("dateAdd(property.date, 5, 'days')", exchange); result.Should().Be(new DateTime(2026, 3, 6)); } [Fact] public void DateAdd_Hours() { var exchange = CreateExchange(); exchange.Properties["date"] = new DateTime(2026, 3, 6, 10, 0, 0); var result = ExpressionResolver.ResolveExpression("dateAdd(property.date, 3, 'hours')", exchange); result.Should().Be(new DateTime(2026, 3, 6, 13, 0, 0)); } [Fact] public void DateAdd_Months() { var exchange = CreateExchange(); exchange.Properties["date"] = new DateTime(2026, 1, 15); var result = ExpressionResolver.ResolveExpression("dateAdd(property.date, 2, 'months')", exchange); result.Should().Be(new DateTime(2026, 3, 15)); } [Fact] public void DateAdd_NegativeDays() { var exchange = CreateExchange(); exchange.Properties["date"] = new DateTime(2026, 3, 6); var result = ExpressionResolver.ResolveExpression("dateAdd(property.date, -1, 'days')", exchange); result.Should().Be(new DateTime(2026, 3, 5)); } [Fact] public void DateAdd_Minutes() { var exchange = CreateExchange(); exchange.Properties["date"] = new DateTime(2026, 3, 6, 10, 0, 0); var result = ExpressionResolver.ResolveExpression("dateAdd(property.date, 30, 'minutes')", exchange); result.Should().Be(new DateTime(2026, 3, 6, 10, 30, 0)); } [Fact] public void DateAdd_Years() { var exchange = CreateExchange(); exchange.Properties["date"] = new DateTime(2026, 3, 6); var result = ExpressionResolver.ResolveExpression("dateAdd(property.date, 1, 'years')", exchange); result.Should().Be(new DateTime(2027, 3, 6)); } [Fact] public void DateAdd_NullDate_ReturnsNull() { var exchange = CreateExchange(); var result = ExpressionResolver.ResolveExpression("dateAdd(property.missing, 1, 'days')", exchange); result.Should().BeNull(); } [Fact] public void DateAdd_StringDate() { var exchange = CreateExchange(); exchange.Properties["date"] = "2026-03-01"; var result = ExpressionResolver.ResolveExpression("dateAdd(property.date, 5, 'days')", exchange); result.Should().Be(new DateTime(2026, 3, 6)); } #endregion // ═══════════════════════════════════════════════════ // SUM() // ═══════════════════════════════════════════════════ #region sum() [Fact] public void Sum_IntList() { var exchange = CreateExchange(); exchange.Properties["items"] = new List { 1, 2, 3, 4, 5 }; var result = ExpressionResolver.ResolveExpression("sum(property.items)", exchange); Convert.ToDouble(result).Should().Be(15); } [Fact] public void Sum_DoubleArray() { var exchange = CreateExchange(); exchange.Properties["items"] = new double[] { 1.5, 2.5, 3.0 }; var result = ExpressionResolver.ResolveExpression("sum(property.items)", exchange); Convert.ToDouble(result).Should().Be(7.0); } [Fact] public void Sum_NullProperty() { var exchange = CreateExchange(); var result = ExpressionResolver.ResolveExpression("sum(property.missing)", exchange); result.Should().BeNull(); } [Fact] public void Sum_EmptyList() { var exchange = CreateExchange(); exchange.Properties["items"] = new List(); var result = ExpressionResolver.ResolveExpression("sum(property.items)", exchange); Convert.ToDouble(result).Should().Be(0); } #endregion // ═══════════════════════════════════════════════════ // AVG() // ═══════════════════════════════════════════════════ #region avg() [Fact] public void Avg_IntList() { var exchange = CreateExchange(); exchange.Properties["items"] = new List { 2, 4, 6 }; var result = ExpressionResolver.ResolveExpression("avg(property.items)", exchange); Convert.ToDouble(result).Should().Be(4); } [Fact] public void Avg_DoubleArray() { var exchange = CreateExchange(); exchange.Properties["items"] = new double[] { 1.0, 2.0, 3.0 }; var result = ExpressionResolver.ResolveExpression("avg(property.items)", exchange); Convert.ToDouble(result).Should().Be(2.0); } [Fact] public void Avg_NullProperty() { var exchange = CreateExchange(); var result = ExpressionResolver.ResolveExpression("avg(property.missing)", exchange); result.Should().BeNull(); } [Fact] public void Avg_EmptyList() { var exchange = CreateExchange(); exchange.Properties["items"] = new List(); var result = ExpressionResolver.ResolveExpression("avg(property.items)", exchange); result.Should().BeNull(); } #endregion // ═══════════════════════════════════════════════════ // COUNT() // ═══════════════════════════════════════════════════ #region count() [Fact] public void Count_List() { var exchange = CreateExchange(); exchange.Properties["items"] = new List { "a", "b", "c" }; var result = ExpressionResolver.ResolveExpression("count(property.items)", exchange); Convert.ToInt32(result).Should().Be(3); } [Fact] public void Count_Array() { var exchange = CreateExchange(); exchange.Properties["items"] = new int[] { 10, 20 }; var result = ExpressionResolver.ResolveExpression("count(property.items)", exchange); Convert.ToInt32(result).Should().Be(2); } [Fact] public void Count_EmptyList() { var exchange = CreateExchange(); exchange.Properties["items"] = new List(); var result = ExpressionResolver.ResolveExpression("count(property.items)", exchange); Convert.ToInt32(result).Should().Be(0); } [Fact] public void Count_NullProperty() { var exchange = CreateExchange(); var result = ExpressionResolver.ResolveExpression("count(property.missing)", exchange); Convert.ToInt32(result).Should().Be(0); } [Fact] public void Count_SingleValue() { var exchange = CreateExchange(); exchange.Properties["val"] = 42; var result = ExpressionResolver.ResolveExpression("count(property.val)", exchange); Convert.ToInt32(result).Should().Be(1); } #endregion // ═══════════════════════════════════════════════════ // COMBINED / CROSS-FEATURE EXPRESSIONS // ═══════════════════════════════════════════════════ #region Combined expressions [Fact] public void Contains_WithNot() { var exchange = CreateExchange(); exchange.Properties["text"] = "Hello World"; var result = ExpressionResolver.ResolveExpression("NOT contains(property.text, 'xyz')", exchange); result.Should().Be(true); } [Fact] public void Replace_WithUpper() { var exchange = CreateExchange(); exchange.Properties["text"] = "hello world"; var result = ExpressionResolver.ResolveExpression("upper(replace(property.text, 'world', 'earth'))", exchange); result.Should().Be("HELLO EARTH"); } [Fact] public void DateFormat_Now() { var exchange = CreateExchange(); var result = ExpressionResolver.ResolveExpression("dateFormat(now(), 'yyyy')", exchange); result.Should().Be(DateTime.UtcNow.Year.ToString()); } [Fact] public void Sum_InComparison() { var exchange = CreateExchange(); exchange.Properties["items"] = new List { 1, 2, 3 }; var result = ExpressionResolver.ResolveExpression("sum(property.items) > 5", exchange); result.Should().Be(true); } [Fact] public void Count_WithTernary() { var exchange = CreateExchange(); exchange.Properties["items"] = new List { 1, 2, 3 }; var result = ExpressionResolver.ResolveExpression("count(property.items) > 2 ? 'many' : 'few'", exchange); result.Should().Be("many"); } [Fact] public void Avg_InArithmetic() { var exchange = CreateExchange(); exchange.Properties["scores"] = new List { 80, 90, 100 }; var result = ExpressionResolver.ResolveExpression("avg(property.scores) + 10", exchange); Convert.ToDouble(result).Should().Be(100); } [Fact] public void StartsWith_AND_EndsWith() { var exchange = CreateExchange(); exchange.Properties["file"] = "report.pdf"; var result = ExpressionResolver.ResolveExpression( "startsWith(property.file, 'report') AND endsWith(property.file, '.pdf')", exchange); result.Should().Be(true); } [Fact] public void DateAdd_DateFormat_Chained() { var exchange = CreateExchange(); exchange.Properties["date"] = new DateTime(2026, 3, 1); var result = ExpressionResolver.ResolveExpression( "dateFormat(dateAdd(property.date, 5, 'days'), 'yyyy-MM-dd')", exchange); result.Should().Be("2026-03-06"); } [Fact] public void Replace_Template() { var exchange = CreateExchange(); exchange.Properties["path"] = "/api/v1/users"; var result = ExpressionResolver.ResolveExpression( "Path: ${replace(property.path, '/api/v1', '/api/v2')}", exchange); result.Should().Be("Path: /api/v2/users"); } [Fact] public void Contains_Template() { var exchange = CreateExchange(); exchange.Properties["text"] = "Hello World"; var result = ExpressionResolver.ResolveExpression( "Has world: ${contains(property.text, 'world')}", exchange); result.Should().Be("Has world: True"); } #endregion } Path: redb-route/tests/redb.Route.Tests/Expressions/ExpressionPositions.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/Expressions/ExpressionPositions.cs ---- using System.Globalization; using System.Text; using redb.Route.Abstractions; using redb.Route.Expressions; using redb.Route.Predicates; namespace redb.Route.Tests.Expressions; /// /// Evaluates one form of the language through every position it can appear in, and renders the /// outcome as one deterministic line. This is the engine of the characterisation net: the corpus /// supplies the forms, this supplies the four answers, and the snapshot pins them. /// internal static class ExpressionPositions { /// The positions a string can occupy in the language. internal static readonly string[] Names = ["value", "condition", "template"]; /// /// Renders the whole corpus as a text document, grouped by section, one line per form. /// /// Runs under so the snapshot is the same on every /// machine. Template interpolation formats numbers with the ambient culture, which would /// otherwise make this file depend on the developer's regional settings; that dependency is /// itself pinned separately by ExpressionLanguageSnapshotTests. /// /// internal static string RenderSnapshot() { var previous = CultureInfo.CurrentCulture; CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; try { return RenderSnapshotCore(); } finally { CultureInfo.CurrentCulture = previous; } } private static string RenderSnapshotCore() { var text = new StringBuilder(); text.AppendLine("# Characterisation of the redb.Route expression language."); text.AppendLine("#"); text.AppendLine("# One line per form of the corpus, four columns, one per position:"); text.AppendLine("# value — StringExpression(form), what SetBody / SetHeader / a connector option does"); text.AppendLine("# condition — PredicateFactory.FromString(form), what Filter / When / LoopWhile / Validate does"); text.AppendLine("# template — StringExpression(\"${form}\"), the interpolated form"); text.AppendLine("#"); text.AppendLine("# This file records what the language does TODAY, right or wrong. A diff here means"); text.AppendLine("# behaviour moved; every moved line has to be explained before the snapshot is updated."); var group = string.Empty; foreach (var entry in ExpressionCorpus.Entries) { if (entry.Group != group) { group = entry.Group; text.AppendLine(); text.AppendLine($"## {group}"); } text.AppendLine(RenderLine(entry)); } return text.ToString(); } private static string RenderLine(ExpressionCorpus.Entry entry) { var form = entry.Form; var fixture = entry.Fixture == ExpressionCorpus.Fixture.Object ? string.Empty : $" @{entry.Fixture}"; return string.Join( " | ", $"{Escape(form)}{fixture}", $"value={Value(form, entry.Fixture)}", $"condition={Condition(form, entry.Fixture)}", $"template={Template(entry)}"); } private static string Value(string form, ExpressionCorpus.Fixture fixture) => Capture(() => new StringExpression(form).Evaluate(ExpressionCorpus.CreateExchange(fixture))); private static string Condition(string form, ExpressionCorpus.Fixture fixture) => Capture(() => PredicateFactory.FromString(form).Matches(ExpressionCorpus.CreateExchange(fixture))); private static string Template(ExpressionCorpus.Entry entry) => entry.Templated ? "-" : Capture(() => new StringExpression("${" + entry.Form + "}") .Evaluate(ExpressionCorpus.CreateExchange(entry.Fixture))); /// /// Runs an evaluation and renders its outcome, a value or the type of whatever it threw. /// Exception messages are deliberately not recorded: they carry file paths and framework /// wording, and the signal here is what happened, not how it was phrased. /// private static string Capture(Func evaluate) { try { return Render(evaluate()); } catch (Exception ex) { return $"!{ex.GetType().Name}"; } } private static string Render(object? value) => value switch { null => "null", string s => $"\"{Escape(s)}\"", bool b => b ? "true" : "false", int or long or short or byte => $"{Convert.ToInt64(value, CultureInfo.InvariantCulture)}:{value.GetType().Name}", double or float or decimal => $"{redb.Route.Core.RouteDecimal.From(value).ToString(CultureInfo.InvariantCulture)}:{value.GetType().Name}", System.Collections.ICollection collection => $"<{value.GetType().Name} count={collection.Count}>", _ => $"<{value.GetType().Name}>" }; private static string Escape(string text) => text.Replace("\\", "\\\\").Replace("\t", "\\t").Replace("\r", "\\r").Replace("\n", "\\n"); } Path: redb-route/tests/redb.Route.Tests/Expressions/ExpressionResolverCollection.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/Expressions/ExpressionResolverCollection.cs ---- namespace redb.Route.Tests.Expressions; /// /// The classes that clear and count the expression caches, which are process state. The collection disables /// parallelization, so no test of another collection compiles or clears between a clear and the count read after it. /// [CollectionDefinition("ExpressionResolver", DisableParallelization = true)] public class ExpressionResolverCollection; Path: redb-route/tests/redb.Route.Tests/Expressions/ExpressionResolverFullTests.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/Expressions/ExpressionResolverFullTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Expressions; using redb.Route.Predicates; namespace redb.Route.Tests.Expressions; /// /// Comprehensive tests for ExpressionResolver — covers template processing, /// logical expressions, value expressions, arithmetic, unary/binary operators, /// increment/decrement, string methods, type coercion, nested properties, /// runtime resolvers, edge cases, and AST integration. /// [Collection("ExpressionResolver")] public class ExpressionResolverFullTests : IDisposable { public ExpressionResolverFullTests() { ExpressionResolver.ClearAllCaches(); } public void Dispose() { ExpressionResolver.ClearAllCaches(); } // The hand-written logical branch (EvaluateLogicalExpression / CompileLogicalPredicate) was // removed on 2026-08-28 - one language, one parser. The semantic tests below migrated to the // surviving condition path; these helpers keep the call shape of the old API. private static bool EvaluateCondition(string condition, IExchange exchange) => PredicateFactory.FromString(condition).Matches(exchange); private static Func CompileCondition(string condition) => PredicateFactory.FromString(condition).Matches; private static IExchange CreateExchange(object? body = null) => new Exchange(new Message(body)); // ═══════════════════════════════════════════════════ // 1. TEMPLATE RESOLUTION — ProcessTemplate // ═══════════════════════════════════════════════════ #region Template resolution [Fact] public void ProcessTemplate_EmptyString_ReturnsEmpty() { var exchange = CreateExchange("body"); var result = ExpressionResolver.ProcessTemplate("", exchange); result.Should().Be(""); } [Fact] public void ProcessTemplate_NullTemplate_ReturnsNull() { var exchange = CreateExchange("body"); var result = ExpressionResolver.ProcessTemplate(null!, exchange); result.Should().BeNull(); } [Fact] public void ProcessTemplate_BodyDotProperty_ResolvesNestedProperty() { var exchange = CreateExchange(new { Name = "Alice", Age = 30 }); var result = ExpressionResolver.ProcessTemplate("Name: ${body.Name}", exchange); result.Should().Be("Name: Alice"); } [Fact] public void ProcessTemplate_BodyDotNestedProperty_ResolvesDeepNesting() { var exchange = CreateExchange(new { Address = new { City = "Moscow" } }); var result = ExpressionResolver.ProcessTemplate("City: ${body.Address.City}", exchange); result.Should().Be("City: Moscow"); } [Fact] public void ProcessTemplate_PropertyDotNestedProperty_ResolvesNesting() { var exchange = CreateExchange("body"); exchange.Properties["customer"] = new { Name = "Bob", Address = new { City = "SPb" } }; var result = ExpressionResolver.ProcessTemplate("City: ${property.customer.Address.City}", exchange); result.Should().Be("City: SPb"); } [Fact] public void ProcessTemplate_ExceptionFullObject_ReturnsToString() { var exchange = CreateExchange("body"); exchange.Exception = new InvalidOperationException("fail"); var result = ExpressionResolver.ProcessTemplate("Err: ${exception}", exchange); result.Should().Contain("fail"); } [Fact] public void ProcessTemplate_ExceptionStackTrace_WhenNull_ReturnsEmpty() { var exchange = CreateExchange("body"); // No exception set var result = ExpressionResolver.ProcessTemplate("ST: ${exception.StackTrace}", exchange); result.Should().Be("ST: "); } [Fact] public void ProcessTemplate_LogicalFunction_ReturnsTrue() { var exchange = CreateExchange("body"); exchange.Properties["x"] = 10; var result = ExpressionResolver.ProcessTemplate("Result: ${logical(property.x > 5)}", exchange); result.Should().Be("Result: True"); } [Fact] public void ProcessTemplate_LogicalFunction_ReturnsFalse() { var exchange = CreateExchange("body"); exchange.Properties["x"] = 3; var result = ExpressionResolver.ProcessTemplate("Result: ${logical(property.x > 5)}", exchange); result.Should().Be("Result: False"); } [Fact] public void ProcessTemplate_ArithmeticExpression_InsideTemplate() { var exchange = CreateExchange("body"); exchange.Properties["a"] = 10; exchange.Properties["b"] = 7; var result = ExpressionResolver.ProcessTemplate("Sum: ${property.a + property.b}", exchange); result.Should().Be("Sum: 17"); } [Fact] public void ProcessTemplate_DefaultExchangeProperty_NoPrefix() { var exchange = CreateExchange("body"); exchange.Properties["myVar"] = "hello"; var result = ExpressionResolver.ProcessTemplate("Value: ${myVar}", exchange); result.Should().Be("Value: hello"); } #endregion // ═══════════════════════════════════════════════════ // 2. LOGICAL EXPRESSIONS — EvaluateLogicalExpression // ═══════════════════════════════════════════════════ #region Logical expressions — comparison operators [Fact] public void Condition_NotEqual_True() { var exchange = CreateExchange("body"); exchange.Properties["status"] = "active"; EvaluateCondition("property.status != 'inactive'", exchange) .Should().BeTrue(); } [Fact] public void Condition_NotEqual_False() { var exchange = CreateExchange("body"); exchange.Properties["status"] = "active"; EvaluateCondition("property.status != 'active'", exchange) .Should().BeFalse(); } [Fact] public void Condition_LessThan_True() { var exchange = CreateExchange("body"); exchange.Properties["count"] = 3; EvaluateCondition("property.count < 10", exchange) .Should().BeTrue(); } [Fact] public void Condition_LessThan_False() { var exchange = CreateExchange("body"); exchange.Properties["count"] = 10; EvaluateCondition("property.count < 5", exchange) .Should().BeFalse(); } [Fact] public void Condition_GreaterOrEqual_True() { var exchange = CreateExchange("body"); exchange.Properties["count"] = 5; EvaluateCondition("property.count >= 5", exchange) .Should().BeTrue(); } [Fact] public void Condition_GreaterOrEqual_False() { var exchange = CreateExchange("body"); exchange.Properties["count"] = 4; EvaluateCondition("property.count >= 5", exchange) .Should().BeFalse(); } [Fact] public void Condition_LessOrEqual_True() { var exchange = CreateExchange("body"); exchange.Properties["count"] = 5; EvaluateCondition("property.count <= 5", exchange) .Should().BeTrue(); } [Fact] public void Condition_LessOrEqual_False() { var exchange = CreateExchange("body"); exchange.Properties["count"] = 6; EvaluateCondition("property.count <= 5", exchange) .Should().BeFalse(); } #endregion #region Logical expressions — connectives [Fact] public void Condition_XOR_TrueWhenOnlyOneTrue() { var exchange = CreateExchange("body"); exchange.Properties["a"] = 10; exchange.Properties["b"] = 3; // a > 5 is true, b > 5 is false → XOR = true EvaluateCondition("property.a > 5 XOR property.b > 5", exchange) .Should().BeTrue(); } [Fact] public void Condition_XOR_FalseWhenBothTrue() { var exchange = CreateExchange("body"); exchange.Properties["a"] = 10; exchange.Properties["b"] = 10; // Both true → XOR = false EvaluateCondition("property.a > 5 XOR property.b > 5", exchange) .Should().BeFalse(); } [Fact] public void Condition_PropertyAsBooleanTruthy() { var exchange = CreateExchange("body"); exchange.Properties["flag"] = true; EvaluateCondition("property.flag", exchange) .Should().BeTrue(); } [Fact] public void Condition_PropertyAsBooleanFalsy() { var exchange = CreateExchange("body"); exchange.Properties["flag"] = false; EvaluateCondition("property.flag", exchange) .Should().BeFalse(); } [Fact] public void Condition_StringEquality() { var exchange = CreateExchange("body"); exchange.In.Headers["type"] = "order"; EvaluateCondition("header.type == 'order'", exchange) .Should().BeTrue(); } [Fact] public void Condition_HeaderNumericComparison() { var exchange = CreateExchange("body"); exchange.In.Headers["status"] = 200; EvaluateCondition("header.status == 200", exchange) .Should().BeTrue(); } [Fact] public void Condition_AND_BothFalse() { var exchange = CreateExchange("body"); exchange.Properties["a"] = 1; exchange.Properties["b"] = 2; EvaluateCondition("property.a > 5 AND property.b > 5", exchange) .Should().BeFalse(); } [Fact] public void Condition_OR_BothFalse() { var exchange = CreateExchange("body"); exchange.Properties["a"] = 1; exchange.Properties["b"] = 2; EvaluateCondition("property.a > 5 OR property.b > 5", exchange) .Should().BeFalse(); } #endregion // ═══════════════════════════════════════════════════ // 3. VALUE EXPRESSIONS — GetCompiledValueExpression // ═══════════════════════════════════════════════════ #region Value expressions — literals [Fact] public void ValueExpression_DoubleLiteral() { var expr = ExpressionResolver.GetCompiledValueExpression("3.14"); var exchange = CreateExchange("body"); Convert.ToDouble(expr(exchange)).Should().BeApproximately(3.14, 0.001); } [Fact] public void ValueExpression_BooleanLiteral_True() { var expr = ExpressionResolver.GetCompiledValueExpression("true"); var exchange = CreateExchange("body"); expr(exchange).Should().Be(true); } [Fact] public void ValueExpression_BooleanLiteral_False() { var expr = ExpressionResolver.GetCompiledValueExpression("false"); var exchange = CreateExchange("body"); expr(exchange).Should().Be(false); } [Fact] public void ValueExpression_NullLiteral() { var expr = ExpressionResolver.GetCompiledValueExpression("null"); var exchange = CreateExchange("body"); expr(exchange).Should().BeNull(); } [Fact] public void ValueExpression_DoubleQuotedString() { var expr = ExpressionResolver.GetCompiledValueExpression("\"hello\""); var exchange = CreateExchange("body"); expr(exchange).Should().Be("hello"); } #endregion #region Value expressions — nested property access [Fact] public void ValueExpression_NestedPropertyAccess() { var expr = ExpressionResolver.GetCompiledValueExpression("property.customer.Name"); var exchange = CreateExchange("body"); exchange.Properties["customer"] = new { Name = "Alice" }; expr(exchange)?.ToString().Should().Be("Alice"); } [Fact] public void ValueExpression_BodyPropertyAccess() { var expr = ExpressionResolver.GetCompiledValueExpression("body.Name"); var exchange = CreateExchange(new { Name = "Bob" }); expr(exchange)?.ToString().Should().Be("Bob"); } [Fact] public void ValueExpression_DeepBodyPropertyAccess() { var expr = ExpressionResolver.GetCompiledValueExpression("body.Address.City"); var exchange = CreateExchange(new { Address = new { City = "Moscow" } }); expr(exchange)?.ToString().Should().Be("Moscow"); } [Fact] public void ValueExpression_PropertyObjectIntField_Compiled() { // property.MyObject.PropInt — compiled via GetCompiledValueExpression var expr = ExpressionResolver.GetCompiledValueExpression("property.MyObject.PropInt"); var exchange = CreateExchange("body"); exchange.Properties["MyObject"] = new { PropInt = 42 }; Convert.ToInt32(expr(exchange)).Should().Be(42); } [Fact] public void ValueExpression_PropertyObjectIntField_Runtime() { // property.MyObject.PropInt — runtime via ResolveExpression var exchange = CreateExchange("body"); exchange.Properties["MyObject"] = new { PropInt = 99 }; var result = ExpressionResolver.ResolveExpression("property.MyObject.PropInt", exchange); Convert.ToInt32(result).Should().Be(99); } [Fact] public void ValueExpression_HeaderObjectIntField_Compiled() { // header.MyObject.PropInt — compiled path var expr = ExpressionResolver.GetCompiledValueExpression("header.MyObject.PropInt"); var exchange = CreateExchange("body"); exchange.In.Headers["MyObject"] = new { PropInt = 77 }; Convert.ToInt32(expr(exchange)).Should().Be(77); } [Fact] public void ValueExpression_HeaderObjectIntField_Runtime() { // header.MyObject.PropInt — runtime via ResolveExpression var exchange = CreateExchange("body"); exchange.In.Headers["MyObject"] = new { PropInt = 55 }; var result = ExpressionResolver.ResolveExpression("header.MyObject.PropInt", exchange); Convert.ToInt32(result).Should().Be(55); } [Fact] public void ValueExpression_DeepNestedPropertyAccess_ThreeLevels() { // property.A.B.C — 3 levels deep var expr = ExpressionResolver.GetCompiledValueExpression("property.root.child.value"); var exchange = CreateExchange("body"); exchange.Properties["root"] = new { child = new { value = "deep" } }; expr(exchange)?.ToString().Should().Be("deep"); } [Fact] public void ValueExpression_PropertyObjectStringField() { var expr = ExpressionResolver.GetCompiledValueExpression("property.obj.Name"); var exchange = CreateExchange("body"); exchange.Properties["obj"] = new { Name = "test", Count = 5 }; expr(exchange)?.ToString().Should().Be("test"); } [Fact] public void ValueExpression_HeaderObjectDeepAccess() { // header.data.Inner.Value — 2 levels within header object var expr = ExpressionResolver.GetCompiledValueExpression("header.data.Inner.Value"); var exchange = CreateExchange("body"); exchange.In.Headers["data"] = new { Inner = new { Value = 123 } }; Convert.ToInt32(expr(exchange)).Should().Be(123); } [Fact] public void ValueExpression_PropertyObjectNullIntermediateReturnsNull() { // property.obj.Missing — obj exists but Missing doesn't var expr = ExpressionResolver.GetCompiledValueExpression("property.obj.Missing"); var exchange = CreateExchange("body"); exchange.Properties["obj"] = new { Name = "test" }; expr(exchange).Should().BeNull(); } [Fact] public void ValueExpression_TemplateWithNestedPropertyObject() { // ${property.MyObject.PropInt} inside a template var template = ExpressionResolver.GetCompiledTemplate("Value: ${property.MyObject.PropInt}"); var exchange = CreateExchange("body"); exchange.Properties["MyObject"] = new { PropInt = 42 }; template(exchange).Should().Be("Value: 42"); } [Fact] public void ValueExpression_TemplateWithNestedHeaderObject() { // ${header.MyObject.PropInt} inside a template var template = ExpressionResolver.GetCompiledTemplate("Header: ${header.info.Status}"); var exchange = CreateExchange("body"); exchange.In.Headers["info"] = new { Status = "OK" }; template(exchange).Should().Be("Header: OK"); } [Fact] public void Condition_NestedPropertyWithNestedProperty() { // Logical: property.obj.Count > 3 var pred = CompileCondition("property.obj.Count > 3"); var exchange = CreateExchange("body"); exchange.Properties["obj"] = new { Count = 5 }; pred(exchange).Should().BeTrue(); } [Fact] public void Condition_NestedPropertyWithNestedPropertyFalse() { var pred = CompileCondition("property.obj.Count > 10"); var exchange = CreateExchange("body"); exchange.Properties["obj"] = new { Count = 5 }; pred(exchange).Should().BeFalse(); } #endregion #region Value expressions — arithmetic [Fact] public void ValueExpression_Subtraction() { var expr = ExpressionResolver.GetCompiledValueExpression("property.a - property.b"); var exchange = CreateExchange("body"); exchange.Properties["a"] = 20; exchange.Properties["b"] = 7; Convert.ToInt32(expr(exchange)).Should().Be(13); } [Fact] public void ValueExpression_Division() { var expr = ExpressionResolver.GetCompiledValueExpression("property.x / 2"); var exchange = CreateExchange("body"); exchange.Properties["x"] = 10; Convert.ToInt32(expr(exchange)).Should().Be(5); } [Fact] public void ValueExpression_OperatorPrecedence_MulBeforeAdd() { // a + b * c should be a + (b * c) = 2 + 3*4 = 14 var expr = ExpressionResolver.GetCompiledValueExpression("property.a + property.b * property.c"); var exchange = CreateExchange("body"); exchange.Properties["a"] = 2; exchange.Properties["b"] = 3; exchange.Properties["c"] = 4; Convert.ToInt32(expr(exchange)).Should().Be(14); } [Fact] public void ValueExpression_Parentheses_OverridePrecedence() { // (a + b) * c = (2 + 3) * 4 = 20 var expr = ExpressionResolver.GetCompiledValueExpression("(property.a + property.b) * property.c"); var exchange = CreateExchange("body"); exchange.Properties["a"] = 2; exchange.Properties["b"] = 3; exchange.Properties["c"] = 4; Convert.ToInt32(expr(exchange)).Should().Be(20); } [Fact] public void ValueExpression_StringConcatenation() { var expr = ExpressionResolver.GetCompiledValueExpression("'hello' + ' ' + 'world'"); var exchange = CreateExchange("body"); expr(exchange)?.ToString().Should().Be("hello world"); } [Fact] public void ValueExpression_StringRepetition() { var expr = ExpressionResolver.GetCompiledValueExpression("'ab' * 3"); var exchange = CreateExchange("body"); expr(exchange)?.ToString().Should().Be("ababab"); } #endregion // ═══════════════════════════════════════════════════ // 4. UNARY OPERATORS // ═══════════════════════════════════════════════════ #region Unary operators [Fact] public void ValueExpression_UnaryNot() { var expr = ExpressionResolver.GetCompiledValueExpression("!property.flag"); var exchange = CreateExchange("body"); exchange.Properties["flag"] = true; expr(exchange).Should().Be(false); } [Fact] public void ValueExpression_UnaryMinus() { var expr = ExpressionResolver.GetCompiledValueExpression("-property.val"); var exchange = CreateExchange("body"); exchange.Properties["val"] = 42; Convert.ToDouble(expr(exchange)).Should().Be(-42); } [Fact] public void ValueExpression_UnaryPlus() { var expr = ExpressionResolver.GetCompiledValueExpression("+property.val"); var exchange = CreateExchange("body"); exchange.Properties["val"] = 42; Convert.ToDouble(expr(exchange)).Should().Be(42); } #endregion // ═══════════════════════════════════════════════════ // 5. INCREMENT / DECREMENT (AST pipeline) // ═══════════════════════════════════════════════════ #region Increment / Decrement [Fact] public void ValueExpression_PrefixIncrement_ReturnsNewValue() { var expr = ExpressionResolver.GetCompiledValueExpression("++property.counter"); var exchange = CreateExchange("body"); exchange.Properties["counter"] = 5; var result = expr(exchange); Convert.ToInt32(result).Should().Be(6); Convert.ToInt32(exchange.Properties["counter"]).Should().Be(6); } [Fact] public void ValueExpression_PrefixDecrement_ReturnsNewValue() { var expr = ExpressionResolver.GetCompiledValueExpression("--property.counter"); var exchange = CreateExchange("body"); exchange.Properties["counter"] = 5; var result = expr(exchange); Convert.ToInt32(result).Should().Be(4); Convert.ToInt32(exchange.Properties["counter"]).Should().Be(4); } [Fact] public void ValueExpression_PostfixIncrement_ReturnsOldValue() { var expr = ExpressionResolver.GetCompiledValueExpression("property.counter++"); var exchange = CreateExchange("body"); exchange.Properties["counter"] = 5; var result = expr(exchange); Convert.ToInt32(result).Should().Be(5); // old value Convert.ToInt32(exchange.Properties["counter"]).Should().Be(6); // mutated } [Fact] public void ValueExpression_PostfixDecrement_ReturnsOldValue() { var expr = ExpressionResolver.GetCompiledValueExpression("property.counter--"); var exchange = CreateExchange("body"); exchange.Properties["counter"] = 5; var result = expr(exchange); Convert.ToInt32(result).Should().Be(5); // old value Convert.ToInt32(exchange.Properties["counter"]).Should().Be(4); // mutated } [Fact] public void ValueExpression_PrefixIncrement_NullInitializesToZero() { var expr = ExpressionResolver.GetCompiledValueExpression("++property.counter"); var exchange = CreateExchange("body"); // counter is not set → should auto-init to 0, then increment to 1 var result = expr(exchange); Convert.ToInt32(result).Should().Be(1); Convert.ToInt32(exchange.Properties["counter"]).Should().Be(1); } [Fact] public void ValueExpression_PrefixIncrement_Header() { var expr = ExpressionResolver.GetCompiledValueExpression("++header.retryCount"); var exchange = CreateExchange("body"); exchange.In.Headers["retryCount"] = 2; var result = expr(exchange); Convert.ToInt32(result).Should().Be(3); Convert.ToInt32(exchange.In.Headers["retryCount"]).Should().Be(3); } #endregion // ═══════════════════════════════════════════════════ // 6. STRING METHODS (via ResolveExpression runtime) // ═══════════════════════════════════════════════════ #region String methods [Fact] public void ResolveExpression_StringContains_True() { var exchange = CreateExchange("body"); exchange.Properties["text"] = "Hello World"; var result = ExpressionResolver.ResolveExpression("property.text.contains('World')", exchange); result.Should().Be(true); } [Fact] public void ResolveExpression_StringContains_False() { var exchange = CreateExchange("body"); exchange.Properties["text"] = "Hello World"; var result = ExpressionResolver.ResolveExpression("property.text.contains('Goodbye')", exchange); result.Should().Be(false); } [Fact] public void ResolveExpression_StringToUpper() { var exchange = CreateExchange("body"); exchange.Properties["text"] = "hello"; var result = ExpressionResolver.ResolveExpression("property.text.toUpper()", exchange); result?.ToString().Should().Be("HELLO"); } [Fact] public void ResolveExpression_StringToLower() { var exchange = CreateExchange("body"); exchange.Properties["text"] = "HELLO"; var result = ExpressionResolver.ResolveExpression("property.text.toLower()", exchange); result?.ToString().Should().Be("hello"); } [Fact] public void ResolveExpression_StringTrim() { var exchange = CreateExchange("body"); exchange.Properties["text"] = " hello "; var result = ExpressionResolver.ResolveExpression("property.text.trim()", exchange); result?.ToString().Should().Be("hello"); } [Fact] public void ResolveExpression_StringReplace() { var exchange = CreateExchange("body"); exchange.Properties["text"] = "Hello World"; var result = ExpressionResolver.ResolveExpression("property.text.replace('World', 'Universe')", exchange); result?.ToString().Should().Be("Hello Universe"); } [Fact] public void ResolveExpression_StringStartsWith_True() { var exchange = CreateExchange("body"); exchange.Properties["text"] = "Hello World"; var result = ExpressionResolver.ResolveExpression("property.text.startsWith('Hello')", exchange); result.Should().Be(true); } [Fact] public void ResolveExpression_StringEndsWith_True() { var exchange = CreateExchange("body"); exchange.Properties["text"] = "Hello World"; var result = ExpressionResolver.ResolveExpression("property.text.endsWith('World')", exchange); result.Should().Be(true); } [Fact] public void ResolveExpression_StringIndexOf() { var exchange = CreateExchange("body"); exchange.Properties["text"] = "Hello World"; var result = ExpressionResolver.ResolveExpression("property.text.indexOf('World')", exchange); Convert.ToInt32(result).Should().Be(6); } [Fact] public void ResolveExpression_StringLength() { var exchange = CreateExchange("body"); exchange.Properties["text"] = "Hello"; var result = ExpressionResolver.ResolveExpression("property.text.length()", exchange); Convert.ToInt32(result).Should().Be(5); } [Fact] public void ResolveExpression_StringSubstring_OneArg() { var exchange = CreateExchange("body"); exchange.Properties["text"] = "Hello World"; var result = ExpressionResolver.ResolveExpression("property.text.substring(6)", exchange); result?.ToString().Should().Be("World"); } [Fact] public void ResolveExpression_StringSubstring_TwoArgs() { var exchange = CreateExchange("body"); exchange.Properties["text"] = "Hello World"; var result = ExpressionResolver.ResolveExpression("property.text.substring(0, 5)", exchange); result?.ToString().Should().Be("Hello"); } [Fact] public void ResolveExpression_CollectionContains_True() { var exchange = CreateExchange("body"); exchange.Properties["list"] = new List { "a", "b", "c" }; var result = ExpressionResolver.ResolveExpression("property.list.contains('b')", exchange); result.Should().Be(true); } [Fact] public void ResolveExpression_CollectionLength() { var exchange = CreateExchange("body"); exchange.Properties["list"] = new List { 1, 2, 3, 4, 5 }; var result = ExpressionResolver.ResolveExpression("property.list.length()", exchange); Convert.ToInt32(result).Should().Be(5); } #endregion // ═══════════════════════════════════════════════════ // 7. TYPE CONVERSION / COERCION // ═══════════════════════════════════════════════════ #region Type conversion [Fact] public void ParseLiteral_Null() { ExpressionResolver.ParseLiteral("null").Should().BeNull(); } [Fact] public void ParseLiteral_SingleQuotedString() { ExpressionResolver.ParseLiteral("'hello'").Should().Be("hello"); } [Fact] public void ParseLiteral_DoubleQuotedString() { ExpressionResolver.ParseLiteral("\"world\"").Should().Be("world"); } [Fact] public void ParseLiteral_Integer() { ExpressionResolver.ParseLiteral("42").Should().Be(42); } [Fact] public void ParseLiteral_Double() { var result = ExpressionResolver.ParseLiteral("3.14"); Convert.ToDouble(result).Should().BeApproximately(3.14, 0.001); } [Fact] public void ParseLiteral_BoolTrue() { ExpressionResolver.ParseLiteral("true").Should().Be(true); } [Fact] public void ParseLiteral_BoolFalse() { ExpressionResolver.ParseLiteral("false").Should().Be(false); } [Fact] public void TryConvertToBool_NullIsFalse() { ExpressionResolver.TryConvertToBool(null, out var result).Should().BeTrue(); result.Should().BeFalse(); } [Fact] public void TryConvertToBool_BoolPassthrough() { ExpressionResolver.TryConvertToBool(true, out var result).Should().BeTrue(); result.Should().BeTrue(); } [Fact] public void TryConvertToBool_StringTrue() { ExpressionResolver.TryConvertToBool("true", out var result).Should().BeTrue(); result.Should().BeTrue(); } [Fact] public void TryConvertToBool_StringYes() { ExpressionResolver.TryConvertToBool("yes", out var result).Should().BeTrue(); result.Should().BeTrue(); } [Fact] public void TryConvertToBool_StringNo() { ExpressionResolver.TryConvertToBool("no", out var result).Should().BeTrue(); result.Should().BeFalse(); } [Fact] public void TryConvertToBool_Int_NonZeroIsTrue() { ExpressionResolver.TryConvertToBool(1, out var result).Should().BeTrue(); result.Should().BeTrue(); } [Fact] public void TryConvertToBool_Int_ZeroIsFalse() { ExpressionResolver.TryConvertToBool(0, out var result).Should().BeTrue(); result.Should().BeFalse(); } [Fact] public void TryConvertToBool_LocaleWords_AreNotSpecial() { // The boolean word set is English-only by design: a routing language must not change // meaning with the author's locale. A foreign word for "no" is an ordinary non-empty // string, which the truthiness rule reads as true. (Until 2026-08-28 a few localized // words were recognised; the removal is recorded in the changelog.) ExpressionResolver.TryConvertToBool("nein", out var result).Should().BeTrue(); result.Should().BeTrue("a non-empty string that is not a boolean word is truthy"); } #endregion // ═══════════════════════════════════════════════════ // 8. RUNTIME RESOLVERS — ResolveExpression // ═══════════════════════════════════════════════════ #region ResolveExpression [Fact] public void ResolveExpression_PropertyAccess() { var exchange = CreateExchange("body"); exchange.Properties["name"] = "Alice"; var result = ExpressionResolver.ResolveExpression("property.name", exchange); result?.ToString().Should().Be("Alice"); } [Fact] public void ResolveExpression_HeaderAccess() { var exchange = CreateExchange("body"); exchange.In.Headers["ContentType"] = "text/plain"; var result = ExpressionResolver.ResolveExpression("header.ContentType", exchange); result?.ToString().Should().Be("text/plain"); } [Fact] public void ResolveExpression_BodyAccess() { var exchange = CreateExchange("hello world"); var result = ExpressionResolver.ResolveExpression("body", exchange); result?.ToString().Should().Be("hello world"); } [Fact] public void ResolveExpression_PrefixIncrement() { var exchange = CreateExchange("body"); exchange.Properties["counter"] = 10; var result = ExpressionResolver.ResolveExpression("++property.counter", exchange); Convert.ToInt32(result).Should().Be(11); Convert.ToInt32(exchange.Properties["counter"]).Should().Be(11); } [Fact] public void ResolveExpression_PostfixIncrement() { var exchange = CreateExchange("body"); exchange.Properties["counter"] = 10; var result = ExpressionResolver.ResolveExpression("property.counter++", exchange); Convert.ToInt32(result).Should().Be(10); // old value Convert.ToInt32(exchange.Properties["counter"]).Should().Be(11); // mutated } [Fact] public void ResolveExpression_PrefixDecrement() { var exchange = CreateExchange("body"); exchange.Properties["counter"] = 10; var result = ExpressionResolver.ResolveExpression("--property.counter", exchange); Convert.ToInt32(result).Should().Be(9); Convert.ToInt32(exchange.Properties["counter"]).Should().Be(9); } [Fact] public void ResolveExpression_PostfixDecrement() { var exchange = CreateExchange("body"); exchange.Properties["counter"] = 10; var result = ExpressionResolver.ResolveExpression("property.counter--", exchange); Convert.ToInt32(result).Should().Be(10); // old value Convert.ToInt32(exchange.Properties["counter"]).Should().Be(9); // mutated } [Fact] public void ResolveExpression_LogicalExpression() { var exchange = CreateExchange("body"); exchange.Properties["x"] = 10; var result = ExpressionResolver.ResolveExpression("property.x > 5", exchange); result.Should().Be(true); } [Fact] public void ResolveExpression_UnaryMinus() { var exchange = CreateExchange("body"); exchange.Properties["val"] = 42; var result = ExpressionResolver.ResolveExpression("-property.val", exchange); Convert.ToDouble(result).Should().Be(-42); } [Fact] public void ResolveExpression_UnaryNot() { var exchange = CreateExchange("body"); exchange.Properties["flag"] = true; var result = ExpressionResolver.ResolveExpression("!property.flag", exchange); result.Should().Be(false); } [Fact] public void ResolveExpression_EmptyString_ReturnsNull() { var exchange = CreateExchange("body"); ExpressionResolver.ResolveExpression("", exchange).Should().BeNull(); } [Fact] public void ResolveExpression_NullString_ReturnsNull() { var exchange = CreateExchange("body"); ExpressionResolver.ResolveExpression(null!, exchange).Should().BeNull(); } [Fact] public void ResolveExpression_TemplateInsideResolve() { var exchange = CreateExchange("body"); exchange.In.Headers["name"] = "Bob"; var result = ExpressionResolver.ResolveExpression("${header.name}", exchange); result?.ToString().Should().Be("Bob"); } #endregion // ═══════════════════════════════════════════════════ // 9. EDGE CASES & ERROR HANDLING // ═══════════════════════════════════════════════════ #region Edge cases [Fact] public void Addition_Null_Plus_Value_ReturnsValue() { var expr = ExpressionResolver.GetCompiledValueExpression("property.a + property.b"); var exchange = CreateExchange("body"); // a is not set (null), b = 10 exchange.Properties["b"] = 10; var result = expr(exchange); Convert.ToInt32(result).Should().Be(10); } [Fact] public void Multiplication_Null_Times_Value_ReturnsNull() { var expr = ExpressionResolver.GetCompiledValueExpression("property.a * property.b"); var exchange = CreateExchange("body"); // a is not set (null), b = 10 exchange.Properties["b"] = 10; expr(exchange).Should().BeNull(); } [Fact] public void Division_ByZero_ReturnsNull() { var expr = ExpressionResolver.GetCompiledValueExpression("property.a / property.b"); var exchange = CreateExchange("body"); exchange.Properties["a"] = 10; exchange.Properties["b"] = 0; expr(exchange).Should().BeNull(); } [Fact] public void Condition_BothNulls_AreEqual() { var exchange = CreateExchange("body"); // Neither property.a nor property.b is set → both null EvaluateCondition("property.a == property.b", exchange) .Should().BeTrue(); } [Fact] public void Condition_NullVsNonNull_NotEqual() { var exchange = CreateExchange("body"); exchange.Properties["b"] = "value"; EvaluateCondition("property.a != property.b", exchange) .Should().BeTrue(); } [Fact] public void ValueExpression_MissingProperty_ReturnsNull() { var expr = ExpressionResolver.GetCompiledValueExpression("property.nonexistent"); var exchange = CreateExchange("body"); expr(exchange).Should().BeNull(); } [Fact] public void ProcessTemplate_NullExchange_Throws() { var act = () => ExpressionResolver.ProcessTemplate("hello", null!); act.Should().Throw(); } [Fact] public void Condition_EmptyString_Throws() { var exchange = CreateExchange("body"); var act = () => EvaluateCondition("", exchange); act.Should().Throw(); } [Fact] public void Subtraction_Null_Minus_Value_ReturnsNull() { var expr = ExpressionResolver.GetCompiledValueExpression("property.a - property.b"); var exchange = CreateExchange("body"); exchange.Properties["b"] = 5; // a is null → subtraction returns left (null) expr(exchange).Should().BeNull(); } [Fact] public void Condition_MixedType_StringVsInt() { var exchange = CreateExchange("body"); exchange.Properties["val"] = "10"; // "10" == 10 should compare numerically EvaluateCondition("property.val == 10", exchange) .Should().BeTrue(); } #endregion // ═══════════════════════════════════════════════════ // 10. CACHING // ═══════════════════════════════════════════════════ #region Caching [Fact] public void ClearTemplateCache_WorksIndependently() { ExpressionResolver.ClearAllCaches(); ExpressionResolver.GetCompiledTemplate("test ${body}"); ExpressionResolver.GetCompiledValueExpression("property.independent"); ExpressionResolver.ClearTemplateCache(); var stats = ExpressionResolver.GetCacheStatistics(); stats.TemplateCount.Should().Be(0); stats.ValueExpressionCount.Should().BeGreaterThanOrEqualTo(1); } [Fact] public void ClearValueExpressionCache_WorksIndependently() { ExpressionResolver.ClearAllCaches(); ExpressionResolver.GetCompiledValueExpression("property.x"); ExpressionResolver.GetCompiledTemplate("test ${body}"); ExpressionResolver.ClearValueExpressionCache(); var stats = ExpressionResolver.GetCacheStatistics(); stats.ValueExpressionCount.Should().Be(0); stats.TemplateCount.Should().BeGreaterThanOrEqualTo(1); } [Fact] public void CacheStatistics_TrackHitsAndMisses() { ExpressionResolver.ClearAllCaches(); var template = "cache-test ${body}"; // First call = miss, second call = hit ExpressionResolver.GetCompiledTemplate(template); ExpressionResolver.GetCompiledTemplate(template); var stats = ExpressionResolver.GetCacheStatistics(); stats.TemplateMisses.Should().BeGreaterThanOrEqualTo(1); stats.TemplateHits.Should().BeGreaterThanOrEqualTo(1); } [Fact] public void ValueExpressionCache_SeparatesAstFromRegular() { ExpressionResolver.ClearAllCaches(); // Regular expression goes into cache with key "property.x" ExpressionResolver.GetCompiledValueExpression("property.x"); // AST expression goes into cache with key "ast:property.x" ExpressionResolver.GetCompiledValueExpressionWithAst("property.x"); var stats = ExpressionResolver.GetCacheStatistics(); stats.ValueExpressionCount.Should().BeGreaterThanOrEqualTo(2); } [Fact] public void GetCompiledTemplate_WithContextId_IsolatesCache() { ExpressionResolver.ClearAllCaches(); var template = "ctx-test ${body}"; var fn1 = ExpressionResolver.GetCompiledTemplate(template, "ctx-A"); var fn2 = ExpressionResolver.GetCompiledTemplate(template, "ctx-B"); var fn3 = ExpressionResolver.GetCompiledTemplate(template); // global (no context) // All three should be in the cache as separate entries var stats = ExpressionResolver.GetCacheStatistics(); stats.TemplateCount.Should().BeGreaterThanOrEqualTo(3); } [Fact] public void ClearCachesForContext_RemovesOnlyScopedEntries() { ExpressionResolver.ClearAllCaches(); // Populate caches with different contexts — capture references var t1 = ExpressionResolver.GetCompiledTemplate("clear-ctx-t1 ${body}", "ctx-1"); var t2 = ExpressionResolver.GetCompiledTemplate("clear-ctx-t2 ${body}", "ctx-2"); var t3 = ExpressionResolver.GetCompiledTemplate("clear-ctx-t3 ${body}"); // global var v1 = ExpressionResolver.GetCompiledValueExpression("property.x", "ctx-1"); var v2 = ExpressionResolver.GetCompiledValueExpression("property.y", "ctx-2"); // Clear only ctx-1 ExpressionResolver.ClearCachesForContext("ctx-1"); // ctx-1 entries should be evicted — re-fetch gives new instances ExpressionResolver.GetCompiledTemplate("clear-ctx-t1 ${body}", "ctx-1") .Should().NotBeSameAs(t1, "ctx-1 template should have been evicted"); ExpressionResolver.GetCompiledValueExpression("property.x", "ctx-1") .Should().NotBeSameAs(v1, "ctx-1 value expression should have been evicted"); // ctx-2 and global entries should still be cached (same references) ExpressionResolver.GetCompiledTemplate("clear-ctx-t2 ${body}", "ctx-2") .Should().BeSameAs(t2, "ctx-2 template should still be cached"); ExpressionResolver.GetCompiledTemplate("clear-ctx-t3 ${body}") .Should().BeSameAs(t3, "global template should still be cached"); ExpressionResolver.GetCompiledValueExpression("property.y", "ctx-2") .Should().BeSameAs(v2, "ctx-2 value expression should still be cached"); } [Fact] public void ProcessTemplate_UsesExchangeRouteId_ForCacheIsolation() { ExpressionResolver.ClearAllCaches(); var exchange1 = CreateExchange("hello"); exchange1.RouteId = "route-alpha"; var exchange2 = CreateExchange("world"); exchange2.RouteId = "route-beta"; // Process same template with different route IDs ExpressionResolver.ProcessTemplate("${body}", exchange1); ExpressionResolver.ProcessTemplate("${body}", exchange2); // Should have 2 separate cache entries var stats = ExpressionResolver.GetCacheStatistics(); stats.TemplateCount.Should().BeGreaterThanOrEqualTo(2); // Clear only route-alpha ExpressionResolver.ClearCachesForContext("route-alpha"); stats = ExpressionResolver.GetCacheStatistics(); stats.TemplateCount.Should().BeGreaterThanOrEqualTo(1); } [Fact] public void ProcessTemplate_WithNullRouteId_UsesGlobalCache() { ExpressionResolver.ClearAllCaches(); var exchange = CreateExchange("test"); // RouteId is null by default exchange.RouteId.Should().BeNull(); ExpressionResolver.ProcessTemplate("${body}", exchange); ExpressionResolver.ProcessTemplate("${body}", exchange); // should hit cache var stats = ExpressionResolver.GetCacheStatistics(); stats.TemplateCount.Should().Be(1); stats.TemplateHits.Should().BeGreaterThanOrEqualTo(1); } #endregion // ═══════════════════════════════════════════════════ // 11. COMPILED LOGICAL PREDICATE // ═══════════════════════════════════════════════════ #region Compiled predicates [Fact] public void CompileLogicalPredicate_ComplexExpression() { var pred = CompileCondition( "property.status == 'active' AND property.count > 0"); var ex1 = CreateExchange("body"); ex1.Properties["status"] = "active"; ex1.Properties["count"] = 5; pred(ex1).Should().BeTrue(); var ex2 = CreateExchange("body"); ex2.Properties["status"] = "active"; ex2.Properties["count"] = 0; pred(ex2).Should().BeFalse(); var ex3 = CreateExchange("body"); ex3.Properties["status"] = "inactive"; ex3.Properties["count"] = 5; pred(ex3).Should().BeFalse(); } [Fact] public void CompileLogicalPredicate_HeaderComparison() { var pred = CompileCondition("header.status == 200"); var ex1 = CreateExchange("body"); ex1.In.Headers["status"] = 200; pred(ex1).Should().BeTrue(); var ex2 = CreateExchange("body"); ex2.In.Headers["status"] = 404; pred(ex2).Should().BeFalse(); } #endregion // ═══════════════════════════════════════════════════ // 12. COMPILED TEMPLATE — GetCompiledTemplate // ═══════════════════════════════════════════════════ #region Compiled template delegates [Fact] public void GetCompiledTemplate_ReusableAcrossDifferentExchanges() { var template = ExpressionResolver.GetCompiledTemplate("Hello, ${header.name}!"); var ex1 = CreateExchange("body"); ex1.In.Headers["name"] = "Alice"; template(ex1).Should().Be("Hello, Alice!"); var ex2 = CreateExchange("body"); ex2.In.Headers["name"] = "Bob"; template(ex2).Should().Be("Hello, Bob!"); } [Fact] public void GetCompiledTemplate_WithProperty() { var template = ExpressionResolver.GetCompiledTemplate("User: ${property.userId}"); var exchange = CreateExchange("body"); exchange.Properties["userId"] = "u-42"; template(exchange).Should().Be("User: u-42"); } #endregion // ═══════════════════════════════════════════════════ // 13. RESOLVE EXPRESSION — FULL CHAIN // ═══════════════════════════════════════════════════ #region ResolveExpression full chain [Fact] public void ResolveExpression_NOT_Expression() { var exchange = CreateExchange("body"); exchange.Properties["flag"] = true; var result = ExpressionResolver.ResolveExpression("NOT property.flag", exchange); result.Should().Be(false); } [Fact] public void ResolveExpression_AND_Expression() { var exchange = CreateExchange("body"); exchange.Properties["a"] = 10; exchange.Properties["b"] = 20; var result = ExpressionResolver.ResolveExpression("property.a > 5 AND property.b > 15", exchange); result.Should().Be(true); } [Fact] public void ResolveExpression_DefaultProperty_FallsThrough() { var exchange = CreateExchange("body"); exchange.Properties["custom"] = "value"; // Expression without prefix → default property lookup var result = ExpressionResolver.ResolveExpression("custom", exchange); result?.ToString().Should().Be("value"); } #endregion #region Dictionary body index access [Fact] public void ProcessTemplate_BodyDictIndexAccess_ResolvesValues() { var dict = new Dictionary(StringComparer.OrdinalIgnoreCase) { ["id"] = 42, ["message"] = "hello world", ["status"] = "active" }; var exchange = CreateExchange(dict); var result = ExpressionResolver.ProcessTemplate( "id=${body['id']}, msg=${body['message']}, status=${body['status']}", exchange); result.Should().Be("id=42, msg=hello world, status=active"); } [Fact] public void ProcessTemplate_BodyDictIndexAccess_NullableObjectDict() { // Matches what SQL component returns: Dictionary var dict = new Dictionary(StringComparer.OrdinalIgnoreCase) { ["id"] = 1, ["name"] = "test", ["value"] = null }; var exchange = CreateExchange(dict); ExpressionResolver.ProcessTemplate("${body['id']}", exchange).Should().Be("1"); ExpressionResolver.ProcessTemplate("${body['name']}", exchange).Should().Be("test"); ExpressionResolver.ProcessTemplate("${body['value']}", exchange).Should().BeEmpty(); } #endregion } Path: redb-route/tests/redb.Route.Tests/Expressions/ExpressionResolverTests.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/Expressions/ExpressionResolverTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Expressions; using redb.Route.Predicates; namespace redb.Route.Tests.Expressions; /// /// Tests for ExpressionResolver — compiled template processing, /// logical expressions, value expressions, and caching. /// [Collection("ExpressionResolver")] public class ExpressionResolverTests : IDisposable { public ExpressionResolverTests() { ExpressionResolver.ClearAllCaches(); } public void Dispose() { ExpressionResolver.ClearAllCaches(); } // The hand-written logical branch was removed on 2026-08-28 - one language, one parser. // The semantic tests below migrated to the surviving condition path via these helpers. private static bool EvaluateCondition(string condition, IExchange exchange) => PredicateFactory.FromString(condition).Matches(exchange); private static Func CompileCondition(string condition) => PredicateFactory.FromString(condition).Matches; private static IExchange CreateExchange(object? body = null) => new Exchange(new Message(body)); // ── Template processing ── [Fact] public void ProcessTemplate_PlainText_ReturnsUnchanged() { var exchange = CreateExchange("body"); var result = ExpressionResolver.ProcessTemplate("Hello World", exchange); result.Should().Be("Hello World"); } [Fact] public void ProcessTemplate_BodyExpression() { var exchange = CreateExchange("MyBody"); var result = ExpressionResolver.ProcessTemplate("Body is: ${body}", exchange); result.Should().Be("Body is: MyBody"); } [Fact] public void ProcessTemplate_HeaderExpression() { var exchange = CreateExchange("body"); exchange.In.Headers["correlationId"] = "abc-123"; var result = ExpressionResolver.ProcessTemplate("ID: ${header.correlationId}", exchange); result.Should().Be("ID: abc-123"); } [Fact] public void ProcessTemplate_PropertyExpression() { var exchange = CreateExchange("body"); exchange.Properties["userId"] = "user42"; var result = ExpressionResolver.ProcessTemplate("User: ${property.userId}", exchange); result.Should().Be("User: user42"); } [Fact] public void ProcessTemplate_ContentTypeExpression() { var exchange = CreateExchange("body"); exchange.In.ContentType = "application/json"; var result = ExpressionResolver.ProcessTemplate("CT: ${contentType}", exchange); result.Should().Be("CT: application/json"); } [Fact] public void ProcessTemplate_ContentTypeExpression_NullReturnsEmpty() { var exchange = CreateExchange("body"); exchange.In.ContentType = null; var result = ExpressionResolver.ProcessTemplate("CT: ${contentType}", exchange); result.Should().Be("CT: "); } [Fact] public void ProcessTemplate_MultipleExpressions() { var exchange = CreateExchange("payload"); exchange.In.Headers["type"] = "request"; exchange.Properties["id"] = 42; var result = ExpressionResolver.ProcessTemplate( "${header.type}: ${body} [${property.id}]", exchange); result.Should().Be("request: payload [42]"); } // ── Condition strings (migrated from the removed logical branch) ── [Fact] public void Condition_SimpleEquality_True() { var exchange = CreateExchange("body"); exchange.Properties["status"] = "active"; var result = EvaluateCondition( "property.status == 'active'", exchange); result.Should().BeTrue(); } [Fact] public void Condition_SimpleEquality_False() { var exchange = CreateExchange("body"); exchange.Properties["status"] = "inactive"; var result = EvaluateCondition( "property.status == 'active'", exchange); result.Should().BeFalse(); } [Fact] public void Condition_ContentTypeEquality() { var exchange = CreateExchange("body"); exchange.In.ContentType = "application/json"; var result = EvaluateCondition( "contentType == 'application/json'", exchange); result.Should().BeTrue(); } [Fact] public void Condition_NumericComparison() { var exchange = CreateExchange("body"); exchange.Properties["count"] = 10; var result = EvaluateCondition( "property.count > 5", exchange); result.Should().BeTrue(); } [Fact] public void Condition_AndOperator() { var exchange = CreateExchange("body"); exchange.Properties["a"] = 10; exchange.Properties["b"] = 20; var result = EvaluateCondition( "property.a > 5 AND property.b > 15", exchange); result.Should().BeTrue(); } [Fact] public void Condition_OrOperator() { var exchange = CreateExchange("body"); exchange.Properties["a"] = 3; exchange.Properties["b"] = 20; var result = EvaluateCondition( "property.a > 5 OR property.b > 15", exchange); result.Should().BeTrue(); } [Fact] public void Condition_NotOperator() { var exchange = CreateExchange("body"); exchange.Properties["flag"] = false; var result = EvaluateCondition( "NOT property.flag", exchange); result.Should().BeTrue(); } // ── Value expressions ── [Fact] public void GetCompiledValueExpression_PropertyAccess() { var expr = ExpressionResolver.GetCompiledValueExpression("property.name"); var exchange = CreateExchange("body"); exchange.Properties["name"] = "TestValue"; expr(exchange).Should().Be("TestValue"); } [Fact] public void GetCompiledValueExpression_BodyAccess() { var expr = ExpressionResolver.GetCompiledValueExpression("body"); var exchange = CreateExchange("hello world"); expr(exchange)?.ToString().Should().Be("hello world"); } [Fact] public void GetCompiledValueExpression_HeaderAccess() { var expr = ExpressionResolver.GetCompiledValueExpression("header.ContentType"); var exchange = CreateExchange("body"); exchange.In.Headers["ContentType"] = "text/plain"; expr(exchange).Should().Be("text/plain"); } [Fact] public void GetCompiledValueExpression_Literal() { var expr = ExpressionResolver.GetCompiledValueExpression("42"); var exchange = CreateExchange("body"); Convert.ToInt32(expr(exchange)).Should().Be(42); } [Fact] public void GetCompiledValueExpression_StringLiteral() { var expr = ExpressionResolver.GetCompiledValueExpression("'hello'"); var exchange = CreateExchange("body"); expr(exchange).Should().Be("hello"); } // ── Arithmetic expressions ── [Fact] public void GetCompiledValueExpression_Addition() { var expr = ExpressionResolver.GetCompiledValueExpression("property.a + property.b"); var exchange = CreateExchange("body"); exchange.Properties["a"] = 10; exchange.Properties["b"] = 20; Convert.ToInt32(expr(exchange)).Should().Be(30); } [Fact] public void GetCompiledValueExpression_Multiplication() { var expr = ExpressionResolver.GetCompiledValueExpression("property.x * 3"); var exchange = CreateExchange("body"); exchange.Properties["x"] = 7; Convert.ToInt32(expr(exchange)).Should().Be(21); } // ── Compiled template caching ── [Fact] public void GetCompiledTemplate_CachesResult() { var template = "Hello ${body}"; var compiled1 = ExpressionResolver.GetCompiledTemplate(template); var compiled2 = ExpressionResolver.GetCompiledTemplate(template); compiled1.Should().BeSameAs(compiled2); } [Fact] public void GetCacheStatistics_ReportsCorrectCounts() { ExpressionResolver.ClearAllCaches(); ExpressionResolver.GetCompiledTemplate("test ${body}"); ExpressionResolver.GetCompiledValueExpression("property.x"); var stats = ExpressionResolver.GetCacheStatistics(); stats.TemplateCount.Should().BeGreaterThanOrEqualTo(1); stats.ValueExpressionCount.Should().BeGreaterThanOrEqualTo(1); } /// /// Proved per entry, by delegate identity, not by the size of the cache: the caches are process /// state, and a route test in another collection compiles a template between the clear and any /// count we could read, so "the cache is empty" is not observable here. The text is unique to this /// test, so nobody else can put it back — whatever else the process is doing, a hit on it after a /// clear is impossible. /// [Fact] public void ClearAllCaches_DropsWhatWasCached() { var unique = Guid.NewGuid().ToString("N"); var template = $"clear-probe-{unique} ${{body}}"; var value = $"property.clear_probe_{unique} + 1"; var compiledTemplate = ExpressionResolver.GetCompiledTemplate(template); var compiledValue = ExpressionResolver.GetCompiledValueExpression(value); ExpressionResolver.GetCompiledTemplate(template).Should().BeSameAs(compiledTemplate, "the template entry is cached before the clear"); ExpressionResolver.GetCompiledValueExpression(value).Should().BeSameAs(compiledValue, "the value entry is cached before the clear"); ExpressionResolver.ClearAllCaches(); // Both caches, not just the template one: "all" is the claim under test. ExpressionResolver.GetCompiledTemplate(template).Should().NotBeSameAs(compiledTemplate, "the clear dropped the template entry, so it is compiled afresh"); ExpressionResolver.GetCompiledValueExpression(value).Should().NotBeSameAs(compiledValue, "the clear dropped the value entry too"); } // ── CompileCondition ── [Fact] public void CompileCondition_ReturnsReusableDelegate() { var pred = CompileCondition("property.val > 5"); var ex1 = CreateExchange("body"); ex1.Properties["val"] = 10; pred(ex1).Should().BeTrue(); var ex2 = CreateExchange("body"); ex2.Properties["val"] = 3; pred(ex2).Should().BeFalse(); } // ── Exception expression ── [Fact] public void ProcessTemplate_ExceptionMessage() { var exchange = CreateExchange("body"); exchange.Exception = new InvalidOperationException("Something went wrong"); var result = ExpressionResolver.ProcessTemplate("Error: ${exception.Message}", exchange); result.Should().Be("Error: Something went wrong"); } [Fact] public void ProcessTemplate_ExceptionNull_ReturnsEmpty() { var exchange = CreateExchange("body"); var result = ExpressionResolver.ProcessTemplate("Error: ${exception.Message}", exchange); result.Should().Be("Error: "); } } Path: redb-route/tests/redb.Route.Tests/Expressions/ExpressionSourceTests.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/Expressions/ExpressionSourceTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Expressions; using XPathExpr = redb.Route.Expressions.XPathExpression; namespace redb.Route.Tests.Expressions; /// /// A query language reads the message body by default and whatever the route names otherwise. /// /// Without a source, XML that arrived in a header has to be moved into the body before it can be /// queried — an extra step that also damages the body for the rest of the route. /// /// /// In the language the source is a second argument with the path staying first: /// xpath('/order/id', header.payload). Camel writes xpath(input,exp), source first, /// which makes the first argument mean different things at one and two arguments; we do not copy /// that, and the divergence is deliberate. /// /// [Collection("ExpressionResolver")] public class ExpressionSourceTests : IDisposable { private const string HeaderXml = "H-1yes"; private const string BodyXml = "B-1"; private const string HeaderJson = """{"id":"J-1","vip":true}"""; public ExpressionSourceTests() => ExpressionResolver.ClearAllCaches(); public void Dispose() { ExpressionResolver.ClearAllCaches(); GC.SuppressFinalize(this); } private static IExchange Exchange() { var exchange = new Exchange(new Message(BodyXml)); exchange.In.Headers["payload"] = HeaderXml; exchange.In.Headers["json"] = HeaderJson; exchange.Properties["doc"] = HeaderJson; return exchange; } // ── Object form ── [Fact] public void XPath_reads_the_named_source_instead_of_the_body() { var exchange = Exchange(); new XPathExpr("/order/id").Evaluate(exchange).Should().Be("B-1"); new XPathExpr("/order/id").From(new HeaderExpression("payload")) .Evaluate(exchange).Should().Be("H-1"); } [Fact] public void JsonPath_reads_the_named_source_instead_of_the_body() { var exchange = Exchange(); new JsonPathExpression("$.id").From(new PropertyExpression("doc")) .Evaluate(exchange).Should().Be("J-1"); } [Fact] public void Reading_a_source_leaves_the_body_alone() { var exchange = Exchange(); new XPathExpr("/order/id").From(new HeaderExpression("payload")).Evaluate(exchange); exchange.In.Body.Should().Be(BodyXml, "querying a header must not cost the route its body"); } [Fact] public void From_returns_a_new_expression_and_leaves_the_original_reading_the_body() { var onBody = new XPathExpr("/order/id"); var onHeader = onBody.From(new HeaderExpression("payload")); var exchange = Exchange(); onHeader.Evaluate(exchange).Should().Be("H-1"); onBody.Evaluate(exchange).Should().Be("B-1"); } [Fact] public void The_source_composes_with_the_result_type() { var exchange = Exchange(); new XPathExpr("/order/id", XPathResult.String).From(new HeaderExpression("payload")) .Evaluate(exchange).Should().Be("H-1"); } [Fact] public void A_condition_on_a_source_asks_the_same_question_as_on_the_body() { var exchange = Exchange(); var predicate = (IPredicateExpression)new XPathExpr("/order/vip").From(new HeaderExpression("payload")); predicate.Matches(exchange).Should().BeTrue("the header's document has a vip element"); ((IPredicateExpression)new XPathExpr("/order/vip")).Matches(exchange) .Should().BeFalse("the body's document does not"); } [Fact] public void A_source_that_produced_nothing_says_so_rather_than_blaming_the_body() { var exchange = Exchange(); var act = () => new XPathExpr("/order/id").From(new HeaderExpression("absent")) .Evaluate(exchange); act.Should().Throw() .WithMessage("*source expression produced no value*"); } // ── Language function, value position ── [Fact] public void The_language_function_takes_the_source_as_a_second_argument() { var exchange = Exchange(); ExpressionResolver.ProcessTemplate("${xpath('/order/id', header.payload)}", exchange) .Should().Be("H-1"); } [Fact] public void One_argument_still_means_the_body() { var exchange = Exchange(); ExpressionResolver.ProcessTemplate("${xpath('/order/id')}", exchange) .Should().Be("B-1"); } [Fact] public void The_jpath_function_takes_a_source_too() { var exchange = Exchange(); ExpressionResolver.ProcessTemplate("${jpath('$.id', header.json)}", exchange) .Should().Be("J-1"); } [Fact] public void The_source_argument_mixes_with_the_rest_of_the_language() { var exchange = Exchange(); ExpressionResolver.ProcessTemplate( "${upper(xpath('/order/id', header.payload))}-${xpath('/order/id')}", exchange) .Should().Be("H-1-B-1"); } [Fact] public void A_comma_inside_the_path_is_part_of_the_path_and_not_a_second_argument() { var exchange = new Exchange(new Message("ok")); // Telling one argument from two is what decides which engine reads the placeholder, so a // comma that belongs to the path must not be mistaken for an argument separator. ExpressionResolver.ProcessTemplate("${xpath(/order/line[@code='1,2'])}", exchange) .Should().Be("ok"); } [Fact] public void A_comma_inside_brackets_is_part_of_a_json_path_too() { var exchange = new Exchange(new Message("""{"a,b":"ok"}""")); ExpressionResolver.ProcessTemplate("${jpath($['a,b'])}", exchange) .Should().Be("ok"); } [Fact] public void A_missing_source_reads_like_a_missing_body_inside_the_language() { // Review follow-up. The language is lenient about missing data — one-argument xpath() on a // null body yields null — and the first cut of the two-argument form threw instead, so the // same language answered the same situation two ways depending on where the data was // missing from. Inside ${...} the two must agree; the strict contract lives on the object // form, where From(...) naming a source that produced nothing still fails loudly. var nullBody = new Exchange(new Message()); var absentHeader = Exchange(); var oneArg = ExpressionResolver.ProcessTemplate("[${xpath('/order/id')}]", nullBody); var twoArg = ExpressionResolver.ProcessTemplate("[${xpath('/order/id', header.absent)}]", absentHeader); twoArg.Should().Be(oneArg); } [Fact] public void The_jpath_function_is_equally_lenient_about_a_missing_source() { var nullBody = new Exchange(new Message()); var absentHeader = Exchange(); var oneArg = ExpressionResolver.ProcessTemplate("[${jpath($.id)}]", nullBody); var twoArg = ExpressionResolver.ProcessTemplate("[${jpath('$.id', header.absent)}]", absentHeader); twoArg.Should().Be(oneArg); } [Fact] public async Task A_condition_over_a_missing_source_is_no_match_rather_than_an_error() { var reached = new List(); await using var context = new RouteContext(); context.AddRoutes(r => r.From("direct://src-cond-absent") .Filter("xpath('/order/vip', header.absent)") .Process(_ => reached.Add("passed")) .EndFilter()); await context.Start(); var producer = context.GetEndpoint("direct://src-cond-absent").CreateProducer(); await producer.Start(); await producer.Process(Exchange()); reached.Should().BeEmpty("an optional header that is absent means the condition does not hold"); } // ── Language function, condition position ── [Fact] public async Task A_condition_written_in_the_language_reads_the_source_too() { var reached = new List(); await using var context = new RouteContext(); context.AddRoutes(r => r.From("direct://src-cond") .Filter("xpath('/order/vip', header.payload)") .Process(_ => reached.Add("header")) .EndFilter()); await context.Start(); var producer = context.GetEndpoint("direct://src-cond").CreateProducer(); await producer.Start(); var exchange = Exchange(); await producer.Process(exchange); reached.Should().Equal("header"); } [Fact] public async Task The_same_condition_without_a_source_reads_the_body_and_finds_nothing() { var reached = new List(); await using var context = new RouteContext(); context.AddRoutes(r => r.From("direct://src-cond-body") .Filter("xpath('/order/vip')") .Process(_ => reached.Add("body")) .EndFilter()); await context.Start(); var producer = context.GetEndpoint("direct://src-cond-body").CreateProducer(); await producer.Start(); await producer.Process(Exchange()); reached.Should().BeEmpty(); } } Path: redb-route/tests/redb.Route.Tests/Expressions/ExpressionTests.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/Expressions/ExpressionTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Expressions; namespace redb.Route.Tests.Expressions; /// /// Tests for the Expression hierarchy (BodyExpression, HeaderExpression, /// PropertyExpression, ConstantExpression, DelegateExpression, ExchangeExpression, /// DelegateExpression). /// public class ExpressionTests { private static IExchange CreateExchange(object? body = null) { var exchange = new Exchange(new Message(body)); return exchange; } // ── BodyExpression ── [Fact] public void BodyExpression_ReturnsBody() { var expr = new BodyExpression(); var exchange = CreateExchange("hello"); expr.Evaluate(exchange).Should().Be("hello"); } [Fact] public void BodyExpression_ReturnsTypedBody() { var expr = new BodyExpression(); var exchange = CreateExchange(42); expr.Evaluate(exchange).Should().Be(42); } [Fact] public void BodyExpression_NullBody_ReturnsDefault() { var expr = new BodyExpression(); var exchange = CreateExchange(null); expr.Evaluate(exchange).Should().BeNull(); } // ── HeaderExpression ── [Fact] public void HeaderExpression_ReturnsHeaderValue() { var expr = new HeaderExpression("ContentType"); var exchange = CreateExchange("body"); exchange.In.Headers["ContentType"] = "application/json"; expr.Evaluate(exchange).Should().Be("application/json"); } [Fact] public void HeaderExpression_MissingHeader_ReturnsDefault() { var expr = new HeaderExpression("Missing"); var exchange = CreateExchange("body"); expr.Evaluate(exchange).Should().BeNull(); } // ── PropertyExpression ── [Fact] public void PropertyExpression_ReturnsPropertyValue() { var expr = new PropertyExpression("userId"); var exchange = CreateExchange("body"); exchange.Properties["userId"] = 123; expr.Evaluate(exchange).Should().Be(123); } [Fact] public void PropertyExpression_MissingProperty_ReturnsDefault() { var expr = new PropertyExpression("missing"); var exchange = CreateExchange("body"); expr.Evaluate(exchange).Should().BeNull(); } // ── ConstantExpression ── [Fact] public void ConstantExpression_ReturnsConstantValue() { var expr = new ConstantExpression("fixed"); var exchange = CreateExchange("body"); expr.Evaluate(exchange).Should().Be("fixed"); } [Fact] public void ConstantExpression_ReturnsTypedConstant() { var expr = new ConstantExpression(42); var exchange = CreateExchange("body"); expr.Evaluate(exchange).Should().Be(42); } // ── DelegateExpression ── [Fact] public void DelegateExpression_ExecutesDelegate() { var expr = new DelegateExpression(ex => ex.In.Body?.ToString()?.ToUpper()); var exchange = CreateExchange("hello"); expr.Evaluate(exchange).Should().Be("HELLO"); } [Fact] public void DelegateExpression_WithTypedDelegate() { var expr = new DelegateExpression(ex => (int)ex.In.Body! * 2); var exchange = CreateExchange(21); expr.Evaluate(exchange).Should().Be(42); } // ── ExchangeExpression ── [Fact] public void ExchangeExpression_ReturnsEvaluatedValue() { var expr = new ExchangeExpression(ex => ex.In.Body); var exchange = CreateExchange("hello"); expr.Evaluate(exchange).Should().Be("hello"); } // LogicalExpression was dead public API (never constructed by the library) and was removed // together with the hand-written logical branch on 2026-08-28. A boolean-valued expression // is written as a condition string or via the predicate factories on IExpression. } Path: redb-route/tests/redb.Route.Tests/Expressions/ExpressionsGuideExamplesTests.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/Expressions/ExpressionsGuideExamplesTests.cs ---- using System.Runtime.CompilerServices; using System.Text.RegularExpressions; using AwesomeAssertions; using redb.Route.Core; using redb.Route.Expressions; using redb.Route.Predicates; namespace redb.Route.Tests.Expressions; /// A person in the guide's fixture exchange. public sealed class GuidePerson { public string Name { get; set; } = ""; public int Age { get; set; } public bool Active { get; set; } public GuidePerson? Manager { get; set; } } /// The bean the guide's bean: examples call. public sealed class GuidePricing { public double Gross(int qty, double price) => qty * price; public bool IsGold(string? name) => name == "Ann"; public string Badge(string name, int points) => $"{name}:{points}"; public void Touch(string _) { } public string Rate => "standard"; } /// /// Runs every example of redb.Route/EXPRESSIONS.md that the guide marks for running: each table preceded by /// <!-- run: value -->, <!-- run: template --> or <!-- run: condition --> is /// evaluated row by row on the exchange of the guide's section 0, and the result column must be what the engine /// gives. The guide cannot drift from the code: a changed result fails here. /// public sealed class ExpressionsGuideExamplesTests : IAsyncLifetime { private readonly RouteContext _context = new(); public Task InitializeAsync() { _context.AddToRegistry("pricing", new GuidePricing()); _context.AddToRegistry("pricing-rules", new GuidePricing()); _context.AddToRegistry("limits.max", 100); return Task.CompletedTask; } public async Task DisposeAsync() => await _context.DisposeAsync(); private static string Guide([CallerFilePath] string file = "") => Path.GetFullPath(Path.Combine(Path.GetDirectoryName(file)!, "..", "..", "..", "EXPRESSIONS.md")); /// The exchange of the guide's section 0, fresh for every row (increments change it). private Exchange Fixture(string? body) { var exchange = new Exchange(new Message(body switch { "json" => """{"order":{"id":7,"total":150.5,"tags":["a","b"]}}""", "xml" => "7150.5", _ => "payload", })) { Context = _context }; var headers = exchange.In.Headers; headers["a"] = 42; headers["b"] = 3; headers["neg"] = -7; headers["zero"] = 0; headers["price"] = 2.5; headers["s"] = "Hello World"; headers["flag"] = true; headers["off"] = false; headers["Content-Type"] = "text/xml"; headers["empty"] = ""; headers["user"] = new GuidePerson { Name = "Ann", Age = 30, Active = true, Manager = new GuidePerson { Name = "Bob", Age = 51 } }; headers["list"] = new List { 5, 1, 9 }; headers["when"] = new DateTime(2026, 8, 28, 10, 30, 0, DateTimeKind.Utc); headers["O'Brien"] = "obrien"; headers["redbFile.Name"] = "orders/a.xml"; headers["redbFile.NameOnly"] = "a"; exchange.Properties["count"] = 7; exchange.Properties["items"] = new List { "p", "q", "r" }; exchange.Properties["nums"] = new List { 1, 2, 3, 4 }; exchange.Properties["cfg"] = new Dictionary { ["enabled"] = true, ["limit"] = 5 }; exchange.Properties["counter"] = 10; exchange.Exception = new InvalidOperationException("boom"); return exchange; } private static readonly Regex Marker = new(@"^$", RegexOptions.Compiled); private static readonly Regex Code = new(@"`(?[^`]+)`", RegexOptions.Compiled); public sealed record Example(string Mode, string? Body, string Expression, string Expected, int Line) { public override string ToString() => $"line {Line}: {Expression}"; } /// Every marked row of the guide. public static IEnumerable Examples() { var lines = File.ReadAllLines(Guide()); for (var i = 0; i < lines.Length; i++) { if (Marker.Match(lines[i].Trim()) is not { Success: true } marker) continue; var mode = marker.Groups["mode"].Value; var body = marker.Groups["body"].Success ? marker.Groups["body"].Value : null; var row = i + 1; while (row < lines.Length && !lines[row].TrimStart().StartsWith('|')) row++; row += 2; // header and separator for (; row < lines.Length && lines[row].TrimStart().StartsWith('|'); row++) { var cells = Cells(lines[row]); var expression = Code.Match(cells[0]).Groups["code"].Value; var expected = Code.Match(cells[1]) is { Success: true } m ? m.Groups["code"].Value : null; if (expected is null) throw new InvalidOperationException($"EXPRESSIONS.md line {row + 1}: a run table row needs a `result`."); yield return [new Example(mode, body, expression, expected, row + 1)]; } } } private static string[] Cells(string line) { var text = line.Trim().Trim('|'); var cells = new List(); var current = new System.Text.StringBuilder(); for (var i = 0; i < text.Length; i++) { if (text[i] == '\\' && i + 1 < text.Length && text[i + 1] == '|') { current.Append('|'); i++; } else if (text[i] == '|') { cells.Add(current.ToString().Trim()); current.Clear(); } else { current.Append(text[i]); } } cells.Add(current.ToString().Trim()); return [.. cells]; } [Fact] public void TheGuide_HasRunnableExamples() { Examples().Count().Should().BeGreaterThan(100); } [Theory] [MemberData(nameof(Examples))] public void EveryMarkedExample_GivesTheDocumentedResult(Example example) { string actual; try { var exchange = Fixture(example.Body); actual = example.Mode switch { "template" => ExpressionResolver.ProcessTemplate(example.Expression, exchange), "condition" => PredicateFactory.FromString(example.Expression).Matches(exchange) ? "True" : "False", _ => new StringExpression(example.Expression).Evaluate(exchange) is { } value ? ExpressionResolver.TemplateText(value) : "null", }; } catch (Exception ex) { actual = $"error: {ex.Message}"; } actual.Should().Be(example.Expected, $"EXPRESSIONS.md line {example.Line}: {example.Expression}"); } } Path: redb-route/tests/redb.Route.Tests/Expressions/FileLanguageTests.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/Expressions/FileLanguageTests.cs ---- using AwesomeAssertions; using redb.Route.Core; using redb.Route.Expressions; namespace redb.Route.Tests.Expressions; /// /// Apache Camel's file language, ${file:name} and its siblings (findings register row 34 point 3): a whole /// placeholder that reads the redbFile.* headers the file consumers set. Until 4.7.0 it rendered empty. /// public sealed class FileLanguageTests { private static Exchange File() { var message = new Message("x"); message.Headers["redbFile.Name"] = "orders/a.xml"; message.Headers["redbFile.NameOnly"] = "a"; message.Headers["redbFile.Extension"] = ".xml"; message.Headers["redbFile.Parent"] = "/in/orders"; message.Headers["redbFile.AbsolutePath"] = "/in/orders/a.xml"; message.Headers["redbFile.RelativePath"] = "orders/a.xml"; message.Headers["redbFile.Length"] = 42L; message.Headers["redbFile.LastModified"] = new DateTimeOffset(2026, 11, 5, 10, 30, 0, TimeSpan.Zero); return new Exchange(message); } [Theory] [InlineData("${file:name}", "orders/a.xml")] [InlineData("${file:onlyname}", "orders/a.xml")] [InlineData("${file:name.noext}", "a")] [InlineData("${file:onlyname.noext}", "a")] [InlineData("${file:ext}", "xml")] [InlineData("${file:name.ext}", "xml")] [InlineData("${file:parent}", "/in/orders")] [InlineData("${file:path}", "/in/orders/a.xml")] [InlineData("${file:absolute.path}", "/in/orders/a.xml")] [InlineData("${file:relative.path}", "orders/a.xml")] [InlineData("${file:length}", "42")] [InlineData("${file:size}", "42")] [InlineData("archive/${file:name.noext}.done", "archive/a.done")] public void AKey_ReadsItsHeader(string template, string expected) { ExpressionResolver.ProcessTemplate(template, File()).Should().Be(expected); } [Fact] public void AWholePlaceholderKeepsTheValue_AndTakesAFormat() { new StringExpression("${file:length}").Evaluate(File()).Should().Be(42L); ExpressionResolver.ProcessTemplate("${file:length:D5}", File()).Should().Be("00042"); } [Fact] public void WithoutTheHeaders_AKeyIsEmpty() { ExpressionResolver.ProcessTemplate("[${file:name}]", new Exchange(new Message("x"))).Should().Be("[]"); } [Theory] [InlineData("${file:nosuch}", "'nosuch'")] [InlineData("${file:}", "''")] [InlineData("${file:NAME}", "'NAME'")] public void AnUnknownKey_IsAnError_ListingTheKeys(string template, string key) { var act = () => ExpressionResolver.ProcessTemplate(template, File()); act.Should().Throw() .WithMessage($"*{key} is not a file key; the keys are name, onlyname, name.noext, *"); } [Fact] public void ModifiedIsTheHeaderTime() { new StringExpression("${file:modified}").Evaluate(File()).Should() .Be(new DateTimeOffset(2026, 11, 5, 10, 30, 0, TimeSpan.Zero)); } // ── The contract the components share (row 34 point 5) ────────── private sealed class Facts : IFileFacts { public string? Name => "a.xml"; public string? NameOnly => "a"; public string? Extension => "xml"; public string? Parent => "/in"; public string? AbsolutePath => "/in/a.xml"; public string? RelativePath => "a.xml"; public long? Length => 3; public DateTimeOffset? LastModified => null; } [Fact] public void TheKeys_AreCamelsThirteen_InTheOrderTheErrorLists() { FileLanguage.Keys.Select(k => k.Key).Should().Equal( "name", "onlyname", "name.noext", "onlyname.noext", "ext", "name.ext", "parent", "path", "absolute.path", "relative.path", "length", "size", "modified"); } [Theory] [InlineData("name", true, true)] [InlineData("NAME", false, true)] [InlineData(" name.noext ", true, true)] [InlineData("nosuch", false, false)] public void TheComparison_IsAParameter(string key, bool ordinal, bool ignoreCase) { FileLanguage.TryGetFact(key, StringComparison.Ordinal, out _).Should().Be(ordinal); FileLanguage.TryGetFact(key, StringComparison.OrdinalIgnoreCase, out _).Should().Be(ignoreCase); } [Fact] public void AnotherComparison_IsRefused() { var act = () => FileLanguage.TryGetFact("name", StringComparison.CurrentCulture, out _); act.Should().Throw(); } [Theory] [InlineData("${file:name}.done", "a.xml.done")] [InlineData("${FILE:Name.NoExt}-${file:ext}-${file:size}", "a-xml-3")] [InlineData("[${file:modified}]", "[]")] [InlineData("${header.x}/${file:parent}", "${header.x}//in")] public void Substitute_IgnoringCase_IsTheComponentForm(string pattern, string expected) { FileLanguage.Substitute(pattern, new Facts(), StringComparison.OrdinalIgnoreCase).Should().Be(expected); } [Fact] public void Substitute_Ordinal_LeavesAnotherCaseAsWritten() { FileLanguage.Substitute("${FILE:NAME}|${file:name}", new Facts(), StringComparison.Ordinal).Should().Be("${FILE:NAME}|a.xml"); } [Fact] public void FindUnknownKey_NamesTheFirstUnknown() { FileLanguage.FindUnknownKey("${file:name}/${file:nosuch}/${file:other}", StringComparison.OrdinalIgnoreCase).Should().Be("nosuch"); FileLanguage.FindUnknownKey("${FILE:NAME}", StringComparison.OrdinalIgnoreCase).Should().BeNull(); FileLanguage.FindUnknownKey("archive", StringComparison.OrdinalIgnoreCase).Should().BeNull(); } [Fact] public void Resolve_WithAnUnknownKey_IsAnArgumentError() { var act = () => FileLanguage.Resolve("nosuch", new Facts(), StringComparison.Ordinal); act.Should().Throw().WithMessage("'nosuch' is not a file key; the keys are *"); } } Path: redb-route/tests/redb.Route.Tests/Expressions/FormatFunctionTests.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/Expressions/FormatFunctionTests.cs ---- using System.Globalization; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Expressions; using redb.Route.TestKit; namespace redb.Route.Tests.Expressions; /// /// format(value, pattern[, culture]) — the explicit locale escape hatch the V4 breaking change /// points at: since ${...} renders culture-invariant, this is how a route asks for local text on /// purpose. It was documented (CHANGELOG, expressions guide) before it existed; these tests are the /// contract. /// [Collection("ExpressionResolver")] public class FormatFunctionTests { private static IExchange Exchange(params (string Name, object? Value)[] headers) { var exchange = redb.Route.Core.Exchange.Create(new Message("body"), null); foreach (var (name, value) in headers) exchange.In.Headers[name] = value; return exchange; } private static object? Eval(string expression, IExchange exchange) => new StringExpression(expression).Evaluate(exchange); [Fact] public void NamedCulture_FormatsForThatLocale() { var exchange = Exchange(("price", 19.95m)); Eval("${format(header.price, 'N2', 'ru-RU')}", exchange).Should().Be("19,95"); Eval("${format(header.price, 'N2', 'en-US')}", exchange).Should().Be("19.95"); } [Fact] public void WithoutACulture_TheResultIsInvariant() { var exchange = Exchange(("price", 19.95m)); var previous = CultureInfo.CurrentCulture; CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("ru-RU"); try { Eval("${format(header.price, 'N2')}", exchange).Should().Be("19.95", "the ambient culture of the server never decides"); } finally { CultureInfo.CurrentCulture = previous; } } [Fact] public void Dates_UseTheSameFunction() { var exchange = Exchange(("when", new DateTime(2026, 9, 1, 10, 30, 0, DateTimeKind.Utc))); Eval("${format(header.when, 'dd.MM.yyyy', 'ru-RU')}", exchange).Should().Be("01.09.2026"); } [Fact] public void AStringThatHoldsANumber_IsParsedInvariantlyFirst() { var exchange = Exchange(("price", "19.95")); Eval("${format(header.price, 'N2', 'ru-RU')}", exchange).Should().Be("19,95"); } [Fact] public void AStringThatIsJustText_ComesBackAsItself() { var exchange = Exchange(("name", "Ada")); Eval("${format(header.name, 'N2')}", exchange).Should().Be("Ada"); } [Fact] public void NullValue_IsNull() => Eval("${format(header.missing, 'N2')}", Exchange()).Should().BeNull(); [Fact] public void AnUnknownCultureName_FailsAndSaysSo() { var exchange = Exchange(("price", 1m)); var act = () => Eval("${format(header.price, 'N2', 'kl-INGON')}", exchange); act.Should().Throw().WithMessage("*culture*"); } [Fact] public async Task InsideARoute_TheResultIsTheLocalText() { await using var ctx = new RouteContext().AddRoutes(b => b .From("direct://fmt").SetBody(new StringExpression("Итого: ${format(header.total, 'N2', 'ru-RU')} ₽")).To("mock://fmt")); await ctx.Start(); await ctx.SendBodyAndHeader("direct://fmt", null, "total", 1234.5m); // Built from the culture, not typed out: the group separator of ru-RU is a no-break space whose // exact code point is an ICU detail, and the test is about the mechanism, not about that. var expected = $"Итого: {1234.5m.ToString("N2", CultureInfo.GetCultureInfo("ru-RU"))} ₽"; ctx.Mock("mock://fmt").ReceivedExchanges[0].In.Body.Should().Be(expected); expected.Should().Contain("234,50", "ru-RU uses a comma for the decimal separator"); } } Path: redb-route/tests/redb.Route.Tests/Expressions/FormatSuffixTests.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/Expressions/FormatSuffixTests.cs ---- using AwesomeAssertions; using redb.Route.Core; using redb.Route.Expressions; namespace redb.Route.Tests.Expressions; /// /// The format suffix ${expr:FORMAT} (findings register row 34 point 4, variant a): format(expr, 'FORMAT') /// with the invariant culture, for a standard .NET format of one letter and up to two digits. Until 4.7.0 the suffix /// was dropped silently (${header.n:F4} gave 2.5). Namespaces and ternaries are not formats. /// public sealed class FormatSuffixTests : IDisposable { private readonly string _env = "REDB_FMT_TEST_" + Guid.NewGuid().ToString("N"); public FormatSuffixTests() => Environment.SetEnvironmentVariable(_env, "E"); public void Dispose() => Environment.SetEnvironmentVariable(_env, null); private static Exchange Message() { var exchange = new Exchange(new Message("x")); exchange.In.Headers["n"] = 2.5; exchange.In.Headers["big"] = 1234567.891m; exchange.In.Headers["id"] = 42; exchange.In.Headers["flag"] = true; exchange.In.Headers["total"] = new Dictionary { ["CostUsd"] = 0.125 }; return exchange; } private static string Render(string template) => ExpressionResolver.ProcessTemplate(template, Message()); [Theory] [InlineData("${header.n:F4}", "2.5000")] [InlineData("${header.n:F0}", "2")] [InlineData("${header.big:N2}", "1,234,567.89")] [InlineData("${header.id:D8}", "00000042")] [InlineData("${header.n * 2:F1}", "5.0")] [InlineData("cost cap hit: ${header.total.CostUsd:F4}", "cost cap hit: 0.1250")] [InlineData("${header.n : F2}", "2.50")] public void TheSuffix_Formats_Invariantly(string template, string expected) { Render(template).Should().Be(expected); } [Fact] public void AWholePlaceholder_GivesTheFormattedText() { new StringExpression("${header.n:F2}").Evaluate(Message()).Should().Be("2.50"); } [Fact] public void AMissingValue_RendersEmpty() { Render("[${header.none:F2}]").Should().Be("[]"); } [Theory] [InlineData("${header.flag ? 'a' : 'b'}", "a")] [InlineData("${header.none ?? 'd'}", "d")] [InlineData("${'a:F2'}", "a:F2")] [InlineData("${format(header.n, 'F3')}", "2.500")] public void TernariesQuotesAndCalls_AreNotSuffixes(string template, string expected) { Render(template).Should().Be(expected); } [Fact] public void ANamespaceAgainstItsName_IsNotASuffix() { Render("${env:" + _env + "}").Should().Be("E"); } [Theory] [InlineData("header.n:F4", true)] [InlineData("header.n:yyyy", false)] [InlineData("env:X", false)] [InlineData("file:name", false)] [InlineData("date:now:yyyyMMdd", false)] [InlineData("header.a ? b : c", false)] [InlineData("round(header.n):N0", true)] public void TheSplitRule(string text, bool split) { ExpressionResolver.TrySplitFormatSuffix(text, out _, out _).Should().Be(split); } } Path: redb-route/tests/redb.Route.Tests/Expressions/InOperatorTests.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/Expressions/InOperatorTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Expressions; using redb.Route.Predicates; namespace redb.Route.Tests.Expressions; /// /// in and not in: membership of a value in a list, as Camel Simple spells it /// (${header.type} in 'gold,silver'). Asked for 2026-09-25 so markup can search by a list of /// keys in one step. The right-hand side is either a collection the message carries /// (header.codes) or a list literal in parentheses — ('gold','silver'); Camel's comma /// string is not adopted, because a comma inside a string already means something else in /// include and antInclude. /// /// Elements are compared with the same equality == uses, so in can never disagree with /// == about whether 2 equals 2L or "2". /// /// [Collection("ExpressionResolver")] public class InOperatorTests : IDisposable { public InOperatorTests() => ExpressionResolver.ClearAllCaches(); public void Dispose() { ExpressionResolver.ClearAllCaches(); GC.SuppressFinalize(this); } private static IExchange With(params (string Key, object? Value)[] headers) { var exchange = new Exchange(new Message("body")); foreach (var (key, value) in headers) exchange.In.Headers[key] = value; return exchange; } private static bool Holds(string condition, IExchange exchange) => PredicateFactory.FromString(condition).Matches(exchange); [Theory] [InlineData("b", true)] [InlineData("z", false)] public void In_tests_membership_in_a_collection_the_message_carries(string code, bool expected) { var exchange = With(("code", code), ("codes", new List { "a", "b", "c" })); Holds("header.code in header.codes", exchange).Should().Be(expected); Holds("header.code not in header.codes", exchange).Should().Be(!expected); } [Fact] public void A_list_literal_is_written_in_parentheses() { var exchange = With(("tier", "silver")); Holds("header.tier in ('gold','silver')", exchange).Should().BeTrue(); Holds("header.tier in ('gold','platinum')", exchange).Should().BeFalse(); Holds("header.tier not in ('gold','platinum')", exchange).Should().BeTrue(); } [Fact] public void Numbers_compare_the_way_equality_compares_them() { // An int in the header, a long in the list: == treats them as equal, so in must too. var exchange = With(("n", 2), ("ids", new List { 1L, 2L, 3L })); Holds("header.n in header.ids", exchange).Should().BeTrue(); Holds("header.n in (1, 2, 3)", exchange).Should().BeTrue(); Holds("header.n in (4, 5)", exchange).Should().BeFalse(); } [Fact] public void The_operator_is_case_insensitive_and_needs_no_space_before_the_parenthesis() { var exchange = With(("tier", "gold")); Holds("header.tier IN ('gold')", exchange).Should().BeTrue(); Holds("header.tier NOT IN ('gold')", exchange).Should().BeFalse(); Holds("header.tier in('gold')", exchange).Should().BeTrue("in( must not be read as a call to a function named in"); } [Fact] public void An_empty_list_finds_nothing() { var exchange = With(("code", "a"), ("codes", new List())); Holds("header.code in header.codes", exchange).Should().BeFalse(); Holds("header.code not in header.codes", exchange).Should().BeTrue(); } [Fact] public void A_missing_collection_is_an_empty_one() { // No such header: nothing to be a member of — false, not an exception and not "everything". var exchange = With(("code", "a")); Holds("header.code in header.codes", exchange).Should().BeFalse(); Holds("header.code not in header.codes", exchange).Should().BeTrue(); } [Fact] public void A_string_on_the_right_is_refused_rather_than_split() { // Camel reads 'a,b' as a list; we do not, and a string must not quietly become a list of // characters either. The author is told which two forms exist. var exchange = With(("code", "a"), ("codes", "a,b")); var act = () => Holds("header.code in header.codes", exchange); act.Should().Throw().Which.ToString().Should().Contain("('a','b')"); } [Fact] public void In_combines_with_the_other_operators() { var exchange = With(("tier", "gold"), ("n", 5)); Holds("header.tier in ('gold','silver') AND header.n > 3", exchange).Should().BeTrue(); Holds("header.tier in ('bronze') OR header.n > 3", exchange).Should().BeTrue(); Holds("header.tier in ('bronze') AND header.n > 3", exchange).Should().BeFalse(); } [Fact] public void A_header_named_in_is_still_a_header() { // The detector that routes expressions to the parser must not mistake a path segment for // the operator: header.in is a header called "in", exactly as before. var exchange = With(("in", "value")); new StringExpression("header.in").Evaluate(exchange).Should().Be("value"); } [Fact] public async Task In_works_in_a_route_filter() { var passed = new List(); await using var context = new RouteContext(); context.AddRoutes(r => r .From("direct://in-filter") .Filter("header.tier in ('gold','silver')") .Process(e => passed.Add((string)e.In.Headers["tier"]!))); await context.Start(); var producer = context.GetEndpoint("direct://in-filter").CreateProducer(); await producer.Start(); foreach (var tier in new[] { "gold", "bronze", "silver" }) { var ex = new Exchange(new Message("x")); ex.In.Headers["tier"] = tier; await producer.Process(ex); } passed.Should().Equal("gold", "silver"); } } Path: redb-route/tests/redb.Route.Tests/Expressions/IncrementOperandTests.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/Expressions/IncrementOperandTests.cs ---- using AwesomeAssertions; using redb.Route.Core; using redb.Route.Expressions; namespace redb.Route.Tests.Expressions; /// /// The operand of ++ / -- (findings register row 23): a missing value starts at 0, a number or a numeric /// text counts, and a value that is there but not a number is an error naming it instead of silently becoming 0. /// public sealed class IncrementOperandTests { private static Exchange Message(object? value) { var exchange = new Exchange(new Message("x")); if (value is not null) exchange.In.Headers["x"] = value; return exchange; } [Theory] [InlineData(null, 0, 1)] [InlineData(5, 5, 6)] [InlineData("7", 7, 8)] public void ACounter_Counts(object? start, int returns, int after) { var exchange = Message(start); Convert.ToInt32(new StringExpression("header.x++").Evaluate(exchange)).Should().Be(returns); Convert.ToInt32(exchange.In.Headers["x"]).Should().Be(after); } [Theory] [InlineData("header.x++", "header.x++")] [InlineData("++header.x", "++header.x")] [InlineData("header.x--", "header.x--")] [InlineData("--header.x", "--header.x")] public void ANonNumericValue_IsAnErrorNamingIt(string expression, string written) { var exchange = Message("abc"); var act = () => new StringExpression(expression).Evaluate(exchange); act.Should().Throw() .WithMessage($"{written}: the value 'abc' (String) is not a number."); exchange.In.Headers["x"].Should().Be("abc", "the value is left as it was"); } [Fact] public void InATemplate_TheSameError() { var act = () => ExpressionResolver.ProcessTemplate("n=${header.x++}", Message("abc")); act.Should().Throw().WithMessage("*is not a number."); } } Path: redb-route/tests/redb.Route.Tests/Expressions/JsonPathDialectSnapshotTests.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/Expressions/JsonPathDialectSnapshotTests.cs ---- using System.Globalization; using System.Text; using System.Text.Json.Nodes; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Expressions; namespace redb.Route.Tests.Expressions; /// /// Characterization net for the jpath dialect (V4 phase 10): every form of the corpus is /// evaluated against a fixed document and described as text; the description is compared with the /// snapshot below line by line. Any change in the engine or the conversion rules shows up here as a /// named line, not as a surprise in a route. /// [Collection("ExpressionResolver")] public class JsonPathDialectSnapshotTests { private const string Store = """ { "store": { "book": [ { "category": "reference", "author": "Nigel Rees", "title": "Sayings of the Century", "price": 8.95, "published": "2026-01-15T10:00:00Z" }, { "category": "fiction", "author": "Evelyn Waugh", "title": "Sword of Honour", "price": 12.99 }, { "category": "fiction", "author": "Herman Melville", "title": "Moby Dick", "isbn": "0-553-21311-3", "price": 8.99 }, { "category": "fiction", "author": "J. R. R. Tolkien", "title": "The Lord of the Rings", "isbn": "0-395-19395-8", "price": 22.99 } ], "bicycle": { "color": "red", "price": 19.95 } }, "expensive": 10, "big": 12345678901, "ids": [1, 2, 3], "tags": ["a", "b"], "empty": [], "nothing": null, "meta": { "guid": "8b0a5e3e-1d4a-4b6d-9d8e-0f1c2a3b4c5d", "when": "2026-09-01T12:00:00+03:00" } } """; public sealed class Poco { public string Name { get; set; } = "Alice"; public int Age { get; set; } = 30; public string[] Tags { get; set; } = ["x", "y"]; } private enum BodyKind { Json, Lenient, SingleQuotes, Poco, JsonNode } private sealed record Case(string Id, string Path, Type Target, BodyKind Body = BodyKind.Json); private static readonly Case[] Corpus = [ new("authors_all", "$.store.book[*].author", typeof(string)), new("authors_arr", "$.store.book[*].author", typeof(string[])), new("authors_list", "$.store.book[*].author", typeof(List)), new("prices_rec_arr", "$..price", typeof(double[])), new("prices_rec_obj", "$..price", typeof(object)), new("slice", "$.store.book[0:2].title", typeof(string[])), new("neg_slice", "$.store.book[-1:].title", typeof(string[])), new("filter_lt", "$.store.book[?(@.price < 10)].title", typeof(string[])), new("filter_exists", "$.store.book[?(@.isbn)].title", typeof(string[])), new("filter_eq", "$.store.book[?(@.category == 'fiction')].author", typeof(List)), new("filter_bool_true", "$.store.book[?(@.price > 20)]", typeof(bool)), new("filter_bool_false", "$.store.book[?(@.price > 100)]", typeof(bool)), new("filter_str_empty", "$.store.book[?(@.price > 100)].title", typeof(string)), new("filter_obj", "$.store.book[?(@.price > 20)].title", typeof(object)), new("first_book_obj", "$.store.book[0]", typeof(object)), new("first_book_dict", "$.store.book[0]", typeof(Dictionary)), new("bracket", "$['store']['bicycle']['color']", typeof(string)), new("int_obj", "$.expensive", typeof(object)), new("big_obj", "$.big", typeof(object)), new("int_typed", "$.expensive", typeof(int)), new("price_obj", "$.store.bicycle.price", typeof(object)), new("price_decimal", "$.store.bicycle.price", typeof(decimal)), new("price_str", "$.store.bicycle.price", typeof(string)), new("ids_int_arr", "$.ids", typeof(int[])), new("ids_obj", "$.ids", typeof(object)), new("ids_str", "$.ids", typeof(string)), new("tags_obj", "$.tags", typeof(object)), new("empty_obj", "$.empty", typeof(object)), new("null_obj", "$.nothing", typeof(object)), new("null_str", "$.nothing", typeof(string)), new("missing_str", "$.missing", typeof(string)), new("missing_int", "$.missing", typeof(int)), new("missing_nint", "$.missing", typeof(int?)), new("missing_obj", "$.missing", typeof(object)), new("chain_missing", "$.store.missing.deeper", typeof(string)), new("date_obj", "$.store.book[0].published", typeof(object)), new("date_typed", "$.store.book[0].published", typeof(DateTime)), new("date_str", "$.store.book[0].published", typeof(string)), new("offset_obj", "$.meta.when", typeof(object)), new("guid_obj", "$.meta.guid", typeof(object)), new("root_obj", "$", typeof(object)), new("root_str", "$", typeof(string)), new("wildcard_obj", "$.store.book[*].price", typeof(object)), new("bool_obj", "$.store.book[?(@.price > 20)].price", typeof(object)), new("lenient_comments", "$.a", typeof(object), BodyKind.Lenient), new("single_quotes", "$.a", typeof(object), BodyKind.SingleQuotes), new("poco_prop", "$.Name", typeof(string), BodyKind.Poco), new("poco_lower", "$.name", typeof(string), BodyKind.Poco), new("poco_arr", "$.Tags", typeof(string[]), BodyKind.Poco), new("poco_obj", "$.Age", typeof(object), BodyKind.Poco), new("jsonnode_str", "$.store.bicycle.color", typeof(string), BodyKind.JsonNode), new("jsonnode_obj", "$.ids", typeof(object), BodyKind.JsonNode), ]; /// Forms that go through the expression language rather than JsonPathExpression directly. private static readonly (string Id, Func Run)[] LanguageCorpus = [ ("tpl_title", e => ExpressionResolver.ProcessTemplate("${jpath($.store.book[1].title)}", e)), ("tpl_missing", e => ExpressionResolver.ProcessTemplate("[${jpath($.missing)}]", e)), ("tpl_price", e => ExpressionResolver.ProcessTemplate("${jpath($.store.bicycle.price)}", e)), ("val_ids", e => ExpressionResolver.ResolveExpression("jpath('$.ids')", e)), ("val_filter_hit", e => ExpressionResolver.ResolveExpression("jpath('$.store.book[?(@.price > 20)]')", e)), ("val_filter_miss", e => ExpressionResolver.ResolveExpression("jpath('$.store.book[?(@.price > 100)]')", e)), ("val_int", e => ExpressionResolver.ResolveExpression("jpath('$.expensive')", e)), ("val_arith", e => ExpressionResolver.ResolveExpression("jpath('$.expensive') * 2", e)), ]; [Fact] public void Dialect_MatchesSnapshot() { var actual = Record(); var expected = Normalize(Snapshot); if (actual == expected) return; var a = actual.Split('\n'); var b = expected.Split('\n'); var diff = new StringBuilder("jpath dialect drift (expected → actual):\n"); foreach (var line in a.Where(l => !b.Contains(l))) diff.Append(" + ").Append(line).Append('\n'); foreach (var line in b.Where(l => !a.Contains(l))) diff.Append(" - ").Append(line).Append('\n'); diff.Append("\n--- full actual ---\n").Append(actual); Assert.Fail(diff.ToString()); } private static string Record() { var sb = new StringBuilder(); foreach (var c in Corpus) sb.Append(c.Id).Append(" | ").Append(TypeName(c.Target)).Append(" | ").Append(Evaluate(c)).Append('\n'); var exchange = Exchange.Create(new Message(Store), null); foreach (var (id, run) in LanguageCorpus) sb.Append(id).Append(" | language | ").Append(Guard(() => run(exchange))).Append('\n'); return Normalize(sb.ToString()); } private static string Evaluate(Case c) { var exchange = Exchange.Create(new Message(Body(c.Body)), null); var method = typeof(JsonPathExpression).GetMethod(nameof(JsonPathExpression.Evaluate))!.MakeGenericMethod(c.Target); return Guard(() => { try { return method.Invoke(new JsonPathExpression(c.Path), [exchange]); } catch (System.Reflection.TargetInvocationException ex) when (ex.InnerException is not null) { throw ex.InnerException; } }); } private static object Body(BodyKind kind) => kind switch { BodyKind.Json => Store, BodyKind.Lenient => "{ // comment\n \"a\": 1, /* block */ \"b\": [1, 2,], }", BodyKind.SingleQuotes => "{'a': 1}", BodyKind.Poco => new Poco(), BodyKind.JsonNode => JsonNode.Parse(Store)!, _ => throw new ArgumentOutOfRangeException(nameof(kind)), }; private static string Guard(Func run) { try { return Describe(run()); } catch (Exception ex) { return "!" + ex.GetType().Name; } } private static string Describe(object? value) => value switch { null => "null", string s => "\"" + s + "\"", bool b => b ? "true" : "false", DateTime d => "DateTime:" + d.ToUniversalTime().ToString("o", CultureInfo.InvariantCulture), DateTimeOffset d => "DateTimeOffset:" + d.ToString("o", CultureInfo.InvariantCulture), Guid g => "Guid:" + g, JsonNode node => node.GetType().Name + ":" + node.ToJsonString(), System.Collections.IDictionary dict => "{" + string.Join(", ", dict.Keys.Cast().Select(k => k.ToString())) + "}:" + TypeName(value.GetType()), System.Collections.IEnumerable list => "[" + string.Join(", ", list.Cast().Select(Describe)) + "]:" + TypeName(value.GetType()), IFormattable f => f.ToString(null, CultureInfo.InvariantCulture) + ":" + value.GetType().Name, _ => value.ToString() + ":" + TypeName(value.GetType()), }; private static string TypeName(Type t) => t.IsArray ? TypeName(t.GetElementType()!) + "[]" : t.IsGenericType ? t.Name[..t.Name.IndexOf('`')] + "<" + string.Join(",", t.GetGenericArguments().Select(TypeName)) + ">" : t.Name; private static string Normalize(string text) => text.Replace("\r\n", "\n").Trim(); // Recorded 2026-09-01 on JsonPath.Net 3.0.2 + System.Text.Json right after the migration. The same corpus was // recorded on the Newtonsoft engine first, and these lines changed with the migration // (dates stay strings, single-quoted JSON rejected, numbers rendered invariant, negative slices and // JsonNode bodies now work, arrays/objects to string give JSON text, empty filter to bool gives false). private const string Snapshot = """ authors_all | String | "Nigel Rees, Evelyn Waugh, Herman Melville, J. R. R. Tolkien" authors_arr | String[] | ["Nigel Rees", "Evelyn Waugh", "Herman Melville", "J. R. R. Tolkien"]:String[] authors_list | List | ["Nigel Rees", "Evelyn Waugh", "Herman Melville", "J. R. R. Tolkien"]:List prices_rec_arr | Double[] | [8.95:Double, 12.99:Double, 8.99:Double, 22.99:Double, 19.95:Double]:Double[] prices_rec_obj | Object | [8.95:Double, 12.99:Double, 8.99:Double, 22.99:Double, 19.95:Double]:Double[] slice | String[] | ["Sayings of the Century", "Sword of Honour"]:String[] neg_slice | String[] | ["The Lord of the Rings"]:String[] filter_lt | String[] | ["Sayings of the Century", "Moby Dick"]:String[] filter_exists | String[] | ["Moby Dick", "The Lord of the Rings"]:String[] filter_eq | List | ["Evelyn Waugh", "Herman Melville", "J. R. R. Tolkien"]:List filter_bool_true | Boolean | true filter_bool_false | Boolean | false filter_str_empty | String | null filter_obj | Object | "The Lord of the Rings" first_book_obj | Object | JsonObject:{"category":"reference","author":"Nigel Rees","title":"Sayings of the Century","price":8.95,"published":"2026-01-15T10:00:00Z"} first_book_dict | Dictionary | {category, author, title, price, published}:Dictionary bracket | String | "red" int_obj | Object | 10:Int64 big_obj | Object | 12345678901:Int64 int_typed | Int32 | 10:Int32 price_obj | Object | 19.95:Double price_decimal | Decimal | 19.95:Decimal price_str | String | "19.95" ids_int_arr | Int32[] | [1:Int32, 2:Int32, 3:Int32]:Int32[] ids_obj | Object | [1:Int32, 2:Int32, 3:Int32]:Int32[] ids_str | String | "[1,2,3]" tags_obj | Object | ["a", "b"]:String[] empty_obj | Object | []:Object[] null_obj | Object | null null_str | String | null missing_str | String | null missing_int | Int32 | !InvalidOperationException missing_nint | Nullable | null missing_obj | Object | null chain_missing | String | null date_obj | Object | "2026-01-15T10:00:00Z" date_typed | DateTime | DateTime:2026-01-15T10:00:00.0000000Z date_str | String | "2026-01-15T10:00:00Z" offset_obj | Object | "2026-09-01T12:00:00+03:00" guid_obj | Object | "8b0a5e3e-1d4a-4b6d-9d8e-0f1c2a3b4c5d" root_obj | Object | JsonObject:{"store":{"book":[{"category":"reference","author":"Nigel Rees","title":"Sayings of the Century","price":8.95,"published":"2026-01-15T10:00:00Z"},{"category":"fiction","author":"Evelyn Waugh","title":"Sword of Honour","price":12.99},{"category":"fiction","author":"Herman Melville","title":"Moby Dick","isbn":"0-553-21311-3","price":8.99},{"category":"fiction","author":"J. R. R. Tolkien","title":"The Lord of the Rings","isbn":"0-395-19395-8","price":22.99}],"bicycle":{"color":"red","price":19.95}},"expensive":10,"big":12345678901,"ids":[1,2,3],"tags":["a","b"],"empty":[],"nothing":null,"meta":{"guid":"8b0a5e3e-1d4a-4b6d-9d8e-0f1c2a3b4c5d","when":"2026-09-01T12:00:00\u002B03:00"}} root_str | String | "{"store":{"book":[{"category":"reference","author":"Nigel Rees","title":"Sayings of the Century","price":8.95,"published":"2026-01-15T10:00:00Z"},{"category":"fiction","author":"Evelyn Waugh","title":"Sword of Honour","price":12.99},{"category":"fiction","author":"Herman Melville","title":"Moby Dick","isbn":"0-553-21311-3","price":8.99},{"category":"fiction","author":"J. R. R. Tolkien","title":"The Lord of the Rings","isbn":"0-395-19395-8","price":22.99}],"bicycle":{"color":"red","price":19.95}},"expensive":10,"big":12345678901,"ids":[1,2,3],"tags":["a","b"],"empty":[],"nothing":null,"meta":{"guid":"8b0a5e3e-1d4a-4b6d-9d8e-0f1c2a3b4c5d","when":"2026-09-01T12:00:00\u002B03:00"}}" wildcard_obj | Object | [8.95:Double, 12.99:Double, 8.99:Double, 22.99:Double]:Double[] bool_obj | Object | 22.99:Double lenient_comments | Object | 1:Int64 single_quotes | Object | !InvalidOperationException poco_prop | String | "Alice" poco_lower | String | null poco_arr | String[] | ["x", "y"]:String[] poco_obj | Object | 30:Int64 jsonnode_str | String | "red" jsonnode_obj | Object | [1:Int32, 2:Int32, 3:Int32]:Int32[] tpl_title | language | "Sword of Honour" tpl_missing | language | "[]" tpl_price | language | "19.95" val_ids | language | [1:Int32, 2:Int32, 3:Int32]:Int32[] val_filter_hit | language | [JsonObject:{"category":"fiction","author":"J. R. R. Tolkien","title":"The Lord of the Rings","isbn":"0-395-19395-8","price":22.99}]:Object[] val_filter_miss | language | null val_int | language | 10:Int64 val_arith | language | 20:Int32 """; } Path: redb-route/tests/redb.Route.Tests/Expressions/JsonPathExpressionTests.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/Expressions/JsonPathExpressionTests.cs ---- using AwesomeAssertions; using System.Text.Json.Nodes; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Expressions; namespace redb.Route.Tests.Expressions; /// /// Tests for JsonPath functionality: JsonPathExpression, TypedJsonPathExpression, /// CompiledJPathExpression, jpath() DSL helpers, and ApplyJPath via ExpressionResolver. /// [Collection("ExpressionResolver")] public class JsonPathExpressionTests : IDisposable { private const string SampleJson = """ { "id": "DRV-001", "firstName": "John", "lastName": "Doe", "isHired": true, "dismissed": false, "age": 35, "salary": 75000.50, "tags": ["driver", "active", "verified"], "scores": [90, 85, 92], "address": { "city": "Moscow", "country": "Russia" }, "contacts": [ { "type": "email", "value": "john@example.com" }, { "type": "phone", "value": "+7-999-123-45-67" } ] } """; public JsonPathExpressionTests() { ExpressionResolver.ClearAllCaches(); } public void Dispose() { ExpressionResolver.ClearAllCaches(); } private static IExchange CreateJsonExchange(string json = SampleJson) => new Exchange(new Message(JsonNode.Parse(json)!)); private static IExchange CreatePocoExchange() => new Exchange(new Message(new { Name = "Alice", Age = 30, Active = true })); // ── JsonPathExpression: basic property access ── [Fact] public void Evaluate_StringProperty_ReturnsString() { var expr = new JsonPathExpression("$.firstName"); var result = expr.Evaluate(CreateJsonExchange()); result.Should().Be("John"); } [Fact] public void Evaluate_BoolProperty_ReturnsBool() { var expr = new JsonPathExpression("$.isHired"); var result = expr.Evaluate(CreateJsonExchange()); result.Should().BeTrue(); } [Fact] public void Evaluate_IntProperty_ReturnsInt() { var expr = new JsonPathExpression("$.age"); var result = expr.Evaluate(CreateJsonExchange()); result.Should().Be(35); } [Fact] public void Evaluate_DoubleProperty_ReturnsDouble() { var expr = new JsonPathExpression("$.salary"); var result = expr.Evaluate(CreateJsonExchange()); result.Should().BeApproximately(75000.50, 0.01); } [Fact] public void Evaluate_NestedProperty_ReturnsValue() { var expr = new JsonPathExpression("$.address.city"); var result = expr.Evaluate(CreateJsonExchange()); result.Should().Be("Moscow"); } [Fact] public void Evaluate_RootPath_ReturnsWholeDocument() { var expr = new JsonPathExpression("$"); var result = expr.Evaluate(CreateJsonExchange()); result.Should().NotBeNull(); // Root returns JsonObject (System.Text.Json) result.Should().BeAssignableTo(); } [Fact] public void Evaluate_ArrayIndexAccess_ReturnsElement() { var expr = new JsonPathExpression("$.tags[0]"); var result = expr.Evaluate(CreateJsonExchange()); result.Should().Be("driver"); } // ── JsonPathExpression: array results ── [Fact] public void Evaluate_ArrayProperty_AsObject_ReturnsTypedArray() { var expr = new JsonPathExpression("$.scores"); var result = expr.Evaluate(CreateJsonExchange()); // ConvertJTokenToType creates a typed int[] for homogeneous integer arrays result.Should().BeAssignableTo(); } [Fact] public void Evaluate_ArrayProperty_AsIntArray() { var expr = new JsonPathExpression("$.scores"); var result = expr.Evaluate(CreateJsonExchange()); result.Should().Equal(90, 85, 92); } [Fact] public void Evaluate_ArrayProperty_AsStringArray() { var expr = new JsonPathExpression("$.tags"); var result = expr.Evaluate(CreateJsonExchange()); result.Should().Equal("driver", "active", "verified"); } [Fact] public void Evaluate_WildcardSelect_ReturnsMultipleValues() { var expr = new JsonPathExpression("$.contacts[*].type"); var result = expr.Evaluate(CreateJsonExchange()); // When T=string with multiple tokens, should join them result.Should().Contain("email"); result.Should().Contain("phone"); } // ── JsonPathExpression: path not found → null / default ── [Fact] public void Evaluate_NonexistentPath_ReturnsDefault() { var expr = new JsonPathExpression("$.nonexistent"); var result = expr.Evaluate(CreateJsonExchange()); result.Should().BeNull(); } [Fact] public void Evaluate_NonexistentPath_String_ReturnsNull() { var expr = new JsonPathExpression("$.doesNotExist"); var result = expr.Evaluate(CreateJsonExchange()); result.Should().BeNull(); } [Fact] public void Evaluate_NonexistentPath_ValueType_Throws() { var expr = new JsonPathExpression("$.doesNotExist"); var act = () => expr.Evaluate(CreateJsonExchange()); act.Should().Throw(); } // ── JsonPathExpression: POCO body (auto-serialized) ── [Fact] public void Evaluate_PocoBody_ExtractsProperty() { var expr = new JsonPathExpression("$.Name"); var result = expr.Evaluate(CreatePocoExchange()); result.Should().Be("Alice"); } [Fact] public void Evaluate_PocoBody_ExtractsBool() { var expr = new JsonPathExpression("$.Active"); var result = expr.Evaluate(CreatePocoExchange()); result.Should().BeTrue(); } // ── JsonPathExpression: string body (auto-parsed) ── [Fact] public void Evaluate_StringBody_ParsesJsonAndExtracts() { var exchange = new Exchange(new Message(SampleJson)); var expr = new JsonPathExpression("$.firstName"); var result = expr.Evaluate(exchange); result.Should().Be("John"); } // ── JsonPathExpression: null body ── [Fact] public void Evaluate_NullBody_Throws() { var expr = new JsonPathExpression("$.anything"); var exchange = new Exchange(new Message(null)); var act = () => expr.Evaluate(exchange); act.Should().Throw().WithMessage("*null*"); } // ── JsonPathExpression: filter queries ── [Fact] public void Evaluate_FilterQuery_ReturnsFilteredResults() { var expr = new JsonPathExpression("$.contacts[?(@.type=='email')].value"); var result = expr.Evaluate(CreateJsonExchange()); result.Should().Be("john@example.com"); } [Fact] public void Evaluate_FilterQuery_AsBool_ReturnsTrueWhenMatches() { var expr = new JsonPathExpression("$.contacts[?(@.type=='email')]"); var result = expr.Evaluate(CreateJsonExchange()); result.Should().BeTrue(); } // ── JsonPathExpression: constructor validation ── [Fact] public void Constructor_NullPath_Throws() { var act = () => new JsonPathExpression(null!); act.Should().Throw(); } // ── TypedJsonPathExpression: type-safe extraction ── [Fact] public void TypedExpression_Bool_ReturnsBool() { var expr = new TypedJsonPathExpression("$.isHired"); // Processor calls Evaluate, but internally evaluates as bool var result = expr.Evaluate(CreateJsonExchange()); result.Should().BeOfType(); result.Should().Be(true); } [Fact] public void TypedExpression_Int_ReturnsInt() { var expr = new TypedJsonPathExpression("$.age"); var result = expr.Evaluate(CreateJsonExchange()); result.Should().BeOfType(); result.Should().Be(35); } [Fact] public void TypedExpression_StringArray_ReturnsStringArray() { var expr = new TypedJsonPathExpression("$.tags"); var result = expr.Evaluate(CreateJsonExchange()); result.Should().BeOfType(); ((string[])result!).Should().Equal("driver", "active", "verified"); } [Fact] public void TypedExpression_DirectT_StillWorks() { var expr = new TypedJsonPathExpression("$.dismissed"); // Directly asking for bool var result = expr.Evaluate(CreateJsonExchange()); result.Should().BeFalse(); } // ── CompiledJPathExpression: dynamic path ── [Fact] public void CompiledJPath_DynamicPathFromProperty() { var compiled = new CompiledJPathExpression(ex => "$." + ex.Properties["field"]?.ToString()); var exchange = CreateJsonExchange(); exchange.Properties["field"] = "firstName"; var result = compiled.Evaluate(exchange); result.Should().Be("John"); } [Fact] public void CompiledJPath_NullPath_ReturnsDefault() { var compiled = new CompiledJPathExpression(_ => null!); var result = compiled.Evaluate(CreateJsonExchange()); result.Should().BeNull(); } // ── ApplyJPath via ExpressionResolver (string expression path) ── [Fact] public void Resolver_JPathInTemplate_ExtractsValue() { var exchange = CreateJsonExchange(); var result = ExpressionResolver.ProcessTemplate("${jpath('$.firstName')}", exchange); result.Should().Be("John"); } [Fact] public void Resolver_JPathInTemplate_PathNotFound_ReturnsEmpty() { var exchange = CreateJsonExchange(); // Path not found → ApplyJPath returns null → template turns null to "" var result = ExpressionResolver.ProcessTemplate("${jpath('$.nonexistent')}", exchange); result.Should().Be(""); } [Fact] public void Resolver_JPathInTemplate_NestedPath() { var exchange = CreateJsonExchange(); var result = ExpressionResolver.ProcessTemplate("City: ${jpath('$.address.city')}", exchange); result.Should().Be("City: Moscow"); } [Fact] public void Resolver_JPathDirect_ReturnsTypedResult() { var exchange = CreateJsonExchange(); var result = ExpressionResolver.ResolveExpression("jpath('$.age')", exchange); // Should return a numeric value, not a string result.Should().NotBeNull(); } [Fact] public void Resolver_JPath_RootPath_ReturnsObject() { var exchange = CreateJsonExchange(); var result = ExpressionResolver.ResolveExpression("jpath('$')", exchange); result.Should().NotBeNull(); } // ── SetProperty with IExpression (integration) ── [Fact] public void ExpressionPropertyProcessor_SetsPropertyFromExpression() { var processor = new redb.Route.Processors.ExpressionPropertyProcessor( "name", new JsonPathExpression("$.firstName")); var exchange = CreateJsonExchange(); processor.Process(exchange); exchange.Properties["name"].Should().Be("John"); } [Fact] public void ExpressionPropertyProcessor_TypedExpression_SetsTypedValue() { var processor = new redb.Route.Processors.ExpressionPropertyProcessor( "hired", new TypedJsonPathExpression("$.isHired")); var exchange = CreateJsonExchange(); processor.Process(exchange); exchange.Properties["hired"].Should().BeOfType(); exchange.Properties["hired"].Should().Be(true); } // ── ApplyJPath: no longer converts JArray to string ── [Fact] public void Resolver_JPath_Array_DoesNotFlattenToString() { var exchange = CreateJsonExchange(); var result = ExpressionResolver.ResolveExpression("jpath('$.scores')", exchange); // Should NOT be a comma-separated string "90, 85, 92" result.Should().NotBeOfType(); } // ── ApplyJPath error handling: propagates real errors, null body → null ── [Fact] public void Resolver_JPath_NullBody_ReturnsNull() { var exchange = new Exchange(new Message(null)); var result = ExpressionResolver.ResolveExpression("jpath('$.anything')", exchange); result.Should().BeNull(); } } Path: redb-route/tests/redb.Route.Tests/Expressions/JsonPathStreamBodyTests.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/Expressions/JsonPathStreamBodyTests.cs ---- using redb.Route.Core; using redb.Route.Expressions; namespace redb.Route.Tests.Expressions; /// Code review 2026-09-01: a stream body can be evaluated more than once; the expression leaves the stream where it found it. [Collection("ExpressionResolver")] public class JsonPathStreamBodyTests { [Fact] public void SeekableStreamBody_CanBeEvaluatedTwice() { var exchange = new Exchange(new Message(new MemoryStream("""{"id":"DRV-001","age":35}"""u8.ToArray()))); new JsonPathExpression("$.id").Evaluate(exchange).Should().Be("DRV-001"); new JsonPathExpression("$.age").Evaluate(exchange).Should().Be(35, "the first evaluation must leave the stream where it found it"); } [Fact] public void SeekableStreamBody_IsReadFromItsCurrentPosition_AndThePositionIsRestored() { var stream = new MemoryStream("xx{\"id\":1}"u8.ToArray()); stream.Position = 2; var exchange = new Exchange(new Message(stream)); new JsonPathExpression("$.id").Evaluate(exchange).Should().Be(1); stream.Position.Should().Be(2); } } Path: redb-route/tests/redb.Route.Tests/Expressions/LanguageAdditionsF15Tests.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/Expressions/LanguageAdditionsF15Tests.cs ---- using System.Globalization; using redb.Route.Abstractions; using redb.Route.Expressions.Ast; using redb.Route.Core; using redb.Route.Expressions; namespace redb.Route.Tests.Expressions; /// /// The three language additions the examples asked for — the modulo operator /// %, uuid([format]) and datediff(a, b, unit). Every form is exercised in BOTH /// engine branches (compiled via , interpreted via the AST directly), /// and the culture-sensitive paths are pinned invariant. /// [Collection("ExpressionResolver")] public class LanguageAdditionsF15Tests { private static IExchange Exchange(params (string Name, object? Value)[] headers) { var exchange = redb.Route.Core.Exchange.Create(new Message("body"), null); foreach (var (name, value) in headers) exchange.In.Headers[name] = value; return exchange; } private static object? Compiled(string expression, IExchange exchange) => new StringExpression(expression).Evaluate(exchange); private static object? Interpreted(string expression, IExchange exchange) { var tokens = new Tokenizer(expression).GetAllTokens(); var node = new Parser(tokens).Parse(); return node.Evaluate(exchange); } // ── % (modulo) ─────────────────────────────────────────────────────────── [Theory] [InlineData("${header.a % 3}", 1)] [InlineData("${header.a%3}", 1)] // whitespace never carries meaning [InlineData("${(header.a + 2) % 4}", 0)] public void Modulo_Compiled_ComputesAndCollapsesWholeResultsToInt(string form, int expected) { Compiled(form, Exchange(("a", 10))).Should().Be(expected); } [Fact] public void Modulo_Interpreted_AgreesWithCompiled() { var exchange = Exchange(("a", 10)); Interpreted("header.a % 3", exchange).Should().Be(1); Interpreted("header.a%3", exchange).Should().Be(1); } [Fact] public void Modulo_ByZero_YieldsNull_LikeDivision() { var exchange = Exchange(("a", 10), ("z", 0)); Compiled("${header.a % header.z}", exchange).Should().BeNull(); Interpreted("header.a % header.z", exchange).Should().BeNull(); } [Fact] public void Modulo_FractionalResult_StaysDouble() { Compiled("${header.p % 2}", Exchange(("p", 5.5))).Should().Be(1.5); } [Fact] public void Modulo_InACondition_Partitions() { var even = Exchange(("n", 42)); var odd = Exchange(("n", 41)); var expr = new StringExpression("${header.n % 2 == 0}"); expr.Evaluate(even).Should().Be(true); expr.Evaluate(odd).Should().Be(false); } [Fact] public void Modulo_IsCultureInvariant_OnDecimalOperands() { var previous = CultureInfo.CurrentCulture; CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("ru-RU"); try { Compiled("${header.p % 2.5}", Exchange(("p", 7.5))).Should().Be(0); } finally { CultureInfo.CurrentCulture = previous; } } // ── uuid() ─────────────────────────────────────────────────────────────── [Fact] public void Uuid_Compiled_ProducesAParseableGuid_DefaultDFormat() { var text = Compiled("${uuid()}", Exchange())?.ToString(); Guid.TryParseExact(text, "D", out _).Should().BeTrue($"got '{text}'"); } [Fact] public void Uuid_CompactNFormat_OnRequest() { var text = Compiled("${uuid('N')}", Exchange())?.ToString(); Guid.TryParseExact(text, "N", out _).Should().BeTrue($"got '{text}'"); } [Fact] public void Uuid_IsImpure_EveryEvaluationYieldsANewValue() { var exchange = Exchange(); var expr = new StringExpression("${uuid()}"); // one compiled delegate, evaluated twice expr.Evaluate(exchange).Should().NotBe(expr.Evaluate(exchange)); } [Fact] public void Uuid_Interpreted_AgreesWithCompiled() { Guid.TryParseExact(Interpreted("uuid()", Exchange())?.ToString(), "D", out _).Should().BeTrue(); Guid.TryParseExact(Interpreted("uuid('N')", Exchange())?.ToString(), "N", out _).Should().BeTrue(); } // ── datediff(a, b, unit) ───────────────────────────────────────────────── [Fact] public void DateDiff_Compiled_FirstMinusSecond_InTheRequestedUnit() { var exchange = Exchange( ("later", new DateTime(2026, 9, 2, 12, 0, 0, DateTimeKind.Utc)), ("earlier", new DateTime(2026, 9, 1, 6, 0, 0, DateTimeKind.Utc))); Compiled("${datediff(header.later, header.earlier, 'hours')}", exchange).Should().Be(30); Compiled("${datediff(header.earlier, header.later, 'hours')}", exchange).Should().Be(-30); Compiled("${datediff(header.later, header.earlier, 'minutes')}", exchange).Should().Be(1800); Compiled("${datediff(header.later, header.earlier, 'ms')}", exchange).Should().Be(108000000); } [Fact] public void DateDiff_FractionalDays_StayDouble() { var exchange = Exchange( ("later", new DateTime(2026, 9, 2, 12, 0, 0, DateTimeKind.Utc)), ("earlier", new DateTime(2026, 9, 1, 6, 0, 0, DateTimeKind.Utc))); Compiled("${datediff(header.later, header.earlier, 'days')}", exchange).Should().Be(1.25); } [Fact] public void DateDiff_ParsesStringDates_Invariantly() { var previous = CultureInfo.CurrentCulture; CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("ru-RU"); try { Compiled("${datediff('2026-01-03', '2026-01-01', 'days')}", Exchange()).Should().Be(2); } finally { CultureInfo.CurrentCulture = previous; } } [Fact] public void DateDiff_UnknownUnitOrUnparsableDate_YieldsNull_LikeDateAdd() { Compiled("${datediff('2026-01-03', '2026-01-01', 'fortnights')}", Exchange()).Should().BeNull(); Compiled("${datediff('not a date', '2026-01-01', 'days')}", Exchange()).Should().BeNull(); } [Fact] public void DateDiff_Interpreted_AgreesWithCompiled() { Interpreted("datediff('2026-01-03', '2026-01-01', 'days')", Exchange()).Should().Be(2); Interpreted("datediff('2026-01-01', '2026-01-03', 'days')", Exchange()).Should().Be(-2); } } Path: redb-route/tests/redb.Route.Tests/Expressions/LogicalShortCircuitTests.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/Expressions/LogicalShortCircuitTests.cs ---- using AwesomeAssertions; using redb.Route.Core; using redb.Route.Expressions; using redb.Route.Expressions.Ast; using redb.Route.Predicates; namespace redb.Route.Tests.Expressions; /// /// AND and OR short-circuit over the truthiness rule (findings register row 25), and ?? evaluates its right side only /// when the left is null (row 26): the right side runs only when the left /// one does not decide. The values are the ones the language gave before; what stops is a side effect or a fault on a /// right side that does not matter. XOR needs both sides and evaluates both. /// public sealed class LogicalShortCircuitTests { private static Exchange Message(bool flag) { var exchange = new Exchange(new Message("x")); exchange.In.Headers["flag"] = flag; exchange.In.Headers["n"] = 0; return exchange; } [Theory] [InlineData("header.flag AND header.n++ > 0", false, 0)] [InlineData("header.flag && header.n++ > 0", false, 0)] [InlineData("header.flag OR header.n++ > 0", true, 0)] [InlineData("header.flag || header.n++ > 0", true, 0)] [InlineData("header.flag AND header.n++ > 0", true, 1)] [InlineData("header.flag OR header.n++ > 0", false, 1)] [InlineData("header.flag XOR header.n++ > 0", false, 1)] [InlineData("header.flag XOR header.n++ > 0", true, 1)] public void TheRightSide_RunsOnlyWhenTheLeftDoesNotDecide(string expression, bool flag, int nAfter) { var exchange = Message(flag); new StringExpression(expression).Evaluate(exchange); exchange.In.Headers["n"].Should().Be(nAfter); } [Theory] [InlineData("header.flag AND bean:svc.Check()", false)] [InlineData("header.flag OR bean:svc.Check()", true)] public void AFaultOnARightSideThatDoesNotMatter_DoesNotHappen(string condition, bool flag) { // The exchange has no route context, so evaluating the bean: call would fail. PredicateFactory.FromString(condition).Matches(Message(flag)).Should().Be(flag); } [Theory] [InlineData("header.flag AND bean:svc.Check()", true)] [InlineData("header.flag OR bean:svc.Check()", false)] public void ARightSideThatMatters_StillRunsAndFails(string condition, bool flag) { var act = () => PredicateFactory.FromString(condition).Matches(Message(flag)); act.Should().Throw().WithMessage("*has no route context*"); } [Theory] [InlineData("header.flag ?? header.n++", true, 0)] [InlineData("header.missing ?? header.n++", true, 1)] public void NullCoalesce_RunsItsRightSideOnlyForANullLeft(string expression, bool flag, int nAfter) { var exchange = Message(flag); new StringExpression(expression).Evaluate(exchange); exchange.In.Headers["n"].Should().Be(nAfter); } [Fact] public void NullCoalesce_AFaultOnTheRightSide_HappensOnlyWhenTheLeftIsNull() { new StringExpression("header.flag ?? bean:svc.Check()").Evaluate(Message(true)).Should().Be(true); var act = () => new StringExpression("header.missing ?? bean:svc.Check()").Evaluate(Message(true)); act.Should().Throw().WithMessage("*has no route context*"); } [Theory] [InlineData("header.missing ?? 'default'", "default")] [InlineData("header.flag ?? 'default'", true)] [InlineData("header.n ?? 5", 0)] public void NullCoalesce_TheValues_AreLeftOrRight(string expression, object expected) { new StringExpression(expression).Evaluate(Message(true)).Should().Be(expected); } [Theory] [InlineData("null AND 'x'", false)] [InlineData("'x' AND 1", true)] [InlineData("0 OR 'no'", false)] [InlineData("0 OR 'anything'", true)] [InlineData("'yes' AND 'on'", true)] [InlineData("header.missing OR header.flag", true)] public void TheValues_AreTheTruthinessRule(string expression, bool expected) { new StringExpression(expression).Evaluate(Message(true)).Should().Be(expected); } [Theory] [InlineData("header.n++", 0, 1)] [InlineData("++header.n", 1, 1)] [InlineData("header.n--", 0, -1)] public void TheInterpretedForm_IsTheCompiledOne_IncrementsWriteBack(string expression, int returns, int nAfter) { // Findings register row 27: Node.Evaluate used to be a second evaluator whose ++/-- did not write back. var exchange = Message(true); var node = new Parser(new Tokenizer(expression).GetAllTokens()).Parse(); Convert.ToInt32(node.Evaluate(exchange)).Should().Be(returns); exchange.In.Headers["n"].Should().BeEquivalentTo(nAfter); } [Theory] [InlineData("header.flag AND bean:svc.Check()", false, false)] [InlineData("header.flag OR bean:svc.Check()", true, false)] [InlineData("header.flag AND bean:svc.Check()", true, true)] [InlineData("header.flag OR bean:svc.Check()", false, true)] public void TheInterpretedForm_ShortCircuitsTheSameWay(string expression, bool flag, bool rightRuns) { // The right side fails when it runs (no route context for the bean: call), which shows whether it ran. var node = new Parser(new Tokenizer(expression).GetAllTokens()).Parse(); var act = () => node.Evaluate(Message(flag)); if (rightRuns) act.Should().Throw().WithMessage("*has no route context*"); else act.Should().NotThrow(); } } Path: redb-route/tests/redb.Route.Tests/Expressions/MemberNameCaseTests.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/Expressions/MemberNameCaseTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Expressions; namespace redb.Route.Tests.Expressions; /// /// A path step names a member case-insensitively, and the exact case wins when several members differ only in case. A /// redb object has both Id and the JSON-named id: ${body.Id} failed with "Ambiguous match found". /// [Collection("ExpressionResolver")] public class MemberNameCaseTests : IDisposable { public MemberNameCaseTests() => ExpressionResolver.ClearAllCaches(); public void Dispose() { ExpressionResolver.ClearAllCaches(); GC.SuppressFinalize(this); } private static object? Evaluate(string expression, object body) => new StringExpression(expression).Evaluate(new Exchange(new Message(body))); /// The shape of a redb object: a property and its JSON-named twin, and the props. public sealed class TwinNamed { #pragma warning disable IDE1006 // the lower-case name is the point of the test public long id { get; set; } = 7; #pragma warning restore IDE1006 public long Id { get => id + 1000; set => id = value; } public Reading Props { get; set; } = new(); public string Status = "open"; public string status = "closed"; } public sealed class Reading { public string Room { get; set; } = "kitchen"; } public sealed class Plain { public long Id { get; set; } = 42; } [Theory] [InlineData("${body.Id}", 1007L)] [InlineData("${body.id}", 7L)] [InlineData("body.Id", 1007L)] [InlineData("body.id", 7L)] public void The_exact_case_picks_one_of_two_members_that_differ_only_in_case(string expression, long expected) => Evaluate(expression, new TwinNamed()).Should().Be(expected); [Fact] public void A_nested_step_goes_through_the_twin_named_type() => Evaluate("${body.Props.Room}", new TwinNamed()).Should().Be("kitchen"); [Theory] [InlineData("${body.Status}", "open")] [InlineData("${body.status}", "closed")] public void Fields_follow_the_same_rule(string expression, string expected) => Evaluate(expression, new TwinNamed()).Should().Be(expected); [Theory] [InlineData("${body.Id}")] [InlineData("${body.id}")] [InlineData("${body.ID}")] public void A_single_member_is_found_in_any_case(string expression) => Evaluate(expression, new Plain()).Should().Be(42L); [Fact] public void A_case_that_matches_neither_twin_exactly_fails_naming_both() { var evaluate = () => Evaluate("${body.ID}", new TwinNamed()); evaluate.Should().Throw().Where(e => Describe(e).Contains("Id, id") || Describe(e).Contains("id, Id")); } private static string Describe(Exception e) => e.InnerException is null ? e.Message : e.Message + " " + Describe(e.InnerException); } Path: redb-route/tests/redb.Route.Tests/Expressions/MessageHistoryFunctionTests.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/Expressions/MessageHistoryFunctionTests.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Configuration; using redb.Route.Core; using redb.Route.Expressions; using redb.Route.Expressions.Ast; using redb.Route.Predicates; namespace redb.Route.Tests.Expressions; /// /// messageHistory(kind) — the trail an exchange left through the route as a value in the /// expression language, so markup (which has no lambdas) can log it and branch on it. /// public class MessageHistoryFunctionTests { private static IExchange ExchangeWithHistory(params (string Node, string Label, double Ms)[] steps) { var exchange = new Exchange(new Message("payload")) { RouteId = "orders" }; foreach (var (node, label, ms) in steps) MessageHistory.Append(exchange, new MessageHistoryEntry("orders", node, label, ms)); return exchange; } private static object? Interpreted(string expression, IExchange exchange) => new Parser(new Tokenizer(expression).GetAllTokens()).Parse().Evaluate(exchange); private static string Template(string expression, IExchange exchange) => ExpressionResolver.ProcessTemplate(expression, exchange); // ── The shapes ─────────────────────────────────────────────────── [Fact] public void Table_IsTheDefault_AndListsEveryStep() { var exchange = ExchangeWithHistory(("s1", "log", 1.5), ("s2", "to(http)", 40)); var byDefault = Template("${messageHistory()}", exchange); var explicitKind = Template("${messageHistory('table')}", exchange); byDefault.Should().Be(explicitKind); byDefault.Should().Contain("orders").And.Contain("log").And.Contain("to(http)"); } [Fact] public void Compact_IsOneLine_InOrder() { var exchange = ExchangeWithHistory(("s1", "log", 1), ("s2", "choice", 2), ("s3", "to(http)", 3)); Template("${messageHistory('compact')}", exchange).Should().Be("log > choice > to(http)"); } [Fact] public void Json_CarriesNodeAndElapsed() { var exchange = ExchangeWithHistory(("s1", "log", 2.5)); var json = Template("${messageHistory('json')}", exchange); json.Should().StartWith("[").And.Contain("\"routeId\":\"orders\"") .And.Contain("\"label\":\"log\"").And.Contain("\"elapsedMs\":2.5"); } // ── The numbers: the point of the whole function for markup ────── [Fact] public void Numbers_AnswerCountTotalAndSlowest() { var exchange = ExchangeWithHistory(("s1", "log", 1), ("s2", "to(http)", 40), ("s3", "save", 9)); Interpreted("messageHistory('count')", exchange).Should().Be(3); Convert.ToDouble(Interpreted("messageHistory('totalMs')", exchange)).Should().BeApproximately(50, 0.001); Convert.ToDouble(Interpreted("messageHistory('slowestMs')", exchange)).Should().BeApproximately(40, 0.001); Interpreted("messageHistory('slowest')", exchange).Should().Be("to(http)"); Interpreted("messageHistory('lastNode')", exchange).Should().Be("save"); } [Fact] public void SlowestMs_WorksAsAPredicate_InBothEngineBranches() { var slow = ExchangeWithHistory(("s1", "log", 1), ("s2", "to(http)", 800)); var quick = ExchangeWithHistory(("s1", "log", 1), ("s2", "to(http)", 5)); PredicateFactory.FromString("messageHistory('slowestMs') > 500").Matches(slow).Should().BeTrue(); PredicateFactory.FromString("messageHistory('slowestMs') > 500").Matches(quick).Should().BeFalse(); Interpreted("messageHistory('slowestMs') > 500", slow).Should().Be(true); } // ── History off: the one place this function does not fail loud ── [Fact] public void HistoryOff_GivesEmptyStringAndZero_NotAFailure() { var exchange = new Exchange(new Message("payload")) { RouteId = "orders" }; Template("${messageHistory()}", exchange).Should().BeEmpty(); Template("${messageHistory('compact')}", exchange).Should().BeEmpty(); Interpreted("messageHistory('count')", exchange).Should().Be(0); Convert.ToDouble(Interpreted("messageHistory('slowestMs')", exchange)).Should().Be(0); Interpreted("messageHistory('slowest')", exchange).Should().Be(string.Empty); } // ── An authoring error still fails loud ────────────────────────── [Fact] public void UnknownKind_Throws_WithTheKnownNames() { var exchange = ExchangeWithHistory(("s1", "log", 1)); var act = () => Template("${messageHistory('slowest-step')}", exchange); act.Should().Throw().WithMessage("*messageHistory()*slowest-step*"); } // ── End to end: a route logs its own trail ─────────────────────── [Fact] public async Task Route_LogsTheTrail_ThroughTheTemplate() { var logged = new List(); var context = new RouteContext(options: new RouteEngineOptions { EnableMessageHistory = true }); context.AddRoutes(r => r .From("direct://mh-fn-in") .RouteId("mh-fn") .Log("trail: ${messageHistory('compact')}", LogLevel.Information) .Process(ex => logged.Add(ExpressionResolver.ProcessTemplate("${messageHistory('compact')}", ex)))); await context.Start(); try { var producer = context.GetEndpoint("direct://mh-fn-in").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("x"))); logged.Should().ContainSingle(); logged[0].Should().NotBeEmpty("the route ran with message history enabled"); } finally { await context.DisposeAsync(); } } } Path: redb-route/tests/redb.Route.Tests/Expressions/MethodCallTests.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/Expressions/MethodCallTests.cs ---- using AwesomeAssertions; using redb.Route.Core; using redb.Route.Expressions; using redb.Route.Predicates; namespace redb.Route.Tests.Expressions; /// A value with methods of its own, for reflection calls. public sealed class MethodTarget { public string Greet(string name) => "hi " + name; public long Twice(long value) => value * 2; public string Boom() => throw new InvalidOperationException("boom"); public string Name => "target"; } /// /// Method calls on values in the AST (findings register row 28, step 28a): the built-in dot helpers, a public method /// of the value's type outside the sandbox, a null value giving null, and a method that throws or does not exist as a /// positioned error instead of a silent null. /// public sealed class MethodCallTests { private static Exchange Message() { var exchange = new Exchange(new Message("payload")); exchange.In.Headers["s"] = "Hello World"; exchange.In.Headers["list"] = new List { 3, 5 }; exchange.In.Headers["o"] = new MethodTarget(); return exchange; } private static object? Value(string expression) => ExpressionResolver.GetCompiledValueExpressionWithAst(expression)(Message()); [Theory] [InlineData("header.s.length()", 11)] [InlineData("header.s.toUpper()", "HELLO WORLD")] [InlineData("header.s.toLower()", "hello world")] [InlineData("header.s.substring(0, 5)", "Hello")] [InlineData("header.s.replace('o', '0')", "Hell0 W0rld")] [InlineData("header.s.indexOf('W')", 6)] [InlineData("header.s.startsWith('Hell')", true)] [InlineData("header.s.endsWith('x')", false)] [InlineData("header.s.contains('lo W')", true)] [InlineData("header.list.contains(5)", true)] [InlineData("header.list.count()", 2)] [InlineData("upper(header.s).length()", 11)] public void TheDotHelpers(string expression, object expected) { Value(expression).Should().Be(expected); } [Theory] [InlineData("header.s.length() > 10", true)] [InlineData("header.s.toUpper() == 'HELLO WORLD'", true)] public void InACondition(string condition, bool expected) { PredicateFactory.FromString(condition).Matches(Message()).Should().Be(expected); } [Fact] public void InATemplate() { ExpressionResolver.ProcessTemplate("[${header.s.toUpper()}]", Message()).Should().Be("[HELLO WORLD]"); } [Fact] public void APublicMethodOfTheValue_IsCalled_WithArgumentsConverted() { Value("header.o.Greet('ann')").Should().Be("hi ann"); Value("header.o.Twice(21)").Should().Be(42L, "the int literal converts to the long parameter"); } [Fact] public void ANullValue_GivesNull() { Value("header.missing.toUpper()").Should().BeNull(); } [Fact] public void AMethodThatThrows_IsAPositionedError() { var act = () => Value("header.o.Boom()"); act.Should().Throw() .WithMessage("header.o.Boom() at position 1 threw InvalidOperationException: boom") .WithInnerException(); } [Fact] public void AMethodTheTypeDoesNotHave_IsAnError() { var act = () => Value("header.s.nosuch()"); act.Should().Throw().WithMessage("'nosuch' is not a method of String at position 1 (in header.s.nosuch())."); } [Fact] public void InABareValueExpression_TheSameError() { // Step 28b: the bare value path is the AST's too; the older compiler swallowed the exception into null. var act = () => ExpressionResolver.GetCompiledValueExpression("header.o.Boom()")(Message()); act.Should().Throw().WithMessage("header.o.Boom() at position 1 threw InvalidOperationException: boom"); } [Fact] public void TheWrongNumberOfArguments_IsAnError() { var act = () => Value("header.o.Greet()"); act.Should().Throw().WithMessage("'Greet' of MethodTarget takes 1 argument(s), not 0, at position 1 (in header.o.Greet())."); } [Fact] public void UnderTheSandbox_AReflectionCallIsRefused_TheHelpersAreNot() { using var sandbox = ExpressionSandbox.Enter(); Value("header.s.toUpper()").Should().Be("HELLO WORLD"); var act = () => Value("header.o.Greet('ann')"); act.Should().Throw(); } } Path: redb-route/tests/redb.Route.Tests/Expressions/MixedTypeEqualityTests.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/Expressions/MixedTypeEqualityTests.cs ---- using AwesomeAssertions; using redb.Route.Core; using redb.Route.Expressions; using redb.Route.Predicates; namespace redb.Route.Tests.Expressions; /// /// Equality of numbers of different types, and of a number with a numeric string (findings register row 31): equal /// only when the values are equal. Until the fix a mixed pair was equal whenever the left value was the smaller one. /// Covered for ==, !=, in, not in and the collection contains(), each pair equal and unequal, in both orders. /// public sealed class MixedTypeEqualityTests { /// Mixed pairs: the left header value, the right header value, whether they are equal. public static TheoryData Pairs => new() { { 3, 3.0, true }, { 3, 5.0, false }, { 5, 3.0, false }, { 3, 3m, true }, { 3, 5m, false }, { 5, 3m, false }, { 3L, 3, true }, { 3L, 5, false }, { 5L, 3, false }, { 3, "3", true }, { 3, "5", false }, { 5, "3", false }, { 2.5, "2.5", true }, { 2.5, "7.5", false }, { 7.5, "2.5", false }, { 2.5m, "2.50", true }, { 2.5m, "7.5", false }, { 9007199254740993L, 9007199254740992m, false }, // beyond double precision: decimal keeps the values apart { 0.1, 0.1f, false }, // a float widens to a double that is not 0.1 }; private static Exchange Message(object left, object right) { var exchange = new Exchange(new Message("x")); exchange.In.Headers["l"] = left; exchange.In.Headers["r"] = right; exchange.In.Headers["list"] = new List { right }; return exchange; } private static bool Condition(string condition, Exchange exchange) => PredicateFactory.FromString(condition).Matches(exchange); [Theory] [MemberData(nameof(Pairs))] public void Equals_BothOrders(object left, object right, bool equal) { Condition("header.l == header.r", Message(left, right)).Should().Be(equal); Condition("header.r == header.l", Message(left, right)).Should().Be(equal); } [Theory] [MemberData(nameof(Pairs))] public void NotEquals_BothOrders(object left, object right, bool equal) { Condition("header.l != header.r", Message(left, right)).Should().Be(!equal); Condition("header.r != header.l", Message(left, right)).Should().Be(!equal); } [Theory] [MemberData(nameof(Pairs))] public void In_AndNotIn(object left, object right, bool equal) { Condition("header.l in header.list", Message(left, right)).Should().Be(equal); Condition("header.l not in header.list", Message(left, right)).Should().Be(!equal); } [Theory] [InlineData("${header.ints.contains('5')}", false)] [InlineData("${header.ints.contains('3')}", true)] [InlineData("${header.doubles.contains(1)}", false)] [InlineData("${header.doubles.contains(7)}", true)] public void CollectionContains(string template, bool expected) { var exchange = new Exchange(new Message("x")); exchange.In.Headers["ints"] = new List { 3 }; exchange.In.Headers["doubles"] = new List { 7.0 }; new StringExpression(template).Evaluate(exchange).Should().Be(expected); } [Theory] [InlineData("header.b == 5.0", false)] [InlineData("header.b == 3.0", true)] [InlineData("header.b == '5'", false)] [InlineData("header.b == '3'", true)] [InlineData("header.b in (5.0, '7')", false)] [InlineData("header.b in (5.0, '3')", true)] public void AgainstLiterals(string condition, bool expected) { var exchange = new Exchange(new Message("x")); exchange.In.Headers["b"] = 3; Condition(condition, exchange).Should().Be(expected); } } Path: redb-route/tests/redb.Route.Tests/Expressions/NamespacedCallGrammarTests.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/Expressions/NamespacedCallGrammarTests.cs ---- using AwesomeAssertions; using redb.Route.Core; using redb.Route.Expressions; using redb.Route.Expressions.Ast; using redb.Route.Predicates; namespace redb.Route.Tests.Expressions; /// /// The grammar of a namespaced call, bean:name.Method(args) (stage 2 step c): the namespace token, the target /// with dashed registry names, the required method, ${...} in the arguments only, the ternary edge, both /// dispatchers reaching the AST. /// public sealed class NamespacedCallGrammarTests { private static (TokenType, string)[] Tokens(string expression) => [.. new Tokenizer(expression).GetAllTokens().Where(t => t.Type != TokenType.Eof).Select(t => (t.Type, t.Value))]; private static AstNode Parse(string expression) => new Parser(new Tokenizer(expression).GetAllTokens()).Parse(); [Fact] public void Namespace_IsOneToken_AndTheTargetFollows() { var tokens = Tokens("bean:svc.Check(body)"); tokens.Select(t => t.Item1).Should().Equal( TokenType.Namespace, TokenType.Function, TokenType.LeftParen, TokenType.Identifier, TokenType.RightParen); tokens[0].Item2.Should().Be("bean"); tokens[1].Item2.Should().Be("svc.Check"); } [Fact] public void DashedRegistryName_IsPartOfTheTarget() { var call = Parse("bean:seen-orders.Check()").Should().BeOfType().Subject; call.Reference.Should().Be("seen-orders"); call.Method.Should().Be("Check"); call.Arguments.Should().BeEmpty(); } [Fact] public void MinusAfterTheCall_IsTheOperator() { Tokens("bean:svc.Count()-1").Select(t => t.Item1).Should().Equal( TokenType.Namespace, TokenType.Function, TokenType.LeftParen, TokenType.RightParen, TokenType.Operator, TokenType.Number); // The one shape a reader may misread: without parentheses the method ends at the dash. Tokens("bean:svc.Count-1").Should().Equal( (TokenType.Namespace, "bean"), (TokenType.Identifier, "svc.Count"), (TokenType.Operator, "-"), (TokenType.Number, "1")); } [Fact] public void MethodWithoutParentheses_HasNoArguments() { var call = Parse("bean:svc.Total").Should().BeOfType().Subject; call.Reference.Should().Be("svc"); call.Method.Should().Be("Total"); call.Arguments.Should().BeEmpty(); } [Theory] [InlineData("bean:svc")] [InlineData("bean:svc(body)")] [InlineData("bean:svc.(body)")] public void TheMethod_IsRequired(string expression) { var act = () => Parse(expression); act.Should().Throw() .WithMessage("a bean: call names its method: bean:svc.Method(...) (position 1 within the expression)."); } [Fact] public void PlaceholderInTheArguments_IsTheTypedValueOfItsExpression() { var call = Parse("bean:svc.Check(${header.a}, 'x', ${body})").Should().BeOfType().Subject; call.Arguments.Should().HaveCount(3); call.Arguments[0].Should().BeOfType().Which.Name.Should().Be("header.a"); call.Arguments[2].Should().BeOfType().Which.Name.Should().Be("body"); } [Fact] public void PlaceholderOutsideBeanArguments_IsRefused() { var act = () => Parse("header.a + ${header.b}"); act.Should().Throw() .WithMessage("${...} inside an expression is supported only in the arguments of a bean: call (position 12 within the expression)."); } [Fact] public void Ternary_WithSpaces_ReadsAsBefore() { Tokens("flag ? bean : other").Select(t => t.Item1).Should().Equal( TokenType.Identifier, TokenType.Operator, TokenType.Identifier, TokenType.Colon, TokenType.Identifier); } [Fact] public void Ternary_WithoutSpaces_BeforeAName_IsANamespacedCall() { // Documented edge: "bean" written against a colon and a name is the namespace. Write spaces in a ternary // whose branch is a variable named bean. var act = () => Parse("flag?bean:other"); act.Should().Throw().WithMessage("a bean: call names its method: bean:other.Method(...)*"); } [Theory] [InlineData("${bean:svc.Check(body)}")] [InlineData("${bean:svc.Check(${body})}")] [InlineData("total: ${bean:pricing-rules.Gross(header.qty, header.price)}")] public void TemplateHole_ReachesTheAst(string template) { // Only the AST knows the namespace: another path would read the hole as a property and give null. The call // site's own error, raised on an exchange without a context, proves the AST compiled it. var expression = new StringExpression(template); expression.Invoking(e => e.Evaluate(new Exchange())) .Should().Throw().WithMessage("*has no route context*"); } [Theory] [InlineData("bean:svc.IsGold(body)")] [InlineData("bean:svc.IsGold(body) == true")] [InlineData("header.vip && bean:svc.IsGold(body)")] public void BareExpression_ReachesTheAst_ThroughBothDispatchers(string expression) { var condition = PredicateFactory.FromString(expression); var value = ExpressionResolver.GetCompiledValueExpression(expression); var exchange = new Exchange(); exchange.In.Headers["vip"] = true; condition.Invoking(c => c.Matches(exchange)) .Should().Throw().WithMessage("*has no route context*"); value.Invoking(v => v(exchange)) .Should().Throw().WithMessage("*has no route context*"); } [Fact] public void BeanInsideAQuotedLiteral_IsText() { new StringExpression("${'bean:svc.Check()'}").Evaluate(new Exchange()).Should().Be("bean:svc.Check()"); } [Fact] public void LoneQuoteAtTheEnd_IsAPositionedError() { var act = () => ExpressionResolver.GetCompiledValueExpressionWithAst("header.a == '"); act.Should().Throw() .WithMessage("*unterminated string literal starting at position 13 within the expression \"header.a == '\"."); } [Fact] public void UnterminatedLiteralWithContent_IsAPositionedError() { // Findings register row 17, decided: it used to be read truncated ('abc as "ab"), silently. var act = () => ExpressionResolver.GetCompiledValueExpressionWithAst("header.a == 'abc"); act.Should().Throw() .WithMessage("*unterminated string literal starting at position 13 within the expression \"header.a == 'abc\"."); } [Theory] [InlineData("header.s == 'Hello World'")] [InlineData("concat('a', \"b\")")] [InlineData("header.s == 'it\\'s'")] public void ClosedLiterals_ReadAsBefore(string expression) { var act = () => ExpressionResolver.GetCompiledValueExpressionWithAst(expression); act.Should().NotThrow(); } } Path: redb-route/tests/redb.Route.Tests/Expressions/PathSpellingTests.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/Expressions/PathSpellingTests.cs ---- using AwesomeAssertions; using redb.Route.Core; using redb.Route.Expressions; namespace redb.Route.Tests.Expressions; /// /// Apache Camel's ${jsonpath:...} and ${xpath:...} (findings register row 34 point 2): spellings of /// jpath('...') and xpath('...') as a whole placeholder. Until 4.7.0 they rendered empty. /// public sealed class PathSpellingTests { private static Exchange Json() => new(new Message("""{"order":{"id":"A-1","amount":12.5,"items":["a","b"]}}""")); private static Exchange Xml() => new(new Message("A-1ab")); [Theory] [InlineData("${jsonpath:$.order.id}", "A-1")] [InlineData("${jsonpath: $.order.id }", "A-1")] [InlineData("id=${jsonpath:$.order.id}", "id=A-1")] public void Jsonpath_IsJpath(string template, string expected) { ExpressionResolver.ProcessTemplate(template, Json()).Should().Be(expected); ExpressionResolver.ProcessTemplate(template.Replace("jsonpath:$.order.id", "jpath('$.order.id')").Replace("jsonpath: $.order.id ", "jpath('$.order.id')"), Json()) .Should().Be(expected, "the spelling and the function agree"); } [Fact] public void Jsonpath_AWholePlaceholderKeepsTheValue_AndTakesAFormat() { new StringExpression("${jsonpath:$.order.amount}").Evaluate(Json()).Should() .Be(new StringExpression("${jpath('$.order.amount')}").Evaluate(Json())); ExpressionResolver.ProcessTemplate("${jsonpath:$.order.amount:F2}", Json()).Should().Be("12.50"); } [Fact] public void Xpath_IsXpath() { ExpressionResolver.ProcessTemplate("${xpath://order/id}", Xml()) .Should().Be(ExpressionResolver.ProcessTemplate("${xpath('//order/id')}", Xml())); ExpressionResolver.ProcessTemplate("id=${xpath://order/id/text()}", Xml()).Should().StartWith("id=A-1"); } [Theory] [InlineData("${jsonpath:}")] [InlineData("${xpath: }")] public void ASpellingWithoutAPath_IsAnError(string template) { var act = () => ExpressionResolver.ProcessTemplate(template, Json()); act.Should().Throw().WithMessage("*names no path*"); } } Path: redb-route/tests/redb.Route.Tests/Expressions/PredicateBranchMatrixTests.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/Expressions/PredicateBranchMatrixTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Expressions; using redb.Route.Predicates; namespace redb.Route.Tests.Expressions; /// /// Characterisation matrix for the ways a string becomes a boolean in this library. /// It is a permanent part of the suite: it pins down what each path does, so a change to one of /// them shows up here instead of surfacing as a silently mis-routed message. /// /// Value position — plus the DSL truthiness rule. /// This is what Expr(...) in SetBody / SetHeader does: an explicit /// expression, evaluated and read for truthiness. Since 2026-08-28 it reads operators /// whatever the spacing, like every other position. /// Condition position — , what Filter, /// When, LoopWhile and Validate use for a string. A ${...} /// template stays a template; anything else is compiled by the AST parser. /// /// [Collection("ExpressionResolver")] public class PredicateBranchMatrixTests { /// What a path did with a condition. public enum Outcome { /// The path produced false. False, /// The path produced true. True, /// The path refused to compile the condition. Throws } private static IExchange CreateExchange() { var exchange = new Exchange(new Message("payload")); exchange.In.Headers["a"] = 42; exchange.In.Headers["b"] = 3; exchange.In.Headers["flag"] = true; exchange.In.Headers["s"] = "hello"; exchange.In.Headers["obj"] = new List { 1, 2, 3, 4, 5 }; exchange.Properties["count"] = 7; exchange.Properties["flag"] = false; exchange.Properties["items"] = new List { "p", "q", "r" }; exchange.Properties["name"] = "abcd"; return exchange; } /// /// condition, value position, condition position, the answer a reader of the condition would /// expect. The hand-written logical branch used to be a fourth column; it was removed with /// the branch itself on 2026-08-28 (one language, one parser). /// public static TheoryData Matrix() => new() { // value condition expected { "header.a > 10", Outcome.True, Outcome.True, Outcome.True }, { "header.a>10", Outcome.True, Outcome.True, Outcome.True }, { "header.a >= 10", Outcome.True, Outcome.True, Outcome.True }, { "header.a>=10", Outcome.True, Outcome.True, Outcome.True }, { "header.a == 'x'", Outcome.False, Outcome.False, Outcome.False }, { "header.a=='x'", Outcome.False, Outcome.False, Outcome.False }, { "header.a != 'x'", Outcome.True, Outcome.True, Outcome.True }, { "header.a>10 AND header.b<5", Outcome.True, Outcome.True, Outcome.True }, { "header.a > 10 AND header.b < 5", Outcome.True, Outcome.True, Outcome.True }, { "property.count > 5 OR property.flag", Outcome.True, Outcome.True, Outcome.True }, { "count(property.items) > 2", Outcome.True, Outcome.True, Outcome.True }, { "count(property.items)>2", Outcome.True, Outcome.True, Outcome.True }, { "length(property.name) > 3 ? true : false", Outcome.True, Outcome.True, Outcome.True }, { "NOT header.flag", Outcome.False, Outcome.False, Outcome.False }, { "!header.flag", Outcome.False, Outcome.False, Outcome.False }, { "header.flag", Outcome.True, Outcome.True, Outcome.True }, { "header.missing", Outcome.False, Outcome.False, Outcome.False }, { "${header.flag}", Outcome.True, Outcome.True, Outcome.True }, { "header.a\t>\t10", Outcome.True, Outcome.True, Outcome.True }, { "header.a > 10", Outcome.True, Outcome.True, Outcome.True }, { "(header.a > 10) AND (header.b < 5)", Outcome.True, Outcome.True, Outcome.True }, { "(header.a>10) AND (header.b<5)", Outcome.True, Outcome.True, Outcome.True }, { "header.s == 'a > b'", Outcome.False, Outcome.False, Outcome.False }, { "header.s == 'a AND b'", Outcome.False, Outcome.False, Outcome.False }, { "contains(header.s, 'ell')", Outcome.True, Outcome.True, Outcome.True }, { "header.a + header.b > 40", Outcome.True, Outcome.True, Outcome.True }, }; [Theory] [MemberData(nameof(Matrix))] public void ValuePosition_MatchesRecordedBehaviour(string condition, Outcome value, Outcome _, Outcome __) => Run(() => RouteTruthiness.ToBoolean(new StringExpression(condition).Evaluate(CreateExchange()))) .Should().Be(value); [Theory] [MemberData(nameof(Matrix))] public void ConditionPosition_MatchesRecordedBehaviour(string condition, Outcome _, Outcome actual, Outcome __) => Run(() => PredicateFactory.FromString(condition).Matches(CreateExchange())) .Should().Be(actual); /// /// The point of the whole exercise: the condition position answers what a reader of the /// condition expects, for every row of the matrix. /// [Theory] [MemberData(nameof(Matrix))] public void ConditionPosition_AnswersWhatTheConditionSays(string condition, Outcome _, Outcome actual, Outcome expected) { actual.Should().Be(expected, "the condition position is the one path that has to be right; " + $"'{condition}' is documented as {actual} but reads as {expected}"); Run(() => PredicateFactory.FromString(condition).Matches(CreateExchange())).Should().Be(expected); } /// /// A comparison against a CLR member behind a header or property resolves through the smart /// resolvers (literal name first, then the member path) in the condition position. This used /// to be an AST gap — the identifier resolver did a flat dictionary lookup of the whole /// dotted tail — and this test pinned the gap until it was closed; now it pins the fix. /// [Theory] [InlineData("header.obj.Count > 3")] [InlineData("property.items.Count > 2")] [InlineData("header.s.Length > 3")] public void MemberAccessOnObject_IsResolvedInTheConditionPosition(string condition) => Run(() => PredicateFactory.FromString(condition).Matches(CreateExchange())).Should().Be(Outcome.True); private static Outcome Run(Func evaluate) { try { return evaluate() ? Outcome.True : Outcome.False; } catch (Exception) { return Outcome.Throws; } } } Path: redb-route/tests/redb.Route.Tests/Expressions/PredicateTests.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/Expressions/PredicateTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Expressions; using redb.Route.Predicates; namespace redb.Route.Tests.Expressions; /// /// Tests for all 19 Predicate classes. /// public class PredicateTests { private static IExchange CreateExchange(object? body = null) => new Exchange(new Message(body)); // ── EqualsPredicate ── [Fact] public void Equals_Matches_WhenEqual() { var pred = new EqualsPredicate(new BodyExpression(), "hello"); pred.Matches(CreateExchange("hello")).Should().BeTrue(); } [Fact] public void Equals_DoesNotMatch_WhenNotEqual() { var pred = new EqualsPredicate(new BodyExpression(), "hello"); pred.Matches(CreateExchange("world")).Should().BeFalse(); } // ── NotEqualsPredicate ── [Fact] public void NotEquals_Matches_WhenDifferent() { var pred = new NotEqualsPredicate(new BodyExpression(), "hello"); pred.Matches(CreateExchange("world")).Should().BeTrue(); } [Fact] public void NotEquals_DoesNotMatch_WhenSame() { var pred = new NotEqualsPredicate(new BodyExpression(), "hello"); pred.Matches(CreateExchange("hello")).Should().BeFalse(); } // ── GreaterThanPredicate ── [Fact] public void GreaterThan_Matches_WhenGreater() { var pred = new GreaterThanPredicate(new BodyExpression(), 5); pred.Matches(CreateExchange(10)).Should().BeTrue(); } [Fact] public void GreaterThan_DoesNotMatch_WhenLessOrEqual() { var pred = new GreaterThanPredicate(new BodyExpression(), 5); pred.Matches(CreateExchange(5)).Should().BeFalse(); } // ── GreaterThanOrEqualPredicate ── [Fact] public void GreaterThanOrEqual_Matches_WhenEqual() { var pred = new GreaterThanOrEqualPredicate(new BodyExpression(), 5); pred.Matches(CreateExchange(5)).Should().BeTrue(); } // ── LessThanPredicate ── [Fact] public void LessThan_Matches_WhenLess() { var pred = new LessThanPredicate(new BodyExpression(), 10); pred.Matches(CreateExchange(5)).Should().BeTrue(); } [Fact] public void LessThan_DoesNotMatch_WhenGreaterOrEqual() { var pred = new LessThanPredicate(new BodyExpression(), 10); pred.Matches(CreateExchange(10)).Should().BeFalse(); } // ── LessThanOrEqualPredicate ── [Fact] public void LessThanOrEqual_Matches_WhenEqual() { var pred = new LessThanOrEqualPredicate(new BodyExpression(), 10); pred.Matches(CreateExchange(10)).Should().BeTrue(); } // ── BetweenPredicate ── [Fact] public void Between_Matches_WhenInRange() { var pred = new BetweenPredicate(new BodyExpression(), 5, 15); pred.Matches(CreateExchange(10)).Should().BeTrue(); } [Fact] public void Between_Matches_WhenOnBoundary() { var pred = new BetweenPredicate(new BodyExpression(), 5, 15); pred.Matches(CreateExchange(5)).Should().BeTrue(); pred.Matches(CreateExchange(15)).Should().BeTrue(); } [Fact] public void Between_DoesNotMatch_WhenOutOfRange() { var pred = new BetweenPredicate(new BodyExpression(), 5, 15); pred.Matches(CreateExchange(20)).Should().BeFalse(); } // ── ContainsPredicate ── [Fact] public void Contains_Matches_WhenSubstringPresent() { var pred = new ContainsPredicate(new BodyExpression(), "world"); pred.Matches(CreateExchange("hello world")).Should().BeTrue(); } [Fact] public void Contains_DoesNotMatch_WhenAbsent() { var pred = new ContainsPredicate(new BodyExpression(), "xyz"); pred.Matches(CreateExchange("hello")).Should().BeFalse(); } // ── StartsWithPredicate ── [Fact] public void StartsWith_Matches() { var pred = new StartsWithPredicate(new BodyExpression(), "hel"); pred.Matches(CreateExchange("hello")).Should().BeTrue(); } [Fact] public void StartsWith_DoesNotMatch() { var pred = new StartsWithPredicate(new BodyExpression(), "xyz"); pred.Matches(CreateExchange("hello")).Should().BeFalse(); } // ── EndsWithPredicate ── [Fact] public void EndsWith_Matches() { var pred = new EndsWithPredicate(new BodyExpression(), "llo"); pred.Matches(CreateExchange("hello")).Should().BeTrue(); } // ── RegexPredicate ── [Fact] public void Regex_Matches() { var pred = new RegexPredicate(new BodyExpression(), @"^\d{3}$"); pred.Matches(CreateExchange("123")).Should().BeTrue(); } [Fact] public void Regex_DoesNotMatch() { var pred = new RegexPredicate(new BodyExpression(), @"^\d{3}$"); pred.Matches(CreateExchange("12")).Should().BeFalse(); } // ── InPredicate ── [Fact] public void In_Matches_WhenValueInList() { var pred = new InPredicate(new BodyExpression(), new object[] { "a", "b", "c" }); pred.Matches(CreateExchange("b")).Should().BeTrue(); } [Fact] public void In_DoesNotMatch_WhenAbsent() { var pred = new InPredicate(new BodyExpression(), new object[] { "a", "b", "c" }); pred.Matches(CreateExchange("d")).Should().BeFalse(); } // ── IsNullPredicate ── [Fact] public void IsNull_Matches_WhenNull() { var pred = new IsNullPredicate(new BodyExpression()); pred.Matches(CreateExchange(null)).Should().BeTrue(); } [Fact] public void IsNull_DoesNotMatch_WhenNotNull() { var pred = new IsNullPredicate(new BodyExpression()); pred.Matches(CreateExchange("value")).Should().BeFalse(); } // ── IsNotNullPredicate ── [Fact] public void IsNotNull_Matches_WhenNotNull() { var pred = new IsNotNullPredicate(new BodyExpression()); pred.Matches(CreateExchange("value")).Should().BeTrue(); } [Fact] public void IsNotNull_DoesNotMatch_WhenNull() { var pred = new IsNotNullPredicate(new BodyExpression()); pred.Matches(CreateExchange(null)).Should().BeFalse(); } // ── NotPredicate ── [Fact] public void Not_InvertsResult() { var inner = new DelegateExpression(ex => ex.In.Body?.ToString() == "hello"); var pred = new NotPredicate(inner); pred.Matches(CreateExchange("hello")).Should().BeFalse(); pred.Matches(CreateExchange("bye")).Should().BeTrue(); } // ── AndPredicate ── [Fact] public void And_MatchesWhenBothTrue() { var left = new DelegateExpression(ex => ex.In.Body is string s && s.Length > 2); var right = new LambdaPredicate(ex => ex.In.Body is string s && s.StartsWith("h")); var pred = new AndPredicate(left, right); pred.Matches(CreateExchange("hello")).Should().BeTrue(); } [Fact] public void And_DoesNotMatchWhenOneFalse() { var left = new DelegateExpression(_ => true); var right = new LambdaPredicate(_ => false); var pred = new AndPredicate(left, right); pred.Matches(CreateExchange("x")).Should().BeFalse(); } // ── OrPredicate ── [Fact] public void Or_MatchesWhenEitherTrue() { var left = new DelegateExpression(_ => false); var right = new LambdaPredicate(_ => true); var pred = new OrPredicate(left, right); pred.Matches(CreateExchange("x")).Should().BeTrue(); } [Fact] public void Or_DoesNotMatchWhenBothFalse() { var left = new DelegateExpression(_ => false); var right = new LambdaPredicate(_ => false); var pred = new OrPredicate(left, right); pred.Matches(CreateExchange("x")).Should().BeFalse(); } // ── LambdaPredicate ── [Fact] public void Lambda_ExecutesDelegate() { var pred = new LambdaPredicate(ex => (int)ex.In.Body! > 5); pred.Matches(CreateExchange(10)).Should().BeTrue(); pred.Matches(CreateExchange(3)).Should().BeFalse(); } // ── Condition strings (LogicalPredicate was removed with the second parser) ── [Fact] public void ConditionString_EvaluatesThroughThePredicateFactory() { var exchange = CreateExchange("body"); exchange.Properties["count"] = 10; var pred = PredicateFactory.FromString("property.count == 10"); pred.Matches(exchange).Should().BeTrue(); } // ── Async ── [Fact] public async Task Equals_MatchesAsync() { var pred = new EqualsPredicate(new BodyExpression(), "hello"); (await pred.MatchesAsync(CreateExchange("hello"))).Should().BeTrue(); } } Path: redb-route/tests/redb.Route.Tests/Expressions/RegistryRefTests.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/Expressions/RegistryRefTests.cs ---- using AwesomeAssertions; using redb.Route.Core; using redb.Route.Expressions; using redb.Route.Expressions.Ast; using redb.Route.Predicates; namespace redb.Route.Tests.Expressions; /// A registry object the ref: tests read. public sealed class ChatSettings { public string Style { get; set; } = "terse"; public override string ToString() => "style=" + Style; } /// /// ref:name of the expression language: the object registered under the whole name (dots and dashes /// included), as in Apache Camel; nothing is called or read on it; a missing name is an error in the bean: words; /// refused under the sandbox; looked up once per context; the ternary edge of bean: applies. /// public sealed class RegistryRefTests : IAsyncLifetime { private readonly RouteContext _context = new(); private readonly ChatSettings _settings = new(); public Task InitializeAsync() { _context.AddToRegistry("chat.settings", _settings); _context.AddToRegistry("seen-orders", new List { 1, 2 }); _context.AddToRegistry("limit", 5); return Task.CompletedTask; } public async Task DisposeAsync() => await _context.DisposeAsync(); private Exchange Message(params (string Key, object? Value)[] headers) { var exchange = new Exchange(new Message("payload")) { Context = _context }; foreach (var (key, value) in headers) exchange.In.Headers[key] = value; return exchange; } private static AstNode Parse(string expression) => new Parser(new Tokenizer(expression).GetAllTokens()).Parse(); [Theory] [InlineData("ref:chat.settings", "chat.settings")] [InlineData("ref:seen-orders", "seen-orders")] [InlineData("ref:limit-1", "limit-1")] public void TheWholeRun_IsTheName(string expression, string name) { Parse(expression).Should().BeOfType().Which.Reference.Should().Be(name); } [Fact] public void ASpaceBeforeAMinus_Subtracts() { new StringExpression("${ref:limit - 1}").Evaluate(Message()).Should().Be(4); } [Fact] public void AWholePlaceholder_KeepsTheObject() { new StringExpression("${ref:chat.settings}").Evaluate(Message()).Should().BeSameAs(_settings); } [Fact] public void InText_TheObjectIsRendered() { ExpressionResolver.ProcessTemplate("[${ref:chat.settings}]", Message()).Should().Be("[style=terse]"); } [Theory] [InlineData("ref:limit > 3", true)] [InlineData("header.n < ref:limit", true)] [InlineData("${ref:limit == 6}", false)] public void InACondition_BareAndTemplated(string condition, bool expected) { PredicateFactory.FromString(condition).Matches(Message(("n", 2))).Should().Be(expected); } [Fact] public void AsAnArgumentOfABeanCall() { _context.AddToRegistry("fmt", new RefFormatter()); new StringExpression("${bean:fmt.Describe(ref:chat.settings)}").Evaluate(Message()).Should().Be("terse"); } [Fact] public void AMissingName_NamesIt_InTheBeanWords() { var act = () => new StringExpression("${ref:absent.thing}").Evaluate(Message()); act.Should().Throw() .WithMessage("ref:absent.thing: 'absent.thing' is not in the context registry. Register it with AddToRegistry or a declaration."); } [Fact] public void AParenthesis_PointsToBean() { var act = () => Parse("ref:chat.settings()"); act.Should().Throw() .WithMessage("ref:chat.settings names a registry object and calls nothing; call a method with bean:chat.settings.Method(...) (position 1 within the expression)."); } [Fact] public void UnderTheSandbox_IsRefused() { var expression = new StringExpression("${ref:chat.settings}"); using var sandbox = ExpressionSandbox.Enter(); var act = () => expression.Evaluate(Message()); act.Should().Throw() .WithMessage("'ref:chat.settings' cannot be read here: the expression runs in a sandbox*not the registry or the process environment."); } [Fact] public void WithoutAContext_TheErrorSaysWhy() { var act = () => new StringExpression("${ref:limit}").Evaluate(new Exchange()); act.Should().Throw().WithMessage("*has no route context*"); } [Fact] public async Task OncePerContext_EachContextItsOwnObject() { await using var other = new RouteContext(); other.AddToRegistry("limit", 9); var expression = new StringExpression("${ref:limit}"); expression.Evaluate(Message()).Should().Be(5); _context.AddToRegistry("limit", 7); expression.Evaluate(Message()).Should().Be(5, "the object is looked up once per context"); expression.Evaluate(new Exchange(new Message("x")) { Context = other }).Should().Be(9); } [Fact] public void Ternary_WithSpaces_ReadsAsBefore() { new Tokenizer("flag ? ref : other").GetAllTokens().Where(t => t.Type != TokenType.Eof).Select(t => t.Type) .Should().Equal(TokenType.Identifier, TokenType.Operator, TokenType.Identifier, TokenType.Colon, TokenType.Identifier); } [Fact] public void Ternary_WithoutSpaces_BeforeAName_IsARegistryName() { // The documented edge of bean: holds for ref: as well. Write spaces in a ternary whose branch is named ref. new Tokenizer("flag?ref:other").GetAllTokens().Select(t => t.Type).Should().Contain(TokenType.Namespace); var act = () => Parse("flag?ref:other"); act.Should().Throw().WithMessage("*Colon*"); } } /// A bean that takes a registry object as an argument. public sealed class RefFormatter { public string Describe(ChatSettings settings) => settings.Style; } Path: redb-route/tests/redb.Route.Tests/Expressions/SandboxViolationTests.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/Expressions/SandboxViolationTests.cs ---- using AwesomeAssertions; using redb.Route.Expressions; namespace redb.Route.Tests.Expressions; /// /// The words of : a refused method call names the method and its type, /// a refused read (ref:name, env:NAME) names the spelling and no method, since it calls none. /// public sealed class SandboxViolationTests { [Fact] public void AMethodCall_NamesTheMethodAndTheType() { var exception = new ExpressionSandboxViolationException("Delete", typeof(FileInfo)); exception.Message.Should().StartWith("Method 'Delete' on FileInfo cannot be called here: the expression runs in a sandbox"); exception.Written.Should().Be("Delete"); exception.MethodName.Should().Be("Delete"); exception.TargetType.Should().Be(); } [Theory] [InlineData("ref:rules")] [InlineData("env:HOME")] public void ARead_NamesTheSpelling_AndNoMethod(string written) { var exception = new ExpressionSandboxViolationException(written); exception.Message.Should().Be( $"'{written}' cannot be read here: the expression runs in a sandbox (a template argument or expr()), " + "which reads the message and its values, not the registry or the process environment."); exception.Message.Should().NotContain("Method"); exception.Written.Should().Be(written); exception.TargetType.Should().BeNull(); } [Fact] public void AReadOfARegistryName_IsRefusedBeforeTheRegistryIsAsked() { // No context registers 'missing': under the sandbox the refusal comes first, so the registry is never read. var exchange = new redb.Route.Core.Exchange(new redb.Route.Core.Message("x")) { Context = new redb.Route.Core.RouteContext(), }; using var sandbox = ExpressionSandbox.Enter(); var act = () => new StringExpression("${ref:missing}").Evaluate(exchange); act.Should().Throw().Which.Written.Should().Be("ref:missing"); } } Path: redb-route/tests/redb.Route.Tests/Expressions/SetVerbExpressionFormTests.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/Expressions/SetVerbExpressionFormTests.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Expressions; using redb.Route.TestKit; using static redb.Route.Core.RouteBuilder; namespace redb.Route.Tests.Expressions; /// /// 4.0 removed the string forms SetBodyExpression(string) / SetHeaderExpression / /// SetPropertyExpression / TransformExpression(string). The removal was safe because the /// string form and Expr(...) already meant the same thing, form by form — proved by an equivalence grid over this corpus before the deletion. What /// survives is the invariant that grid protected: one engine, so the four verbs answer alike, and a /// whole-string placeholder keeps the CLR type of its value. /// [Collection("ExpressionResolver")] public class SetVerbExpressionFormTests { /// Forms that exercise the placeholder pipeline: whole-string, mixed, arithmetic, comparison, accessors, literals, jpath, explicit locale. public static TheoryData Templates => [ "${header.name}", "${header.count}", "${header.price}", "Hello ${header.name}!", "${header.first} ${header.last}", "${header.a + header.b}", "${header.count > 5}", "${header.count>5}", "${body}", "${header.Content-Type}", "${header.missing}", "${property.tenant}", "plain text", "${jpath($.id)}", "${format(header.price, 'N2', 'ru-RU')}", ]; private static Dictionary Headers() => new() { ["name"] = "world", ["count"] = 7, ["price"] = 19.95m, ["first"] = "Ada", ["last"] = "Lovelace", ["a"] = 2, ["b"] = 3, ["Content-Type"] = "application/json", }; private const string Body = """{"id": "DRV-1"}"""; [Theory] [MemberData(nameof(Templates))] public async Task TheFourVerbs_AgreeOnEveryForm(string template) { await using var ctx = new RouteContext().AddRoutes(b => { b.From("direct://body").SetBody(Expr(template)).To("mock://body"); b.From("direct://transform").Transform(Expr(template)).To("mock://transform"); b.From("direct://header").SetHeader("out", Expr(template)).To("mock://header"); b.From("direct://property").SetProperty("out", Expr(template)).To("mock://property"); }); await ctx.Start(); foreach (var target in new[] { "body", "transform", "header", "property" }) await ctx.SendBodyAndHeaders($"direct://{target}", Body, Headers()); var fromBody = ctx.Mock("mock://body").ReceivedExchanges[0].In.Body; var fromTransform = ctx.Mock("mock://transform").ReceivedExchanges[0].In.Body; var fromHeader = ctx.Mock("mock://header").ReceivedExchanges[0].In.Headers["out"]; var fromProperty = ctx.Mock("mock://property").ReceivedExchanges[0].Properties["out"]; fromTransform.Should().BeEquivalentTo(fromBody, "one engine serves every position"); fromHeader.Should().BeEquivalentTo(fromBody); fromProperty.Should().BeEquivalentTo(fromBody); fromTransform?.GetType().Should().Be(fromBody?.GetType()); fromHeader?.GetType().Should().Be(fromBody?.GetType()); fromProperty?.GetType().Should().Be(fromBody?.GetType()); } [Fact] public async Task AWholeStringPlaceholder_KeepsTheClrType_AndAMixedOneRendersInvariant() { await using var ctx = new RouteContext().AddRoutes(b => { b.From("direct://typed").SetBody(Expr("${header.price}")).To("mock://typed"); b.From("direct://mixed").SetBody(Expr("total ${header.price}")).To("mock://mixed"); }); await ctx.Start(); await ctx.SendBodyAndHeaders("direct://typed", null, Headers()); await ctx.SendBodyAndHeaders("direct://mixed", null, Headers()); ctx.Mock("mock://typed").ReceivedExchanges[0].In.Body.Should().Be(19.95m, "a whole-string placeholder is the value, not its text"); ctx.Mock("mock://mixed").ReceivedExchanges[0].In.Body.Should().Be("total 19.95", "text is invariant; ask for a locale with format(...)"); } [Fact] public async Task APlainStringIsALiteral_TheContentNeverDecides() { await using var ctx = new RouteContext().AddRoutes(b => b .From("direct://literal").SetBody("Hello ${header.name}").To("mock://literal")); await ctx.Start(); await ctx.SendBodyAndHeaders("direct://literal", null, Headers()); ctx.Mock("mock://literal").ReceivedExchanges[0].In.Body.Should().Be("Hello ${header.name}", "SetBody(string) is a literal body; the template form is SetBody(Expr(...))"); } } Path: redb-route/tests/redb.Route.Tests/Expressions/StatsFunctionTests.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/Expressions/StatsFunctionTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Expressions; namespace redb.Route.Tests.Expressions; /// /// stats(target, metric) — endpoint measurements as values in the expression language, /// so a route can branch on them: turn traffic away from a degraded /// endpoint, alarm on a cancellation storm, log its own counters without capturing the context. /// Built on ; every failure is an authoring error and says so /// loudly rather than routing messages on a silent null. /// [Collection("ExpressionResolver")] public sealed class StatsFunctionTests { private static async Task Started(RouteContext context, string uri) { await context.Start(); var producer = context.GetEndpoint(uri).CreateProducer(); await producer.Start(); return producer; } // ── Value position, both engine branches through the template ── [Fact] public async Task Reads_a_named_endpoints_counter_in_a_template() { await using var context = new RouteContext(); string? rendered = null; context.AddRoutes(r => r.From("direct:st-value").Process(e => rendered = ExpressionResolver.ProcessTemplate("${stats('direct:st-value', 'messagesIn')}", e))); var producer = await Started(context, "direct:st-value"); await producer.Process(new Exchange(new Message("m"))); rendered.Should().Be("1", "the exchange being processed has already been counted in"); } [Fact] public async Task Current_means_the_route_processing_the_exchange() { await using var context = new RouteContext(); string? health = null; context.AddRoutes(r => r.From("direct:st-current").RouteId("st-current").Process(e => health = ExpressionResolver.ProcessTemplate("${stats('current', 'health')}", e))); var producer = await Started(context, "direct:st-current"); await producer.Process(new Exchange(new Message("m"))); health.Should().Be("Healthy"); } // ── Condition position: the point of the exercise ── [Fact] public async Task A_route_can_turn_traffic_away_from_a_degraded_target() { await using var context = new RouteContext(); var reached = new List(); context.AddRoutes(r => { r.From("direct:st-target").RouteId("st-target") .Process(e => { if (Equals(e.In.Body, "boom")) throw new InvalidOperationException("down"); }); r.From("direct:st-guarded") .Filter("stats('direct:st-target', 'errors') == 0") .Process(_ => reached.Add("sent")) .EndFilter(); }); var guarded = await Started(context, "direct:st-guarded"); var target = context.GetEndpoint("direct:st-target").CreateProducer(); await target.Start(); await guarded.Process(new Exchange(new Message("m"))); var act = () => target.Process(new Exchange(new Message("boom"))); await act.Should().ThrowAsync(); await guarded.Process(new Exchange(new Message("m"))); reached.Should().Equal("sent"); } [Fact] public async Task The_interpreting_engine_branch_evaluates_stats_too() { // The format() lesson: a function that lives only in the compiled branch is a documented // lie. The template and Filter paths above compile; this drives AstNode.Evaluate directly. await using var context = new RouteContext(); object? result = null; context.AddRoutes(r => r.From("direct:st-interp").RouteId("st-interp").Process(e => { var tokens = new redb.Route.Expressions.Ast.Tokenizer("stats('current', 'messagesIn')").GetAllTokens(); var ast = new redb.Route.Expressions.Ast.Parser(tokens).Parse(); result = ast.Evaluate(e); })); var producer = await Started(context, "direct:st-interp"); await producer.Process(new Exchange(new Message("m"))); result.Should().Be(1L); } // ── Authoring errors are loud ── [Fact] public async Task An_unknown_metric_written_as_a_literal_fails_when_the_route_is_built() { await using var context = new RouteContext(); context.AddRoutes(r => r.From("direct:st-bad") .Filter("stats('current', 'erors') > 0") .Process(_ => { }) .EndFilter()); var act = () => context.Start(); (await act.Should().ThrowAsync()) .WithMessage("*unknown statistic 'erors'*", "a typo in a metric name must fail the build with the list of known names, not the first message"); } [Fact] public void An_exchange_that_never_entered_a_route_cannot_read_stats() { var act = () => ExpressionResolver.ProcessTemplate( "${stats('direct:x', 'errors')}", new Exchange(new Message("m"))); act.Should().Throw() .WithMessage("*carries no route context*"); } } Path: redb-route/tests/redb.Route.Tests/Expressions/StatsOtelFunctionTests.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/Expressions/StatsOtelFunctionTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Expressions; using redb.Route.Telemetry; namespace redb.Route.Tests.Expressions; /// /// stats('otel:instrument[@route][/step]', field) — the OpenTelemetry layer as values in the /// expression language (METRICS_IN_ROUTE_PLAN, open question 2). The EIP counters and /// .Metered() durations live only in that layer, so without this a markup route cannot see /// them at all. The in-process subscriber stays opt-in; asking for it without /// UseMetricsSnapshot() is an authoring error and says so. /// [Collection("ExpressionResolver")] public sealed class StatsOtelFunctionTests { private static async Task Started(RouteContext context, string uri) { await context.Start(); var producer = context.GetEndpoint(uri).CreateProducer(); await producer.Start(); return producer; } [Fact] public async Task Reads_a_metered_step_of_the_current_route() { var routeId = $"otel-fn-{Guid.NewGuid():N}"; await using var context = new RouteContext(); context.UseMetricsSnapshot(); string? count = null; string? max = null; context.AddRoutes(r => r.From("direct:otel-fn-step").RouteId(routeId) .Metered("work", _ => { }) .Process(e => { count = ExpressionResolver.ProcessTemplate("${stats('otel:redb.route.step.duration/work', 'count')}", e); max = ExpressionResolver.ProcessTemplate("${stats('otel:redb.route.step.duration/work', 'max')}", e); })); var producer = await Started(context, "direct:otel-fn-step"); await producer.Process(new Exchange(new Message("x"))); count.Should().Be("1", "the step ran once on this route"); max.Should().NotBeNullOrEmpty(); } [Fact] public async Task Named_route_and_step_can_be_addressed_from_another_route() { var workerRoute = $"otel-fn-w-{Guid.NewGuid():N}"; await using var context = new RouteContext(); context.UseMetricsSnapshot(); double? seen = null; context.AddRoutes(r => { r.From("direct:otel-fn-worker").RouteId(workerRoute).Metered("work", _ => { }); r.From("direct:otel-fn-reader").RouteId($"otel-fn-r-{Guid.NewGuid():N}") .Process(e => seen = Convert.ToDouble( ExpressionResolver.ProcessTemplate( $"${{stats('otel:redb.route.step.duration@{workerRoute}/work', 'count')}}", e))); }); var worker = await Started(context, "direct:otel-fn-worker"); await worker.Process(new Exchange(new Message("x"))); await worker.Process(new Exchange(new Message("x"))); var reader = context.GetEndpoint("direct:otel-fn-reader").CreateProducer(); await reader.Start(); await reader.Process(new Exchange(new Message("x"))); seen.Should().Be(2); } [Fact] public async Task An_instrument_nothing_recorded_reads_as_zero() { await using var context = new RouteContext(); context.UseMetricsSnapshot(); string? rendered = null; context.AddRoutes(r => r.From("direct:otel-fn-empty").RouteId($"otel-fn-e-{Guid.NewGuid():N}") .Process(e => rendered = ExpressionResolver.ProcessTemplate( "${stats('otel:redb.route.throttle.delayed', 'sum')}", e))); var producer = await Started(context, "direct:otel-fn-empty"); await producer.Process(new Exchange(new Message("x"))); rendered.Should().Be("0", "an instrument with no measurements is zero, not a failure"); } [Fact] public async Task Without_the_subscriber_it_fails_loudly() { await using var context = new RouteContext(); // no UseMetricsSnapshot() Exception? captured = null; context.AddRoutes(r => r.From("direct:otel-fn-off").RouteId($"otel-fn-o-{Guid.NewGuid():N}") .Process(e => { try { ExpressionResolver.ProcessTemplate("${stats('otel:redb.route.step.duration/work', 'count')}", e); } catch (Exception ex) { captured = ex; } })); var producer = await Started(context, "direct:otel-fn-off"); await producer.Process(new Exchange(new Message("x"))); captured.Should().NotBeNull(); captured!.Message.Should().Contain("UseMetricsSnapshot"); } [Fact] public async Task An_unknown_field_names_the_known_ones() { await using var context = new RouteContext(); context.UseMetricsSnapshot(); Exception? captured = null; context.AddRoutes(r => r.From("direct:otel-fn-bad").RouteId($"otel-fn-b-{Guid.NewGuid():N}") .Process(e => { try { ExpressionResolver.ProcessTemplate("${stats('otel:redb.route.step.duration/work', 'median')}", e); } catch (Exception ex) { captured = ex; } })); var producer = await Started(context, "direct:otel-fn-bad"); await producer.Process(new Exchange(new Message("x"))); captured.Should().NotBeNull(); captured!.Message.Should().Contain("median").And.Contain("count"); } [Fact] public async Task A_literal_unknown_field_fails_while_the_route_is_built() { await using var context = new RouteContext(); context.UseMetricsSnapshot(); context.AddRoutes(r => r.From("direct:otel-fn-build").RouteId("otel-fn-build") .Filter("stats('otel:redb.route.step.duration/work', 'median') > 0") .To("direct:otel-fn-sink") .EndFilter()); var act = () => context.Start(); (await act.Should().ThrowAsync()) .WithMessage("*median*", "a condition that can never work fails at build, not on the first message"); } [Fact] public void An_endpoint_metric_still_reads_as_before() { RedbRouteStatsNameCheck.KnownEndpointMetricsStillAccepted(); } /// Guard: the endpoint branch of stats() keeps its own metric names. private static class RedbRouteStatsNameCheck { public static void KnownEndpointMetricsStillAccepted() { ExpressionResolver.IsKnownStatistic("messagesIn").Should().BeTrue(); ExpressionResolver.IsKnownStatistic("max").Should().BeFalse("max belongs to the otel: branch"); } } } Path: redb-route/tests/redb.Route.Tests/Expressions/StringExpressionTests.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/Expressions/StringExpressionTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Expressions; using redb.Route.Predicates; namespace redb.Route.Tests.Expressions; /// /// Tests for — unified string expression that bridges /// the ExpressionResolver world with the IExpression/IPredicate world. /// public class StringExpressionTests : IDisposable { public StringExpressionTests() { ExpressionResolver.ClearAllCaches(); } public void Dispose() { ExpressionResolver.ClearAllCaches(); } private static IExchange CreateExchange(object? body = null) { var exchange = new Exchange(new Message(body)); return exchange; } // ── Template mode (contains ${...}) ── [Fact] public void Evaluate_Template_HeaderInterpolation() { var expr = new StringExpression("${header.name}"); var exchange = CreateExchange(); exchange.In.Headers["name"] = "Alice"; expr.Evaluate(exchange).Should().Be("Alice"); } [Fact] public void Evaluate_Template_MultipleInterpolations() { var expr = new StringExpression("Hello ${header.first} ${header.last}!"); var exchange = CreateExchange(); exchange.In.Headers["first"] = "John"; exchange.In.Headers["last"] = "Doe"; expr.Evaluate(exchange).Should().Be("Hello John Doe!"); } [Fact] public void Evaluate_Template_BodyInterpolation() { var expr = new StringExpression("Body is: ${body}"); var exchange = CreateExchange("test-payload"); expr.Evaluate(exchange).Should().Be("Body is: test-payload"); } [Fact] public void Evaluate_Template_PropertyInterpolation() { var expr = new StringExpression("id=${property.orderId}"); var exchange = CreateExchange(); exchange.Properties["orderId"] = "ORD-123"; expr.Evaluate(exchange).Should().Be("id=ORD-123"); } // ── Value expression mode (no ${...} wrapper) ── [Fact] public void Evaluate_ValueExpr_HeaderValue() { var expr = new StringExpression("header.amount"); var exchange = CreateExchange(); exchange.In.Headers["amount"] = 500; expr.Evaluate(exchange).Should().Be(500); } [Fact] public void Evaluate_ValueExpr_Arithmetic() { var expr = new StringExpression("header.a + header.b"); var exchange = CreateExchange(); exchange.In.Headers["a"] = 10; exchange.In.Headers["b"] = 20; var result = expr.Evaluate(exchange); Convert.ToInt32(result).Should().Be(30); } [Fact] public void Evaluate_ValueExpr_Body() { var expr = new StringExpression("body"); var exchange = CreateExchange("hello"); expr.Evaluate(exchange).Should().Be("hello"); } // ── Type conversion ── [Fact] public void Evaluate_TypeConversion_StringToInt() { var expr = new StringExpression("header.count"); var exchange = CreateExchange(); exchange.In.Headers["count"] = "42"; expr.Evaluate(exchange).Should().Be(42); } [Fact] public void Evaluate_NullResult_ReturnsDefault() { var expr = new StringExpression("header.value"); var exchange = CreateExchange(); exchange.In.Headers["value"] = null!; expr.Evaluate(exchange).Should().BeNull(); } // ── Predicate integration (inherited from Expression base) ── [Fact] public void Predicate_IsEqualTo_Matches() { var expr = new StringExpression("header.status"); var predicate = expr.isEqualTo("active"); var exchange = CreateExchange(); exchange.In.Headers["status"] = "active"; predicate.Matches(exchange).Should().BeTrue(); } [Fact] public void Predicate_IsEqualTo_NoMatch() { var expr = new StringExpression("header.status"); var predicate = expr.isEqualTo("active"); var exchange = CreateExchange(); exchange.In.Headers["status"] = "inactive"; predicate.Matches(exchange).Should().BeFalse(); } [Fact] public void Predicate_IsGreaterThan_Matches() { var expr = new StringExpression("header.amount"); var predicate = expr.isGreaterThan(100); var exchange = CreateExchange(); exchange.In.Headers["amount"] = 500; predicate.Matches(exchange).Should().BeTrue(); } [Fact] public void Predicate_Contains_Matches() { var expr = new StringExpression("header.message"); var predicate = expr.contains("error"); var exchange = CreateExchange(); exchange.In.Headers["message"] = "An error occurred"; predicate.Matches(exchange).Should().BeTrue(); } [Fact] public void Predicate_IsNull_Matches() { var expr = new StringExpression("header.status"); var predicate = expr.isNull(); var exchange = CreateExchange(); exchange.In.Headers["status"] = null!; predicate.Matches(exchange).Should().BeTrue(); } [Fact] public void Predicate_IsNotNull_Matches() { var expr = new StringExpression("header.present"); var predicate = expr.isNotNull(); var exchange = CreateExchange(); exchange.In.Headers["present"] = "yes"; predicate.Matches(exchange).Should().BeTrue(); } [Fact] public void Predicate_In_Matches() { var expr = new StringExpression("header.priority"); var predicate = expr.In("high", "critical"); var exchange = CreateExchange(); exchange.In.Headers["priority"] = "high"; predicate.Matches(exchange).Should().BeTrue(); } [Fact] public void Predicate_Regex_Matches() { var expr = new StringExpression("header.code"); var predicate = expr.regex(@"^ERR-\d+$"); var exchange = CreateExchange(); exchange.In.Headers["code"] = "ERR-404"; predicate.Matches(exchange).Should().BeTrue(); } [Fact] public void Predicate_StartsWith_Matches() { var expr = new StringExpression("header.path"); var predicate = expr.startsWith("/api"); var exchange = CreateExchange(); exchange.In.Headers["path"] = "/api/orders"; predicate.Matches(exchange).Should().BeTrue(); } [Fact] public void Predicate_EndsWith_Matches() { var expr = new StringExpression("header.file"); var predicate = expr.endsWith(".csv"); var exchange = CreateExchange(); exchange.In.Headers["file"] = "report.csv"; predicate.Matches(exchange).Should().BeTrue(); } [Fact] public void Predicate_IsBetween_Matches() { var expr = new StringExpression("header.score"); var predicate = expr.isBetween(1, 10); var exchange = CreateExchange(); exchange.In.Headers["score"] = 5; predicate.Matches(exchange).Should().BeTrue(); } [Fact] public void Predicate_And_Combination() { var expr = new StringExpression("header.amount"); var gt = expr.isGreaterThan(0); var lt = expr.isLessThan(1000); var predicate = new LambdaPredicate(e => gt.Matches(e) && lt.Matches(e)); var exchange = CreateExchange(); exchange.In.Headers["amount"] = 500; predicate.Matches(exchange).Should().BeTrue(); } [Fact] public void Predicate_Not_Negation() { var expr = new StringExpression("header.status"); var eq = expr.isEqualTo("blocked"); var predicate = new LambdaPredicate(e => !eq.Matches(e)); var exchange = CreateExchange(); exchange.In.Headers["status"] = "active"; predicate.Matches(exchange).Should().BeTrue(); } // ── SetValue throws ── [Fact] public void SetValue_ThrowsNotSupported() { var expr = new StringExpression("header.x"); var exchange = CreateExchange(); var act = () => expr.SetValue(exchange, "value"); act.Should().Throw() .WithMessage("*read-only*"); } // ── ToString ── [Fact] public void ToString_ReturnsExprFormat() { var expr = new StringExpression("${header.name}"); expr.ToString().Should().Be("Expr(\"${header.name}\")"); } // ── Template property ── [Fact] public void Template_ReturnsOriginal() { var expr = new StringExpression("header.amount + 100"); expr.Template.Should().Be("header.amount + 100"); } // ── Constructor validation ── [Fact] public void Constructor_NullTemplate_Throws() { var act = () => new StringExpression(null!); act.Should().Throw(); } [Fact] public void Constructor_EmptyTemplate_Throws() { var act = () => new StringExpression(""); act.Should().Throw(); } // ── Integration: used as IExpression in route DSL context ── [Fact] public void AsIExpression_WorksWithSetBody() { // Simulate what .SetBody(Expr("${header.x}")) does via ExpressionBodyProcessor IExpression expr = new StringExpression("${header.source}"); var exchange = CreateExchange(); exchange.In.Headers["source"] = "kafka-topic-1"; var result = expr.Evaluate(exchange); exchange.In.Body = result; exchange.In.Body.Should().Be("kafka-topic-1"); } [Fact] public void AsIExpression_WorksWithFilter() { // Simulate what .Filter(Expr("${header.active}").isEqualTo("true")) does IExpression expr = new StringExpression("header.active"); var predicate = ((Expression)expr).isEqualTo("true"); var exchange = CreateExchange(); exchange.In.Headers["active"] = "true"; predicate.Matches(exchange).Should().BeTrue(); } // ── Caching verification ── [Fact] public void MultipleInstances_SameTemplate_ShareCache() { var expr1 = new StringExpression("header.x"); var expr2 = new StringExpression("header.x"); var exchange = CreateExchange(); exchange.In.Headers["x"] = "value"; expr1.Evaluate(exchange).Should().Be("value"); expr2.Evaluate(exchange).Should().Be("value"); // Both use same compiled delegate from ExpressionResolver cache } } Path: redb-route/tests/redb.Route.Tests/Expressions/TemplateScannerTests.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/Expressions/TemplateScannerTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Expressions; namespace redb.Route.Tests.Expressions; /// /// The shared ${...} reader: balanced holes, quoted braces, the shapes that read as before, and the unclosed /// ${ that is an error. /// public sealed class TemplateScannerTests { private static (int, int)[] Spans(string template) => [.. TemplateScanner.Scan(template).Holes.Select(h => (h.Start, h.Length))]; [Theory] [InlineData("${body}", 0, 7)] [InlineData("a ${header.x} b", 2, 11)] [InlineData("${bean:svc.Check(${body})}", 0, 26)] [InlineData("${header.a == '}'}", 0, 18)] [InlineData("${concat(\"}\", 'x')}", 0, 19)] [InlineData("${header.O'Brien}", 0, 17)] [InlineData("${ {a} }", 0, 6)] [InlineData("$${body}", 1, 7)] public void OneHole(string template, int start, int length) { Spans(template).Should().Equal((start, length)); TemplateScanner.Scan(template).Unclosed.Should().BeEmpty(); } [Fact] public void AdjacentHoles_AreRead_InOrder() { Spans("${header.a}${header.b} and ${body}").Should().Equal((0, 11), (11, 11), (27, 7)); } [Theory] [InlineData("plain text")] [InlineData("${}")] [InlineData("{{key}}")] [InlineData("$ {body}")] public void NoHole(string template) { TemplateScanner.Scan(template).Holes.Should().BeEmpty(); TemplateScanner.HasPlaceholder(template).Should().BeFalse(); } [Theory] [InlineData("text ${", 6)] [InlineData("text ${body", 6)] [InlineData("${a ${b}", 1)] [InlineData("${body} and ${", 13)] public void Unclosed_IsAPositionedError(string template, int position) { TemplateScanner.HasPlaceholder(template).Should().BeTrue("a started placeholder is a template, and fails where it compiles"); var act = () => TemplateScanner.Holes(template); act.Should().Throw() .WithMessage($"unclosed '${{' at position {position} of \"{template}\": the placeholder has no closing '}}'."); } [Fact] public void Unclosed_FailsTheStringExpression_AndTheTemplate() { var expression = () => new StringExpression("total ${header.amount"); var template = () => ExpressionResolver.ProcessTemplate("total ${header.amount", new Exchange()); expression.Should().Throw().WithMessage("unclosed '${' at position 7*"); template.Should().Throw().WithMessage("unclosed '${' at position 7*"); } [Fact] public void QuotedBrace_ComparesInsteadOfBeingCut() { var exchange = new Exchange(); exchange.In.Headers["a"] = "}"; new StringExpression("${header.a == '}'}").Evaluate(exchange).Should().BeTrue(); } [Fact] public void DocumentedReadings_HoldAsTheReadmeStatesThem() { var exchange = new Exchange(); exchange.In.Headers["id"] = 42; exchange.In.Headers["O'Brien"] = "obrien"; ExpressionResolver.ProcessTemplate("${concat('a', '}', 'b')}", exchange).Should().Be("a}b"); ExpressionResolver.ProcessTemplate("{${header.id}}", exchange).Should().Be("{42}"); ExpressionResolver.ProcessTemplate("${}", exchange).Should().Be("${}"); ExpressionResolver.ProcessTemplate("${header.O'Brien}", exchange).Should().Be("obrien"); } [Theory] [InlineData("\\${", "${")] [InlineData("echo \\${HOME}", "echo ${HOME}")] [InlineData("\\${not} and ${header.id}", "${not} and 42")] [InlineData("${header.id} costs \\${x}", "42 costs ${x}")] [InlineData("a \\${b \\${c", "a ${b ${c")] public void AnEscape_IsALiteralPlaceholderOpener(string template, string rendered) { // Findings register row 16: \${ writes ${ and opens nothing, so it is never unclosed. var exchange = new Exchange(); exchange.In.Headers["id"] = 42; TemplateScanner.Scan(template).Unclosed.Should().BeEmpty(); TemplateScanner.HasPlaceholder(template).Should().BeTrue("an escape makes the text a template, which renders it"); ExpressionResolver.ProcessTemplate(template, exchange).Should().Be(rendered); new StringExpression(template).Evaluate(exchange).Should().Be(rendered); } [Fact] public void AnEscape_IsNotAHole() { TemplateScanner.Scan("\\${header.x} ${body}").Holes.Should().ContainSingle().Which.Start.Should().Be(13); TemplateScanner.Scan("\\${header.x}").Escapes.Should().Equal(0); ExpressionResolver.TryGetSinglePlaceholder("\\${header.x}", out _).Should().BeFalse(); } [Fact] public void SinglePlaceholder_IsTheWholeBalancedHole() { ExpressionResolver.TryGetSinglePlaceholder("${header.a == '}'}", out var inner).Should().BeTrue(); inner.Should().Be("header.a == '}'"); ExpressionResolver.TryGetSinglePlaceholder("${a} ${b}", out _).Should().BeFalse(); ExpressionResolver.TryGetSinglePlaceholder("${a ${b}", out _).Should().BeFalse("an unclosed placeholder is no single one"); } [Fact] public void EndpointOption_WithAnUnclosedPlaceholder_IsRefusedWhenBound() { var options = new ProbeOptions(); var act = () => options.BindFromUri(new Dictionary { ["value"] = "a ${header.b" }); act.Should().Throw().Which.ToString().Should().Contain("unclosed '${' at position 3"); } private sealed class ProbeOptions : EndpointOptions { public DynamicValue Value { get; set; } public override void Validate() { } } } Path: redb-route/tests/redb.Route.Tests/Expressions/Tokenizers/JsonArrayTokenizerTests.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/Expressions/Tokenizers/JsonArrayTokenizerTests.cs ---- using System.Text; using redb.Route.Expressions.Tokenizers; using AwesomeAssertions; namespace redb.Route.Tests.Expressions.Tokenizers; public class JsonArrayTokenizerTests { [Fact] public async Task PrimitiveArray_ThreeElements() { var result = await Collect(JsonArrayTokenizer.Tokenize("[1, 2, 3]")).ConfigureAwait(false); result.Should().Equal("1", "2", "3"); } [Fact] public async Task ObjectArray_TwoRawJsonStrings() { const string json = "[{\"a\":1}, {\"b\":2}]"; var result = await Collect(JsonArrayTokenizer.Tokenize(json)).ConfigureAwait(false); result.Should().HaveCount(2); ((string)result[0]!).Should().Contain("\"a\""); ((string)result[1]!).Should().Contain("\"b\""); } [Fact] public async Task EmptyArray_ZeroElements() { var result = await Collect(JsonArrayTokenizer.Tokenize("[]")).ConfigureAwait(false); result.Should().BeEmpty(); } [Fact] public async Task NotArray_ThrowsInvalidOperation() { var act = async () => await Collect(JsonArrayTokenizer.Tokenize("{\"a\":1}")).ConfigureAwait(false); await act.Should().ThrowAsync() .WithMessage("*not a JSON array*").ConfigureAwait(false); } [Fact] public async Task Stream_ParsesCorrectly() { var stream = new MemoryStream(Encoding.UTF8.GetBytes("[10, 20]")); var result = await Collect(JsonArrayTokenizer.Tokenize(stream)).ConfigureAwait(false); result.Should().Equal("10", "20"); } [Fact] public async Task ByteArray_ParsesCorrectly() { var bytes = Encoding.UTF8.GetBytes("[\"x\", \"y\"]"); var result = await Collect(JsonArrayTokenizer.Tokenize(bytes)).ConfigureAwait(false); result.Should().Equal("\"x\"", "\"y\""); } [Fact] public async Task ScalarBody_IsNotAJsonArray() { var act = async () => await Collect(JsonArrayTokenizer.Tokenize(12345)).ConfigureAwait(false); await act.Should().ThrowAsync() .WithMessage("*not a JSON array*").ConfigureAwait(false); } [Fact] public async Task NullBody_Throws() { var act = async () => await Collect(JsonArrayTokenizer.Tokenize(null)).ConfigureAwait(false); await act.Should().ThrowAsync() .WithMessage("*body is null*").ConfigureAwait(false); } [Fact] public async Task JpathResult_ObjectArray_SplitsIntoElementJson() { // then : the body is the object[] jpath returns. var exchange = new redb.Route.Core.Exchange(); exchange.In.Body = """{"id":"o-1","lines":[{"sku":"A-1","qty":1},{"sku":"B-2","qty":2}]}"""; var lines = new redb.Route.Expressions.JsonPathExpression("$.lines").Evaluate(exchange); var result = await Collect(JsonArrayTokenizer.Tokenize(lines)).ConfigureAwait(false); lines.Should().BeOfType(); result.Should().Equal("""{"sku":"A-1","qty":1}""", """{"sku":"B-2","qty":2}"""); } [Fact] public async Task TypedScalarArray_SplitsLikeTheText() { var result = await Collect(JsonArrayTokenizer.Tokenize(new[] { 1, 2 })).ConfigureAwait(false); var strings = await Collect(JsonArrayTokenizer.Tokenize(new[] { "x", "y" })).ConfigureAwait(false); result.Should().Equal("1", "2"); strings.Should().Equal("\"x\"", "\"y\""); } [Fact] public async Task JsonTree_SplitsAndKeepsNonAsciiAsWritten() { var node = System.Text.Json.Nodes.JsonNode.Parse("""[{"name":"Склад"},null]"""); using var document = System.Text.Json.JsonDocument.Parse("""[{"name":"Склад"}]"""); var fromNode = await Collect(JsonArrayTokenizer.Tokenize(node)).ConfigureAwait(false); var fromDocument = await Collect(JsonArrayTokenizer.Tokenize(document)).ConfigureAwait(false); fromNode.Should().Equal("""{"name":"Склад"}""", "null"); fromDocument.Should().Equal("""{"name":"Склад"}"""); } private static async Task> Collect(IAsyncEnumerable source) { var list = new List(); await foreach (var item in source.ConfigureAwait(false)) list.Add(item); return list; } } Path: redb-route/tests/redb.Route.Tests/Expressions/Tokenizers/LineTokenizerTests.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/Expressions/Tokenizers/LineTokenizerTests.cs ---- using System.Text; using redb.Route.Expressions.Tokenizers; using AwesomeAssertions; namespace redb.Route.Tests.Expressions.Tokenizers; public class LineTokenizerTests { [Fact] public async Task Stream_ThreeLines_ThreeElements() { var stream = new MemoryStream("line1\nline2\nline3"u8.ToArray()); var result = await Collect(LineTokenizer.Tokenize(stream, "\n", false)).ConfigureAwait(false); result.Should().Equal("line1", "line2", "line3"); } [Fact] public async Task String_WithNewlines_SplitsCorrectly() { var result = await Collect(LineTokenizer.Tokenize("a\nb\nc", "\n", false)).ConfigureAwait(false); result.Should().Equal("a", "b", "c"); } [Fact] public async Task ByteArray_SplitsCorrectly() { var bytes = Encoding.UTF8.GetBytes("x\ny\nz"); var result = await Collect(LineTokenizer.Tokenize(bytes, "\n", false)).ConfigureAwait(false); result.Should().Equal("x", "y", "z"); } [Fact] public async Task SkipEmpty_True_SkipsEmptyLines() { var result = await Collect(LineTokenizer.Tokenize("a\n\nb\n \nc", "\n", true)).ConfigureAwait(false); result.Should().Equal("a", "b", "c"); } [Fact] public async Task EmptyStream_ZeroElements() { var stream = new MemoryStream(Array.Empty()); var result = await Collect(LineTokenizer.Tokenize(stream, "\n", false)).ConfigureAwait(false); result.Should().BeEmpty(); } [Fact] public async Task NullBody_ZeroElements() { var result = await Collect(LineTokenizer.Tokenize(null, "\n", false)).ConfigureAwait(false); result.Should().BeEmpty(); } private static async Task> Collect(IAsyncEnumerable source) { var list = new List(); await foreach (var item in source.ConfigureAwait(false)) list.Add(item); return list; } } Path: redb-route/tests/redb.Route.Tests/Expressions/Tokenizers/XmlTokenizerTests.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/Expressions/Tokenizers/XmlTokenizerTests.cs ---- using System.Text; using redb.Route.Expressions.Tokenizers; using AwesomeAssertions; namespace redb.Route.Tests.Expressions.Tokenizers; public class XmlTokenizerTests { private const string SimpleXml = "AB"; [Fact] public async Task String_TwoOrders_TwoElements() { var result = await Collect(XmlTokenizer.Tokenize(SimpleXml, "order", null)).ConfigureAwait(false); result.Should().HaveCount(2); result[0].Should().Be("A"); result[1].Should().Be("B"); } [Fact] public async Task Stream_TwoOrders_TwoElements() { var stream = new MemoryStream(Encoding.UTF8.GetBytes(SimpleXml)); var result = await Collect(XmlTokenizer.Tokenize(stream, "order", null)).ConfigureAwait(false); result.Should().HaveCount(2); } [Fact] public async Task ByteArray_TwoOrders_TwoElements() { var bytes = Encoding.UTF8.GetBytes(SimpleXml); var result = await Collect(XmlTokenizer.Tokenize(bytes, "order", null)).ConfigureAwait(false); result.Should().HaveCount(2); } [Fact] public async Task InheritNamespace_InjectsParentNamespace() { const string xml = "1"; var result = await Collect(XmlTokenizer.Tokenize(xml, "order", "orders")).ConfigureAwait(false); result.Should().ContainSingle(); var orderXml = (string)result[0]!; orderXml.Should().Contain("xmlns:ns=\"urn:test\""); } [Fact] public async Task EmptyXml_NoOrders_ZeroElements() { const string xml = ""; var result = await Collect(XmlTokenizer.Tokenize(xml, "order", null)).ConfigureAwait(false); result.Should().BeEmpty(); } [Fact] public async Task NestedSameElement_ReturnsOuterXml() { const string xml = "nested"; var result = await Collect(XmlTokenizer.Tokenize(xml, "item", null)).ConfigureAwait(false); result.Should().ContainSingle(); var outerXml = (string)result[0]!; outerXml.Should().Contain("nested"); } [Fact] public async Task DtdProcessing_Prohibit_ThrowsOnDtd() { const string xml = "]>&xxe;"; var act = async () => await Collect(XmlTokenizer.Tokenize(xml, "item", null)).ConfigureAwait(false); await act.Should().ThrowAsync().ConfigureAwait(false); } [Fact] public async Task UnsupportedBody_Throws() { var act = async () => await Collect(XmlTokenizer.Tokenize(12345, "item", null)).ConfigureAwait(false); await act.Should().ThrowAsync() .WithMessage("*unsupported body type*").ConfigureAwait(false); } private static async Task> Collect(IAsyncEnumerable source) { var list = new List(); await foreach (var item in source.ConfigureAwait(false)) list.Add(item); return list; } } Path: redb-route/tests/redb.Route.Tests/Expressions/TrailingTextTests.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/Expressions/TrailingTextTests.cs ---- using AwesomeAssertions; using redb.Route.Core; using redb.Route.Expressions; using redb.Route.Predicates; namespace redb.Route.Tests.Expressions; /// /// Text after a complete expression (findings register row 32): until 4.7.0 the engine stopped at the end of the /// expression and dropped the rest, so header.b == 3 garbage compared and ${exception.type|message} /// rendered empty. Now the rest is an error naming it and its position, when the route is built. /// public sealed class TrailingTextTests { private static Exchange Exchange() { var exchange = new Exchange(new Message("x")); exchange.In.Headers["b"] = 3; exchange.In.Headers["Content-Type"] = "text/xml"; exchange.In.Headers["user"] = new Dictionary { ["name"] = "Ann" }; return exchange; } [Theory] [InlineData("${header.b == 3 garbage}", "unexpected 'garbage' at position 15 within the expression")] [InlineData("${exception.type|message}", "unexpected '|' at position 15 within the expression")] [InlineData("${upper(header.s) x}", "unexpected 'x' at position 17 within the expression")] [InlineData("total ${header.a 7}", "unexpected '7' at position 10 within the expression")] [InlineData("${a ${b}}", "unexpected '${' at position 3 within the expression")] public void InAPlaceholder_TheRestIsAnError(string template, string detail) { var act = () => ExpressionResolver.ProcessTemplate(template, Exchange()); act.Should().Throw().WithMessage($"*{detail}: the expression ends before it."); } [Theory] [InlineData("header.b == 3 garbage")] [InlineData("header.b == 3 'x'")] [InlineData("upper(header.s) x")] public void InAValueAndACondition_TheRestIsAnError(string expression) { var value = () => ExpressionResolver.GetCompiledValueExpression(expression); var condition = () => PredicateFactory.FromString(expression); value.Should().Throw().WithMessage("*the expression ends before it."); condition.Should().Throw().WithMessage("*the expression ends before it."); } [Theory] [InlineData("header.b 3")] [InlineData("plain text")] public void BareTextWithoutAnOperator_StaysTheText(string expression) { ExpressionResolver.GetCompiledValueExpression(expression)(Exchange()).Should().Be(expression, "the bare-text rule of row 29"); } [Fact] public void AnUppercaseFileKey_GetsAHint() { var act = () => ExpressionResolver.ProcessTemplate("${FILE:Name.NoExt}", Exchange()); act.Should().Throw().WithMessage("${FILE:Name.NoExt}: file keys are lowercase: ${file:name.noext}."); } // ── the literal-name-first rule keeps its names ───────────────── [Theory] [InlineData("${header.Content-Type}", "text/xml")] [InlineData("${header.user.name}", "Ann")] [InlineData("[${header.missing-name}]", "[]")] [InlineData("[${header.no.such.path}]", "[]")] public void OneWordNames_StillReadTheHeader(string template, string expected) { ExpressionResolver.ProcessTemplate(template, Exchange()).Should().Be(expected); } [Fact] public void AOneWordTailThatDoesNotCompile_IsANameLookup() { var exchange = Exchange(); exchange.In.Headers["a#b"] = "hash"; ExpressionResolver.ProcessTemplate("${header.a#b}", exchange).Should().Be("hash"); } [Fact] public void ATailWithWhitespaceThatDoesNotCompile_IsTheError_NotAMissingName() { var act = () => ExpressionResolver.ProcessTemplate("${header.b == 3 garbage}", Exchange()); act.Should().Throw(); } } Path: redb-route/tests/redb.Route.Tests/Expressions/WhitespaceInsensitivityTests.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/Expressions/WhitespaceInsensitivityTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Expressions; using redb.Route.Predicates; namespace redb.Route.Tests.Expressions; /// /// A condition is a boolean expression, so whitespace between its tokens carries no meaning and an /// operator inside a quoted literal is not an operator. A value is not a condition: a bare string /// in value position stays a literal, which is what connector options and SetBody depend on. /// These tests hold both halves of that rule in place. /// [Collection("ExpressionResolver")] public class WhitespaceInsensitivityTests { private static IExchange CreateExchange() { var exchange = new Exchange(new Message("payload")); exchange.In.Headers["a"] = 42; exchange.In.Headers["b"] = 3; exchange.In.Headers["name"] = "a > b"; exchange.In.Headers["phrase"] = "x AND y"; return exchange; } private static bool Condition(string condition) => PredicateFactory.FromString(condition).Matches(CreateExchange()); private static object? Value(string expression) => new StringExpression(expression).Evaluate(CreateExchange()); // ── Condition position: whitespace is not part of the language ──────────── [Theory] [InlineData("header.a>10")] [InlineData("header.a > 10")] [InlineData("header.a > 10")] [InlineData("header.a\t>\t10")] [InlineData("header.a\n>\n10")] [InlineData("header.a >\n 10")] [InlineData(" header.a>10 ")] public void Comparison_ReadsTheSameHoweverItIsSpaced(string condition) => Condition(condition).Should().BeTrue(); [Theory] [InlineData("header.a<10")] [InlineData("header.a < 10")] [InlineData("header.a < 10")] [InlineData("header.a\t<\t10")] public void Comparison_ThatDoesNotHold_ReadsTheSameHoweverItIsSpaced(string condition) => Condition(condition).Should().BeFalse(); [Theory] [InlineData("header.a>=42")] [InlineData("header.a <= 42")] [InlineData("header.a!=41")] [InlineData("header.a==42")] public void EveryComparisonOperator_WorksWithoutSurroundingSpaces(string condition) => Condition(condition).Should().BeTrue(); [Theory] [InlineData("header.a>10 AND header.b<5")] [InlineData("header.a > 10 AND header.b < 5")] [InlineData("header.a>10 AND header.b<5")] [InlineData("header.a>10\tAND\theader.b<5")] [InlineData("header.a>10\nAND\nheader.b<5")] [InlineData("header.a>10 and header.b<5")] public void WordLogic_ReadsTheSameHoweverItIsSpaced(string condition) => Condition(condition).Should().BeTrue(); [Theory] [InlineData("(header.a>10) AND (header.b<5)")] [InlineData("(header.a > 10) AND (header.b < 5)")] public void ParenthesisedGroups_AreUnderstood(string condition) => Condition(condition).Should().BeTrue(); /// /// An operator inside a quoted literal is part of the literal. The header holds the exact /// text a > b, so the comparison has to succeed rather than being read as a chain of /// comparisons. /// [Fact] public void OperatorInsideQuotedLiteral_IsNotAnOperator() { Condition("header.name == 'a > b'").Should().BeTrue(); Condition("header.name=='a > b'").Should().BeTrue(); Condition("header.name == 'a < b'").Should().BeFalse(); } [Fact] public void WordLogicInsideQuotedLiteral_IsNotAnOperator() { Condition("header.phrase == 'x AND y'").Should().BeTrue(); Condition("header.phrase == 'x OR y'").Should().BeFalse(); } // ── Condition position: no operator means a value read ──────────────────── /// /// A condition carrying no operator is a value read for truthiness, not a boolean expression. /// That distinction is load-bearing: the AST parser does not resolve a CLR member or a /// dictionary entry behind a header or property, so sending every condition through it would /// turn working conditions such as property.cfg.enabled into a constant false. /// [Theory] [InlineData(true)] [InlineData(false)] public void ConditionWithoutOperator_ResolvesAMemberBehindAHeader(bool active) { var exchange = new Exchange(new Message("payload")); exchange.In.Headers["user"] = new { Active = active }; PredicateFactory.FromString("header.user.Active").Matches(exchange).Should().Be(active); } [Theory] [InlineData(true)] [InlineData(false)] public void ConditionWithoutOperator_ResolvesAnEntryBehindAProperty(bool enabled) { var exchange = new Exchange(new Message("payload")); exchange.Properties["cfg"] = new Dictionary { ["enabled"] = enabled }; PredicateFactory.FromString("property.cfg.enabled").Matches(exchange).Should().Be(enabled); } [Fact] public void ConditionWithoutOperator_ResolvesAHeaderWhoseNameContainsADot() { var exchange = new Exchange(new Message("payload")); exchange.In.Headers["dotted.key"] = "present"; PredicateFactory.FromString("header.dotted.key").Matches(exchange).Should().BeTrue(); } // ── Value position: a bare string stays a literal ───────────────────────── /// /// An explicit expression (Expr(...), i.e. ) that carries /// no operator is a literal, whatever else it contains. /// [Theory] [InlineData("plain text")] [InlineData("hello")] [InlineData("dGVzdC1zZWNyZXQ=")] [InlineData("key=value")] public void ExplicitExpression_WithoutAnOperator_StaysALiteral(string literal) => Value(literal).Should().Be(literal); /// /// An explicit expression that carries an operator is an expression, whatever the spacing: /// "a string is a string, an expression is an expression". Until 2026-08-28 these read as /// literals because the value dialect only saw operators surrounded by single spaces — the /// last place in the language where whitespace carried meaning. The guarantee that a plain /// string stays a literal now lives where it belongs, on the string position: /// SetHeader("k", "a>b") is covered end-to-end in ValueAndValidateEndToEndTests. /// [Theory] [InlineData("a>b", false)] [InlineData("x Value(expression).Should().Be(expected); /// /// An explicit expression that carries an operator but does not parse fails while it is being /// built. It used to compile to a mangled lookup and yield null or its own text on every /// message; failing early is the only honest answer for text that means nothing. /// [Theory] [InlineData("")] [InlineData("")] [InlineData("dGVzdC1zZWNyZXQ==")] public void ExplicitExpression_WithAnOperatorThatDoesNotParse_FailsAtBuildTime(string expression) { var build = () => new StringExpression(expression); build.Should().Throw(); } [Theory] [InlineData("header.a+header.b", 45)] [InlineData("header.a + header.b", 45)] [InlineData("header.a*2", 84)] [InlineData("header.a * 2", 84)] [InlineData("header.a-2", 40)] [InlineData("header.a - 2", 40)] [InlineData("header.a/2", 21)] public void ValuePosition_ArithmeticIsUnchanged(string expression, int expected) => Value(expression).Should().Be(expected); [Fact] public void ValuePosition_TemplateIsUnchanged() => Value("${header.a} > 10").Should().Be("42 > 10"); } Path: redb-route/tests/redb.Route.Tests/Expressions/XPathExpressionTests.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/Expressions/XPathExpressionTests.cs ---- using System.Xml; using System.Xml.Linq; using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Expressions; using redb.Route.Serialization; using XPathExpr = redb.Route.Expressions.XPathExpression; namespace redb.Route.Tests.Expressions; /// /// Tests for XML/XPath functionality: XPathExpression, TypedXPathExpression, /// CompiledXPathExpression, xpath() DSL helpers, ApplyXPath via ExpressionResolver, /// and XmlMessageSerializer. /// [Collection("ExpressionResolver")] public class XPathExpressionTests : IDisposable { private const string SampleXml = """ DRV-001 John Doe true false 35 75000.50 driver active verified 90 85 92
Moscow Russia
"""; public XPathExpressionTests() { ExpressionResolver.ClearAllCaches(); } public void Dispose() { ExpressionResolver.ClearAllCaches(); } private static IExchange CreateXmlExchange(string xml = SampleXml) => new Exchange(new Message(xml)); private static IExchange CreateXDocumentExchange() => new Exchange(new Message(XDocument.Parse(SampleXml))); private static IExchange CreateXElementExchange() => new Exchange(new Message(XDocument.Parse(SampleXml).Root!)); // ── XPathExpression: basic element access ── [Fact] public void Evaluate_StringElement_ReturnsString() { var expr = new XPathExpr("/driver/firstName"); var result = expr.Evaluate(CreateXmlExchange()); result.Should().Be("John"); } [Fact] public void Evaluate_BoolElement_ReturnsBool() { var expr = new XPathExpr("/driver/isHired"); var result = expr.Evaluate(CreateXmlExchange()); result.Should().BeTrue(); } [Fact] public void Evaluate_BoolFalseElement_ReturnsFalse() { var expr = new XPathExpr("/driver/dismissed"); var result = expr.Evaluate(CreateXmlExchange()); result.Should().BeFalse(); } [Fact] public void Evaluate_IntElement_ReturnsInt() { var expr = new XPathExpr("/driver/age"); var result = expr.Evaluate(CreateXmlExchange()); result.Should().Be(35); } [Fact] public void Evaluate_DoubleElement_ReturnsDouble() { var expr = new XPathExpr("/driver/salary"); var result = expr.Evaluate(CreateXmlExchange()); result.Should().Be(75000.50); } [Fact] public void Evaluate_NestedElement_ReturnsValue() { var expr = new XPathExpr("/driver/address/city"); var result = expr.Evaluate(CreateXmlExchange()); result.Should().Be("Moscow"); } // ── Attribute access ── [Fact] public void Evaluate_Attribute_ReturnsValue() { var expr = new XPathExpr("/driver/contacts/contact[@type='email']/@value"); var result = expr.Evaluate(CreateXmlExchange()); result.Should().Be("john@example.com"); } [Fact] public void Evaluate_AttributeSelector_ReturnsCorrectContact() { var expr = new XPathExpr("/driver/contacts/contact[@type='phone']/@value"); var result = expr.Evaluate(CreateXmlExchange()); result.Should().Be("+7-999-123-45-67"); } // ── Multiple elements ── [Fact] public void Evaluate_MultipleElements_ReturnsStringArray() { var expr = new XPathExpr("/driver/tags/tag"); var result = expr.Evaluate(CreateXmlExchange()); result.Should().BeEquivalentTo("driver", "active", "verified"); } [Fact] public void Evaluate_MultipleElements_JoinedString() { var expr = new XPathExpr("/driver/tags/tag"); var result = expr.Evaluate(CreateXmlExchange()); result.Should().Be("driver, active, verified"); } [Fact] public void Evaluate_MultipleScores_ReturnsIntArray() { var expr = new XPathExpr("/driver/scores/score"); var result = expr.Evaluate(CreateXmlExchange()); result.Should().BeEquivalentTo(new[] { 90, 85, 92 }); } [Fact] public void Evaluate_MultipleElements_AsXElements() { var expr = new XPathExpr("/driver/tags/tag"); var result = expr.Evaluate(CreateXmlExchange()); result.Should().HaveCount(3); result[0].Value.Should().Be("driver"); } // ── XPath functions ── [Fact] public void Evaluate_CountFunction_ReturnsInt() { var expr = new XPathExpr("count(/driver/tags/tag)"); var result = expr.Evaluate(CreateXmlExchange()); result.Should().Be(3); } [Fact] public void Evaluate_StringFunction_ReturnsString() { var expr = new XPathExpr("string(/driver/firstName)"); var result = expr.Evaluate(CreateXmlExchange()); result.Should().Be("John"); } [Fact] public void Evaluate_BooleanFunction_ReturnsBool() { // boolean() on non-empty string returns true var expr = new XPathExpr("boolean(/driver/firstName)"); var result = expr.Evaluate(CreateXmlExchange()); result.Should().BeTrue(); } [Fact] public void Evaluate_BooleanFunctionOnMissing_ReturnsFalse() { var expr = new XPathExpr("boolean(/driver/nonExistent)"); var result = expr.Evaluate(CreateXmlExchange()); result.Should().BeFalse(); } [Fact] public void Evaluate_SumFunction_ReturnsDouble() { var expr = new XPathExpr("sum(/driver/scores/score)"); var result = expr.Evaluate(CreateXmlExchange()); result.Should().Be(267); } [Fact] public void Evaluate_CountAsObject_ReturnsInt() { // count() returns double from XPath, but Evaluate should smart-convert to int var expr = new XPathExpr("count(/driver/tags/tag)"); var result = expr.Evaluate(CreateXmlExchange()); result.Should().Be(3); // int, not double } // ── Path not found ── [Fact] public void Evaluate_NotFound_ReturnsNull_ForString() { var expr = new XPathExpr("/driver/nonExistent"); var result = expr.Evaluate(CreateXmlExchange()); result.Should().BeNull(); } [Fact] public void Evaluate_NotFound_Throws_ForValueType() { var expr = new XPathExpr("/driver/nonExistent"); var act = () => expr.Evaluate(CreateXmlExchange()); act.Should().Throw(); } // ── XDocument body ── [Fact] public void Evaluate_XDocumentBody_Works() { var expr = new XPathExpr("/driver/id"); var result = expr.Evaluate(CreateXDocumentExchange()); result.Should().Be("DRV-001"); } // ── XElement body ── [Fact] public void Evaluate_XElementBody_Works() { var expr = new XPathExpr("/driver/lastName"); var result = expr.Evaluate(CreateXElementExchange()); result.Should().Be("Doe"); } // ── POCO body (auto-serialized) ── [Fact] public void Evaluate_PocoBody_Serialized() { var exchange = new Exchange(new Message(new TestPoco { Name = "Alice", Age = 30 })); var expr = new XPathExpr("//Name"); var result = expr.Evaluate(exchange); result.Should().Be("Alice"); } [Fact] public void Evaluate_PocoBody_IntField() { var exchange = new Exchange(new Message(new TestPoco { Name = "Bob", Age = 42 })); var expr = new XPathExpr("//Age"); var result = expr.Evaluate(exchange); result.Should().Be(42); } // ── Null body ── [Fact] public void Evaluate_NullBody_Throws() { var exchange = new Exchange(new Message(null)); var expr = new XPathExpr("/root"); var act = () => expr.Evaluate(exchange); act.Should().Throw().WithMessage("*null*"); } // ── Empty string body ── [Fact] public void Evaluate_EmptyStringBody_Throws() { var exchange = new Exchange(new Message("")); var expr = new XPathExpr("/root"); var act = () => expr.Evaluate(exchange); act.Should().Throw().WithMessage("*empty string*"); } // ── Invalid XML body ── [Fact] public void Evaluate_InvalidXml_Throws() { var exchange = new Exchange(new Message("not xml at all")); var expr = new XPathExpr("/root"); var act = () => expr.Evaluate(exchange); act.Should().Throw().WithMessage("*XML parsing error*"); } // ── Constructor validation ── [Fact] public void Constructor_NullPath_Throws() { var act = () => new XPathExpr(null!); act.Should().Throw(); } // ── SetValue not supported ── [Fact] public void SetValue_Throws() { var expr = new XPathExpr("/root"); var act = () => expr.SetValue(CreateXmlExchange(), "value"); act.Should().Throw(); } // ── Evaluate single element ── [Fact] public void EvaluateObject_SingleElement_ReturnsSmartParsed() { var expr = new XPathExpr("/driver/age"); var result = expr.Evaluate(CreateXmlExchange()); result.Should().Be(35); // smart-parsed to int } [Fact] public void EvaluateObject_SingleStringElement_ReturnsString() { var expr = new XPathExpr("/driver/firstName"); var result = expr.Evaluate(CreateXmlExchange()); result.Should().Be("John"); } [Fact] public void EvaluateObject_MultipleElements_ReturnsStringArray() { var expr = new XPathExpr("/driver/tags/tag"); var result = expr.Evaluate(CreateXmlExchange()); result.Should().BeOfType(); (result as string[]).Should().BeEquivalentTo("driver", "active", "verified"); } // ── TypedXPathExpression ── [Fact] public void TypedXPath_Bool_ReturnsBoxedBool() { var expr = new TypedXPathExpression("/driver/isHired"); // Processor calls Evaluate — TypedXPath must route to Evaluate var result = expr.Evaluate(CreateXmlExchange()); result.Should().BeOfType(); result.Should().Be(true); } [Fact] public void TypedXPath_Int_ReturnsBoxedInt() { var expr = new TypedXPathExpression("/driver/age"); var result = expr.Evaluate(CreateXmlExchange()); result.Should().BeOfType(); result.Should().Be(35); } [Fact] public void TypedXPath_StringArray_ReturnsTypedArray() { var expr = new TypedXPathExpression("/driver/tags/tag"); var result = expr.Evaluate(CreateXmlExchange()); result.Should().BeOfType(); (result as string[]).Should().BeEquivalentTo("driver", "active", "verified"); } [Fact] public void TypedXPath_DirectT_ForwardsCorrectly() { var expr = new TypedXPathExpression("/driver/firstName"); var result = expr.Evaluate(CreateXmlExchange()); result.Should().Be("John"); } // ── CompiledXPathExpression ── [Fact] public void CompiledXPath_DynamicPath_Works() { var exchange = CreateXmlExchange(); exchange.Properties["xpathQuery"] = "/driver/firstName"; var compiled = new CompiledXPathExpression(ex => ex.getProperty("xpathQuery")!); var result = compiled.Evaluate(exchange); result.Should().Be("John"); } [Fact] public void CompiledXPath_NullPath_ReturnsDefault() { var exchange = CreateXmlExchange(); var compiled = new CompiledXPathExpression(_ => null!); var result = compiled.Evaluate(exchange); result.Should().BeNull(); } // ── ExpressionResolver template integration ── [Fact] public void ExpressionResolver_XPathTemplate_ResolvesCorrectly() { var exchange = CreateXmlExchange(); var template = "Driver: ${xpath(/driver/firstName)}"; var result = ExpressionResolver.ResolveExpression(template, exchange)?.ToString(); result.Should().Be("Driver: John"); } [Fact] public void ExpressionResolver_XPathDirectExpression_ResolvesCorrectly() { var exchange = CreateXmlExchange(); var result = ExpressionResolver.ResolveExpression("xpath(/driver/age)", exchange); result.Should().Be(35); } [Fact] public void ExpressionResolver_XPathQuotedExpression_ResolvesCorrectly() { var exchange = CreateXmlExchange(); var result = ExpressionResolver.ResolveExpression("xpath('/driver/lastName')", exchange); // Should return smart-parsed object — "Doe" is a string result.Should().Be("Doe"); } // ── ApplyXPath via ExpressionResolver (null body) ── [Fact] public void ApplyXPath_NullBody_ReturnsNull() { var exchange = new Exchange(new Message(null)); var result = ExpressionResolver.ResolveExpression("xpath(/root/child)", exchange); result.Should().BeNull(); } // ── Namespace support ── [Fact] public void Evaluate_WithNamespace_Works() { const string nsXml = """ Hello """; var nsMgr = new XmlNamespaceManager(new NameTable()); nsMgr.AddNamespace("ns", "http://example.com/ns"); var exchange = new Exchange(new Message(nsXml)); var expr = new XPathExpr("/root/ns:item", nsMgr); var result = expr.Evaluate(exchange); result.Should().Be("Hello"); } // ── XmlMessageSerializer ── [Fact] public void XmlSerializer_Serialize_ProducesXml() { var serializer = new XmlMessageSerializer(); var data = new TestPoco { Name = "Alice", Age = 30 }; var bytes = serializer.Serialize(data); bytes.Should().NotBeEmpty(); var xml = System.Text.Encoding.UTF8.GetString(bytes); xml.Should().Contain("Alice"); xml.Should().Contain("30"); } [Fact] public void XmlSerializer_Deserialize_ReturnsObject() { var serializer = new XmlMessageSerializer(); var original = new TestPoco { Name = "Bob", Age = 42 }; var bytes = serializer.Serialize(original); var restored = serializer.Deserialize(bytes); restored.Should().NotBeNull(); restored!.Name.Should().Be("Bob"); restored.Age.Should().Be(42); } [Fact] public void XmlSerializer_DeserializeUntyped_ReturnsObject() { var serializer = new XmlMessageSerializer(); var original = new TestPoco { Name = "Carol", Age = 50 }; var bytes = serializer.Serialize(original); var restored = serializer.Deserialize(bytes, typeof(TestPoco)) as TestPoco; restored.Should().NotBeNull(); restored!.Name.Should().Be("Carol"); } [Fact] public void XmlSerializer_ContentType_IsApplicationXml() { var serializer = new XmlMessageSerializer(); serializer.ContentType.Should().Be("application/xml"); } [Fact] public void XmlSerializer_RoundTrip_PreservesData() { var serializer = new XmlMessageSerializer(); var original = new TestPoco { Name = "Dave", Age = 28 }; var bytes = serializer.Serialize(original); var restored = serializer.Deserialize(bytes); restored!.Name.Should().Be(original.Name); restored.Age.Should().Be(original.Age); } [Fact] public void XmlSerializer_Deserialize_NullData_Throws() { var serializer = new XmlMessageSerializer(); var act = () => serializer.Deserialize(null!); act.Should().Throw(); } [Fact] public void XmlSerializer_DeserializeUntyped_NullData_Throws() { var serializer = new XmlMessageSerializer(); var act = () => serializer.Deserialize(null!, typeof(TestPoco)); act.Should().Throw(); } // ── Marshal/Unmarshal integration ── [Fact] public async Task MarshalProcessor_WithXmlSerializer_SetsContentType() { var serializer = new XmlMessageSerializer(); var processor = new MarshalProcessor(serializer); var exchange = new Exchange(new Message(new TestPoco { Name = "Eve", Age = 33 })); await processor.Process(exchange); exchange.In.Body.Should().BeOfType(); exchange.In.Headers["Content-Type"].Should().Be("application/xml"); } [Fact] public async Task UnmarshalProcessor_WithXmlSerializer_RestoresObject() { var serializer = new XmlMessageSerializer(); var marshalProcessor = new MarshalProcessor(serializer); var unmarshalProcessor = new UnmarshalProcessor(serializer, typeof(TestPoco)); var original = new TestPoco { Name = "Frank", Age = 45 }; var exchange = new Exchange(new Message(original)); await marshalProcessor.Process(exchange); await unmarshalProcessor.Process(exchange); var restored = exchange.In.Body as TestPoco; restored.Should().NotBeNull(); restored!.Name.Should().Be("Frank"); restored.Age.Should().Be(45); } // ── ExpressionPropertyProcessor with XPath ── [Fact] public async Task ExpressionPropertyProcessor_WithXPath_SetsProperty() { var exchange = CreateXmlExchange(); var expr = new XPathExpr("/driver/firstName"); var processor = new redb.Route.Processors.ExpressionPropertyProcessor("driverName", expr); await processor.Process(exchange); exchange.Properties["driverName"].Should().Be("John"); } // ── Descendant axis (//) ── [Fact] public void Evaluate_DescendantAxis_FindsNested() { var expr = new XPathExpr("//city"); var result = expr.Evaluate(CreateXmlExchange()); result.Should().Be("Moscow"); } // ── Predicate with index ── [Fact] public void Evaluate_IndexPredicate_ReturnsCorrect() { var expr = new XPathExpr("/driver/scores/score[2]"); var result = expr.Evaluate(CreateXmlExchange()); result.Should().Be(85); } // ── XPath returning XElement ── [Fact] public void Evaluate_ReturnsXElement_WhenRequested() { var expr = new XPathExpr("/driver/address"); var result = expr.Evaluate(CreateXmlExchange()); result.Should().NotBeNull(); result.Name.LocalName.Should().Be("address"); result.Element("city")!.Value.Should().Be("Moscow"); } // ── Test POCO ── public class TestPoco { public string Name { get; set; } = ""; public int Age { get; set; } } } Path: redb-route/tests/redb.Route.Tests/Expressions/XPathParameterTests.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/Expressions/XPathParameterTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Expressions; using XPathExpr = redb.Route.Expressions.XPathExpression; namespace redb.Route.Tests.Expressions; /// /// A value from the message takes part in an XPath query by being bound to a /// $name variable, never by being pasted into the query text. /// /// Concatenation is what Apache Camel offers as allowSimple, and it is the reason XPath /// injection has an OWASP entry and a CodeQL query of its own. Binding is the settled answer /// everywhere else: JAXP's XPathVariableResolver, XQuery's declare variable $x /// external, .NET's XsltArgumentList, SQL prepared statements. /// /// public class XPathParameterTests { private const string Orders = """ 10 20 """; private static IExchange Exchange(params (string Key, object? Value)[] headers) { var exchange = new Exchange(new Message(Orders)); foreach (var (key, value) in headers) exchange.In.Headers[key] = value; return exchange; } [Fact] public void A_bound_value_selects_the_matching_node() { var total = new XPathExpr("/orders/order[@id=$id]/total") .WithParameters(("id", new HeaderExpression("wanted"))) .Evaluate(Exchange(("wanted", "B-2"))); total.Should().Be("20"); } [Fact] public void The_same_expression_answers_differently_for_different_messages() { var expression = new XPathExpr("/orders/order[@id=$id]/total") .WithParameters(("id", new HeaderExpression("wanted"))); expression.Evaluate(Exchange(("wanted", "A-1"))).Should().Be("10"); expression.Evaluate(Exchange(("wanted", "B-2"))).Should().Be("20"); } [Fact] public void A_number_is_bound_as_a_number() { var id = new XPathExpr("/orders/order[total > $min]/@id") .WithParameters(("min", new HeaderExpression("min"))) .Evaluate(Exchange(("min", 15))); id.Should().Be("B-2", "an int must reach XPath as a number, not as the text '15'"); } [Fact] public void A_decimal_is_bound_invariantly() { // A comma decimal separator would make the same route match different documents on // different machines, which is the class of bug the template engine already ruled out. var id = new XPathExpr("/orders/order[total > $min]/@id") .WithParameters(("min", new HeaderExpression("min"))) .Evaluate(Exchange(("min", 15.5m))); id.Should().Be("B-2"); } [Fact] public void Several_parameters_bind_together() { var id = new XPathExpr("/orders/order[total > $min and total < $max]/@id") .WithParameters(("min", new HeaderExpression("min")), ("max", new HeaderExpression("max"))) .Evaluate(Exchange(("min", 5), ("max", 15))); id.Should().Be("A-1"); } [Fact] public void Bindings_added_in_two_calls_are_both_kept() { var id = new XPathExpr("/orders/order[total > $min and total < $max]/@id") .WithParameters(("min", new HeaderExpression("min"))) .WithParameters(("max", new HeaderExpression("max"))) .Evaluate(Exchange(("min", 5), ("max", 15))); id.Should().Be("A-1"); } // ── The point of the exercise ── [Fact] public void A_value_carrying_XPath_syntax_stays_a_value() { var expression = new XPathExpr("/orders/order[@id=$id]/total") .WithParameters(("id", new HeaderExpression("wanted"))); var hostile = expression.Evaluate(Exchange(("wanted", "B-2' or '1'='1"))); hostile.Should().BeNull( "the value is compared, not parsed: no order has that literal id, so nothing matches"); } [Fact] public void A_parameterised_expression_refuses_the_template_form_instead_of_dropping_its_bindings() { // Review finding: the first cut serialised to ${xpath(path)} — the constant path was the // point being made, but the serialised form had lost its bindings, so evaluating it would // fail on the unbound $id. The same refusal the result type already gets applies here. var expression = new XPathExpr("/orders/order[@id=$id]/total") .WithParameters(("id", new HeaderExpression("wanted"))); var act = () => expression.ToTemplateString(); act.Should().Throw().WithMessage("*bindings would be dropped*"); } [Fact] public void A_sourced_expression_refuses_the_template_form_instead_of_silently_reading_the_body() { var expression = new XPathExpr("/orders/order[1]/total").From(new HeaderExpression("doc")); var act = () => expression.ToTemplateString(); act.Should().Throw().WithMessage("*read the body instead*"); } // ── Composition and refusals ── [Fact] public void Parameters_compose_with_a_source_and_a_result_type() { var exchange = new Exchange(new Message("")); exchange.In.Headers["doc"] = Orders; exchange.In.Headers["wanted"] = "A-1"; var value = new XPathExpr("/orders/order[@id=$id]/total", XPathResult.String) .From(new HeaderExpression("doc")) .WithParameters(("id", new HeaderExpression("wanted"))) .Evaluate(exchange); value.Should().Be("10"); } [Fact] public void Parameters_work_in_a_condition() { var predicate = (IPredicateExpression)new XPathExpr("/orders/order[@id=$id]") .WithParameters(("id", new HeaderExpression("wanted"))); predicate.Matches(Exchange(("wanted", "B-2"))).Should().BeTrue(); predicate.Matches(Exchange(("wanted", "Z-9"))).Should().BeFalse(); } [Fact] public void A_name_written_with_its_dollar_sign_is_refused() { var act = () => new XPathExpr("/orders/order[@id=$id]") .WithParameters(("$id", new HeaderExpression("wanted"))); act.Should().Throw().WithMessage("*without the '$'*"); } [Fact] public void A_prefixed_variable_does_not_borrow_an_unprefixed_binding() { // Review follow-up: resolution used to match on the local name alone, so $x:id quietly // resolved to the binding named "id". WithParameters can only bind local names — it rejects // even a leading '$' — so a prefixed variable can never have a binding, and the honest // answer is the engine's own loud "variable not defined", not a silent match. var act = () => new XPathExpr("/orders/order[@id=$x:id]/total") .WithNamespaces(("x", "urn:acme")) .WithParameters(("id", new HeaderExpression("wanted"))) .Evaluate(Exchange(("wanted", "B-2"))); act.Should().Throw(); } [Fact] public void An_unbound_variable_in_the_path_fails_loudly() { var act = () => new XPathExpr("/orders/order[@id=$missing]/total") .WithParameters(("id", new HeaderExpression("wanted"))) .Evaluate(Exchange(("wanted", "B-2"))); act.Should().Throw(); } [Fact] public async Task A_parameterised_expression_works_where_the_DSL_takes_an_expression() { var seen = new List(); await using var context = new RouteContext(); context.AddRoutes(r => r.From("direct://xpath-params") .SetHeader("total", new XPathExpr("/orders/order[@id=$id]/total") .WithParameters(("id", new HeaderExpression("wanted")))) .Process(e => seen.Add(e.In.Headers["total"]))); await context.Start(); var producer = context.GetEndpoint("direct://xpath-params").CreateProducer(); await producer.Start(); await producer.Process(Exchange(("wanted", "A-1"))); await producer.Process(Exchange(("wanted", "B-2"))); seen.Should().Equal(10, 20); } } Path: redb-route/tests/redb.Route.Tests/Expressions/XPathParityOptionsTests.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/Expressions/XPathParityOptionsTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Expressions; using XPathExpr = redb.Route.Expressions.XPathExpression; namespace redb.Route.Tests.Expressions; /// /// The remaining option-level gaps against Camel's XPath language: reaching namespaces from the /// DSL, and trimming extracted text. /// public class XPathParityOptionsTests { private const string Namespaced = """ A-1 """; private const string Padded = """ John a b """; private static IExchange Exchange(string xml) => new Exchange(new Message(xml)); // ── Namespaces ── [Fact] public void A_namespaced_document_is_queryable_from_the_DSL() { var value = new XPathExpr("/e:Envelope/e:Body/o:order/o:id") .WithNamespaces( ("e", "http://schemas.xmlsoap.org/soap/envelope/"), ("o", "urn:acme:orders")) .Evaluate(Exchange(Namespaced)); value.Should().Be("A-1"); } [Fact] public void The_prefixes_are_the_expressions_own_and_need_not_match_the_document() { // The document says env:; the expression says whatever it likes, as long as the URI matches. var value = new XPathExpr("/soap:Envelope/soap:Body/ord:order/ord:id") .WithNamespaces( ("soap", "http://schemas.xmlsoap.org/soap/envelope/"), ("ord", "urn:acme:orders")) .Evaluate(Exchange(Namespaced)); value.Should().Be("A-1"); } [Fact] public void WithNamespaces_returns_a_new_expression() { var bare = new XPathExpr("/e:Envelope"); var bound = bare.WithNamespaces(("e", "http://schemas.xmlsoap.org/soap/envelope/")); bound.Should().NotBeSameAs(bare); ((IPredicateExpression)bound).Matches(Exchange(Namespaced)).Should().BeTrue(); // Without a binding the prefix is not merely unmatched — the path will not run at all, // which is why a namespaced document was unreachable from the DSL rather than just awkward. var act = () => bare.Evaluate(Exchange(Namespaced)); act.Should().Throw().WithMessage("*Namespace Manager*"); } [Fact] public void The_namespace_binding_survives_the_other_options() { var value = new XPathExpr("/soap:Envelope/soap:Body/ord:order/ord:id", XPathResult.String) .WithNamespaces( ("soap", "http://schemas.xmlsoap.org/soap/envelope/"), ("ord", "urn:acme:orders")) .From(new HeaderExpression("doc")) .Evaluate(WithHeader()); value.Should().Be("A-1"); static IExchange WithHeader() { var exchange = new Exchange(new Message("")); exchange.In.Headers["doc"] = Namespaced; return exchange; } } // ── Trim ── [Fact] public void Text_keeps_its_whitespace_unless_asked_otherwise() { new XPathExpr("/order/name").Evaluate(Exchange(Padded)).Should().Be(" John "); } [Fact] public void Trimmed_removes_the_surrounding_whitespace() { new XPathExpr("/order/name").Trimmed().Evaluate(Exchange(Padded)).Should().Be("John"); } [Fact] public void Trimmed_reaches_every_value_of_a_node_set() { // This is the case XPath cannot answer for itself: normalize-space() takes the first node // of a node-set, so several padded values have no in-language fix. new XPathExpr("/order/tags/tag").Trimmed().Evaluate(Exchange(Padded)) .Should().Equal("a", "b"); } [Fact] public void Trimmed_applies_to_a_string_result_too() { new XPathExpr("/order/name", XPathResult.String).Trimmed() .Evaluate(Exchange(Padded)).Should().Be("John"); } [Fact] public void Trimmed_can_be_turned_back_off() { new XPathExpr("/order/name").Trimmed().Trimmed(false) .Evaluate(Exchange(Padded)).Should().Be(" John "); } // ── A per-message path is now an expression ── [Fact] public async Task A_path_computed_per_message_can_be_used_where_an_expression_is_taken() { var seen = new List(); await using var context = new RouteContext(); context.AddRoutes(r => r.From("direct://dyn-xpath") .SetHeader("picked", new CompiledXPathExpression(e => e.In.GetHeader("selector")!)) .Process(e => seen.Add(e.In.Headers["picked"]))); await context.Start(); var producer = context.GetEndpoint("direct://dyn-xpath").CreateProducer(); await producer.Start(); var first = new Exchange(new Message("12")); first.In.Headers["selector"] = "/order/a"; await producer.Process(first); var second = new Exchange(new Message("12")); second.In.Headers["selector"] = "/order/b"; await producer.Process(second); seen.Should().Equal(1, 2); } } Path: redb-route/tests/redb.Route.Tests/Expressions/XPathPredicateSemanticsTests.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/Expressions/XPathPredicateSemanticsTests.cs ---- using AwesomeAssertions; using redb.Route.Core; using redb.Route.Expressions; using XPathExpr = redb.Route.Expressions.XPathExpression; namespace redb.Route.Tests.Expressions; /// /// XPath in a condition position asks whether the path matched, not what the matched node says. /// /// This is XPath 1.0, not a house rule: a node-set is true when it is non-empty, and the node's /// content never enters the question. The distinction is invisible until the content happens to /// look falsy — <discount>0</discount>, an empty <vip/>, a /// <flag>false</flag> — and then a matched node reads as "no match". /// /// /// The give-away that the old reading was a defect rather than a choice is that it disagreed with /// itself: one <discount>0</discount> was false while two of them were true, /// because a multi-node result never got flattened to a scalar. /// /// /// Asking for a CLR type is a different question and keeps its own answer: /// XPath<bool>("/order/flag") reads the node's text, so it is false. So does an XPath /// expression that already produces a scalar — string(...), count(...) > 0 — which /// is read by the one DSL truthiness rule like any other value. /// /// public class XPathPredicateSemanticsTests { private const string Order = """ 0 false """; private const string TwoDiscounts = """ 0 0 """; // ── Harness ── // // One context per run: a route added after Start() is not started, so sharing a context // between two runs inside one test silently answers "did not pass" for the second one. private static async Task PassesFilter(string id, redb.Route.Abstractions.IExpression expression, string xml) { await using var context = new RouteContext(); var passed = false; context.AddRoutes(r => r.From($"direct://xp-{id}") .Filter(expression) .Process(_ => passed = true) .EndFilter()); await Send(context, $"xp-{id}", xml); return passed; } private static async Task MatchesWhen(string id, redb.Route.Abstractions.IExpression expression, string xml) { await using var context = new RouteContext(); var matched = false; context.AddRoutes(r => r.From($"direct://xp-{id}") .Choice() .When(expression) .Process(_ => matched = true) .EndChoice()); await Send(context, $"xp-{id}", xml); return matched; } private static async Task Send(RouteContext context, string id, string xml) { await context.Start(); var producer = context.GetEndpoint($"direct://{id}").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message(xml))); } // ── The spelling the semantics exist for ── [Fact] public async Task An_expression_goes_straight_into_a_condition_verb() { // A compile-time guard, not a runtime one. Condition verbs are overloaded on IExpression // and IPredicate both, so an expression that implemented IPredicate would make this call // ambiguous and cost the language the very spelling the semantics were added for. The rest // of this class passes expressions through an IExpression-typed parameter, which would have // hidden that. var passed = false; await using var context = new RouteContext(); context.AddRoutes(r => r.From("direct://xp-direct") .Filter(new XPathExpr("/order/discount")) .Process(_ => passed = true) .EndFilter()); await context.Start(); var producer = context.GetEndpoint("direct://xp-direct").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message(Order))); passed.Should().BeTrue(); } // ── The node-set question ── [Fact] public async Task A_path_that_matches_nothing_is_false() { var passed = await PassesFilter("miss", new XPathExpr("/order/missing"), Order); passed.Should().BeFalse(); } [Fact] public async Task A_matched_node_holding_zero_is_still_a_match() { var passed = await PassesFilter("zero", new XPathExpr("/order/discount"), Order); passed.Should().BeTrue("the element exists; XPath 1.0 reads a non-empty node-set as true"); } [Fact] public async Task A_matched_empty_element_is_still_a_match() { var passed = await PassesFilter("vip", new XPathExpr("/order/vip"), Order); passed.Should().BeTrue("an element with no content is an element that matched"); } [Fact] public async Task A_matched_node_holding_the_word_false_is_still_a_match() { var passed = await PassesFilter("flag", new XPathExpr("/order/flag"), Order); passed.Should().BeTrue("the node's text is not the question a bare path asks"); } [Fact] public async Task Two_matched_nodes_are_a_match() { var passed = await PassesFilter("two", new XPathExpr("/order/discount"), TwoDiscounts); passed.Should().BeTrue(); } [Fact] public async Task One_match_and_two_matches_answer_the_same_way() { var one = await PassesFilter("cons1", new XPathExpr("/order/discount"), Order); var two = await PassesFilter("cons2", new XPathExpr("/order/discount"), TwoDiscounts); one.Should().Be(two, "the same path over the same element name cannot flip on how many matched"); } [Fact] public async Task When_reads_a_path_the_same_way_Filter_does() { var matched = await MatchesWhen("when", new XPathExpr("/order/discount"), Order); matched.Should().BeTrue(); } // ── The other two questions, unchanged ── [Fact] public async Task Asking_for_a_CLR_bool_still_reads_the_node_text() { var passed = await PassesFilter("typed", new TypedXPathExpression("/order/flag"), Order); passed.Should().BeFalse("XPath asks to convert the node's text, and the text is 'false'"); } [Fact] public async Task An_XPath_boolean_function_keeps_XPath_semantics() { var present = await PassesFilter("fn1", new XPathExpr("boolean(/order/discount)"), Order); var absent = await PassesFilter("fn2", new XPathExpr("boolean(/order/missing)"), Order); present.Should().BeTrue(); absent.Should().BeFalse(); } [Fact] public async Task An_XPath_scalar_result_is_read_by_the_one_DSL_truthiness_rule() { // string() produces a scalar, so the node-set question never arises and the DSL rule // applies exactly as it would to a header holding "0". var zeroText = await PassesFilter("str", new XPathExpr("string(/order/discount)"), Order); var counted = await PassesFilter("cnt", new XPathExpr("count(/order/discount) > 0"), Order); zeroText.Should().BeFalse(); counted.Should().BeTrue(); } } Path: redb-route/tests/redb.Route.Tests/Expressions/XPathResultTypeTests.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/Expressions/XPathResultTypeTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Expressions; using XPathExpr = redb.Route.Expressions.XPathExpression; namespace redb.Route.Tests.Expressions; /// /// The XPath-level result type — Camel's resultQName — as distinct from the CLR type the /// caller converts to. String, number and boolean are XPath's own coercions, so the engine /// performs them; node-set and node differ only in how many matches survive. /// public class XPathResultTypeTests { private const string Order = """ 0 7 a b c """; private static IExchange Exchange() => new Exchange(new Message(Order)); // ── String ── [Fact] public void String_keeps_the_text_instead_of_smart_parsing_it() { var asNodeSet = new XPathExpr("/order/discount").Evaluate(Exchange()); var asString = new XPathExpr("/order/discount", XPathResult.String).Evaluate(Exchange()); asNodeSet.Should().Be(0, "a node-set result is smart-parsed, and '0' parses as a number"); asString.Should().Be("0", "string() asked for text, so text is what comes back"); } [Fact] public void String_of_a_path_that_matched_nothing_is_empty() { var value = new XPathExpr("/order/missing", XPathResult.String).Evaluate(Exchange()); value.Should().BeEmpty(); } // ── Number ── [Fact] public void Number_converts_the_text_the_way_XPath_does() { var value = new XPathExpr("/order/qty", XPathResult.Number).Evaluate(Exchange()); value.Should().Be(7d); } [Fact] public void Number_of_a_path_that_matched_nothing_is_NaN() { var value = new XPathExpr("/order/missing", XPathResult.Number).Evaluate(Exchange()); double.IsNaN(value).Should().BeTrue(); } // ── Boolean ── [Fact] public void Boolean_is_existence_for_a_path() { var present = new XPathExpr("/order/discount", XPathResult.Boolean).Evaluate(Exchange()); var absent = new XPathExpr("/order/missing", XPathResult.Boolean).Evaluate(Exchange()); present.Should().BeTrue("boolean() of a non-empty node-set is true whatever the node holds"); absent.Should().BeFalse(); } // ── Node against NodeSet ── [Fact] public void Node_keeps_only_the_first_match_while_NodeSet_keeps_all() { var nodeSet = new XPathExpr("/order/tags/tag").Evaluate(Exchange()); var node = new XPathExpr("/order/tags/tag", XPathResult.Node).Evaluate(Exchange()); nodeSet.Should().Be("a, b, c"); node.Should().Be("a"); } [Fact] public void Node_of_a_path_that_matched_nothing_is_absent() { var value = new XPathExpr("/order/missing", XPathResult.Node).Evaluate(Exchange()); value.Should().BeNull(); } // ── Composition with the CLR type ── [Fact] public void The_XPath_type_and_the_CLR_type_compose() { var value = new TypedXPathExpression("/order/qty", XPathResult.Number).Evaluate(Exchange()); value.Should().Be(7); } // ── Template serialization ── [Fact] public void A_default_expression_still_serializes_to_a_template() { new XPathExpr("/order/qty").ToTemplateString().Should().Be("${xpath(/order/qty)}"); } [Fact] public void A_result_type_that_the_template_cannot_carry_is_refused_rather_than_dropped() { var act = () => new XPathExpr("/order/qty", XPathResult.String).ToTemplateString(); act.Should().Throw() .WithMessage("*only a path*"); } } Path: redb-route/tests/redb.Route.Tests/Expressions/XmlEntityExpansionTests.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/Expressions/XmlEntityExpansionTests.cs ---- using System.Text; using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Expressions; namespace redb.Route.Tests.Expressions; /// /// A message body is somebody else's XML, whatever transport carried it. Evaluating an XPath over one /// used to parse it with the expanding loader, so a 452-byte body with nested internal entities cost /// the worker hundreds of thousands of characters — and that is the small version. Reported while /// preparing the AS4 connector, 2026-09-25. /// public class XmlEntityExpansionTests { private static string BillionLaughs(int levels = 5, int fanOut = 10) { var sb = new StringBuilder(""); for (var i = 1; i <= levels; i++) { sb.Append($""); } return sb.Append($"]>&lol{levels};").ToString(); } private static IExchange WithBody(object body) => new Exchange(new Message(body)); [Fact] public void An_xpath_over_a_body_with_a_dtd_is_refused_not_expanded() { var exchange = WithBody(BillionLaughs()); var act = () => new XPathExpression("/lolz").Evaluate(exchange); // Refused, and refused loudly: a route that cannot read the body must not quietly carry on // with an empty value either. act.Should().Throw().Which.ToString().Should().Contain("DTD"); } [Fact] public void An_ordinary_xml_body_still_evaluates() { var exchange = WithBody("7"); new XPathExpression("/order/id").Evaluate(exchange).Should().Be("7"); } } Path: redb-route/tests/redb.Route.Tests/Extensions/RouteContextExtensionsTests.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/Extensions/RouteContextExtensionsTests.cs ---- using System.Reflection; using Microsoft.Extensions.DependencyInjection; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Extensions; namespace redb.Route.Tests.Extensions; /// /// Tests for and convenience constructors. /// public class RouteContextExtensionsTests { // ─── AddComponents ─────────────────────────────────────────────── [Fact] public void AddComponents_RegistersComponentsFromAssembly() { var ctx = new RouteContext(); ctx.AddComponents(typeof(StubComponentA).Assembly); ctx.HasComponent("stub-a").Should().BeTrue(); ctx.HasComponent("stub-b").Should().BeTrue(); } [Fact] public void AddComponents_SkipsAlreadyRegistered() { var ctx = new RouteContext(); // "direct" is built-in ctx.HasComponent("direct").Should().BeTrue(); // scanning this test assembly should not throw or overwrite built-in ctx.AddComponents(typeof(StubComponentA).Assembly); ctx.HasComponent("direct").Should().BeTrue(); } [Fact] public void AddComponents_SkipsAbstractAndInterface() { var ctx = new RouteContext(); ctx.AddComponents(typeof(AbstractStubComponent).Assembly); ctx.HasComponent("abstract-stub").Should().BeFalse(); } [Fact] public void AddComponents_SkipsTypesRequiringCtorArgs() { var ctx = new RouteContext(); // Should not throw even though CtorArgComponent requires args ctx.Invoking(c => c.AddComponents(typeof(CtorArgComponent).Assembly)) .Should().NotThrow(); } [Fact] public void AddComponents_SetsContextOnComponentBase() { var ctx = new RouteContext(); ctx.AddComponents(typeof(StubComponentA).Assembly); var comp = ctx.GetComponent(); comp.Should().NotBeNull(); comp!.Context.Should().BeSameAs(ctx); } [Fact] public void AddComponents_ReturnsSameContext_ForFluent() { var ctx = new RouteContext(); var result = ctx.AddComponents(typeof(StubComponentA).Assembly); result.Should().BeSameAs(ctx); } [Fact] public void AddComponents_MultipleAssemblies() { var ctx = new RouteContext(); ctx.AddComponents(typeof(StubComponentA).Assembly, typeof(RouteContext).Assembly); ctx.HasComponent("stub-a").Should().BeTrue(); } // ─── Convenience constructor ───────────────────────────────────── [Fact] public void ServiceProviderCtor_RegistersProvider() { var sp = new ServiceCollection().BuildServiceProvider(); var ctx = new RouteContext(sp); ctx.GetServiceProvider().Should().BeSameAs(sp); } [Fact] public void ServiceProviderCtor_RegistersBuiltInComponents() { var sp = new ServiceCollection().BuildServiceProvider(); var ctx = new RouteContext(sp, contextId: "test-sp"); ctx.ContextId.Should().Be("test-sp"); ctx.HasComponent("direct").Should().BeTrue(); ctx.HasComponent("seda").Should().BeTrue(); ctx.HasComponent("timer").Should().BeTrue(); ctx.HasComponent("mock").Should().BeTrue(); ctx.HasComponent("log").Should().BeTrue(); } [Fact] public void ServiceProviderCtor_ThrowsOnNullProvider() { Action act = () => new RouteContext(serviceProvider: null!); act.Should().Throw(); } // ─── Stub components for assembly scanning ─────────────────────── public class StubComponentA : ComponentBase { public override string Scheme => "stub-a"; public override IEndpoint CreateEndpoint(EndpointUri uri) => throw new NotSupportedException(); } public class StubComponentB : ComponentBase { public override string Scheme => "stub-b"; public override IEndpoint CreateEndpoint(EndpointUri uri) => throw new NotSupportedException(); } public abstract class AbstractStubComponent : ComponentBase { public override string Scheme => "abstract-stub"; public override IEndpoint CreateEndpoint(EndpointUri uri) => throw new NotSupportedException(); } public class CtorArgComponent : ComponentBase { private readonly string _required; public CtorArgComponent(string required) => _required = required; public override string Scheme => "ctor-arg"; public override IEndpoint CreateEndpoint(EndpointUri uri) => throw new NotSupportedException(); } } Path: redb-route/tests/redb.Route.Tests/Extensions/RouteHealthCheckTests.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/Extensions/RouteHealthCheckTests.cs ---- using Microsoft.Extensions.Diagnostics.HealthChecks; using NSubstitute; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Extensions; namespace redb.Route.Tests.Extensions; /// /// Tests for per-route status and endpoint statistics. /// public class RouteHealthCheckTests : IAsyncLifetime { private readonly RouteContext _context = new(); public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { await _context.DisposeAsync(); GC.SuppressFinalize(this); } [Fact] public async Task NoRoutes_ReturnsDegraded() { var healthCheck = new RouteHealthCheck(_context); var result = await healthCheck.CheckHealthAsync(CreateContext()); result.Status.Should().Be(HealthStatus.Degraded); result.Description.Should().Contain("No routes"); } [Fact] public async Task AllRoutesStarted_ReturnsHealthy() { _context.AddRoutes(r => { r.From("direct://health-source") .Process(e => { }); }); await _context.Start(); var healthCheck = new RouteHealthCheck(_context); var result = await healthCheck.CheckHealthAsync(CreateContext()); result.Status.Should().Be(HealthStatus.Healthy); result.Description.Should().Contain("1 route(s) running"); } [Fact] public async Task WithRoutes_IncludesRouteCount() { _context.AddRoutes(r => { r.From("direct://a") .Process(e => { }); }); _context.AddRoutes(r => { r.From("direct://b") .Process(e => { }); }); await _context.Start(); var healthCheck = new RouteHealthCheck(_context); var result = await healthCheck.CheckHealthAsync(CreateContext()); result.Status.Should().Be(HealthStatus.Healthy); result.Data.Should().ContainKey("routeCount"); result.Data["routeCount"].Should().Be(2); } [Fact] public async Task WithRoutes_IncludesRouteDetails() { _context.AddRoutes(r => { r.From("direct://meta") .RouteId("test-route") .Process(e => { }); }); await _context.Start(); var healthCheck = new RouteHealthCheck(_context); var result = await healthCheck.CheckHealthAsync(CreateContext()); result.Data.Should().ContainKey("routes"); var routes = result.Data["routes"] as List; routes.Should().NotBeNull(); routes!.Count.Should().Be(1); var routeDict = routes[0] as Dictionary; routeDict.Should().NotBeNull(); routeDict!["routeId"].Should().Be("test-route"); routeDict["status"].Should().Be("Started"); } [Fact] public async Task ErroredRoute_ReturnsUnhealthy() { _context.AddRoutes(r => { r.From("direct://err") .RouteId("errored-route") .Process(e => { }); }); await _context.Start(); // Manually set route to Errored state var route = _context.Routes.First(r => r.RouteId == "errored-route"); route.Status = RouteStatus.Errored; var healthCheck = new RouteHealthCheck(_context); var result = await healthCheck.CheckHealthAsync(CreateContext()); result.Status.Should().Be(HealthStatus.Unhealthy); result.Description.Should().Contain("errors detected"); } [Fact] public async Task StoppedRoute_ReturnsDegraded() { _context.AddRoutes(r => { r.From("direct://stopped") .RouteId("stopped-route") .Process(e => { }); }); await _context.Start(); await _context.StopRoute("stopped-route"); var healthCheck = new RouteHealthCheck(_context); var result = await healthCheck.CheckHealthAsync(CreateContext()); result.Status.Should().Be(HealthStatus.Degraded); result.Description.Should().Contain("degraded"); } [Fact] public void Constructor_NullContext_Throws() { var act = () => new RouteHealthCheck((IRouteContext)null!); act.Should().Throw(); } [Fact] public async Task ASendSideEndpointThatKnowsItIsBroken_MakesTheContextDegraded_UnderItsMaskedUri() { _context.AddComponent(new ConditionComponent()); _context.AddRoutes(r => r.From("direct://health-sender").Process(_ => { })); await _context.Start(); var endpoint = (ConditionEndpoint)_context.GetEndpoint("cond://broker?password=s3cret-pw&host=b1"); endpoint.Condition = (EndpointHealthStatus.Critical, "The broker blocks publishing: low on disk"); var result = await new RouteHealthCheck(_context).CheckHealthAsync(CreateContext()); result.Status.Should().Be(HealthStatus.Degraded, "a send-side endpoint never makes a running context Unhealthy"); var listed = result.Data["endpoints"].Should().BeAssignableTo>().Which .Should().ContainSingle().Which.Should().BeAssignableTo>().Which; listed["uri"].Should().BeOfType().Which.Should().Contain("broker").And.Contain(EndpointUri.Redacted); listed["endpointHealth"].Should().Be("Critical"); listed["reason"].Should().Be("The broker blocks publishing: low on disk"); System.Text.Json.JsonSerializer.Serialize(result.Data).Should().NotContain("s3cret-pw"); // The condition clears, and the endpoint returns to its computed status by itself. endpoint.Condition = null; var cleared = await new RouteHealthCheck(_context).CheckHealthAsync(CreateContext()); cleared.Status.Should().Be(HealthStatus.Healthy); cleared.Data.Should().NotContainKey("endpoints"); } [Fact] public async Task AnErrorThatQuotesACredentialedUri_ReachesThePayloadMasked() { // A connector's exception may quote the URI it failed on, password and all; the payload is often read by // unauthenticated probes. _context.AddRoutes(r => r.From("direct://health-leak").Process(_ => throw new InvalidOperationException( "None of the endpoints were reachable: amqp://svc:Sup3rS3cret@broker:5672 (password=Sup3rS3cret)"))); await _context.Start(); var producer = _context.GetEndpoint("direct://health-leak").CreateProducer(); await producer.Start(); try { await producer.Process(new Exchange(new Message("x"))); } catch (InvalidOperationException) { } var result = await new RouteHealthCheck(_context).CheckHealthAsync(CreateContext()); var payload = System.Text.Json.JsonSerializer.Serialize(result.Data); payload.Should().Contain("svc:" + EndpointUri.Redacted + "@broker", "the error is still there, masked"); payload.Should().NotContain("Sup3rS3cret"); } [Fact] public async Task ManyBrokenSendSideEndpoints_AreListedUpToTheCap_AndCounted() { _context.AddComponent(new ConditionComponent()); _context.AddRoutes(r => r.From("direct://health-many").Process(_ => { })); await _context.Start(); for (var i = 0; i < 1000; i++) { var endpoint = (ConditionEndpoint)_context.GetEndpoint($"cond://dynamic-{i}"); if (i % 2 == 0) endpoint.Condition = (EndpointHealthStatus.Failed, "down"); } var endpointsBefore = _context.GetEndpoints().Count; var result = await new RouteHealthCheck(_context).CheckHealthAsync(CreateContext()); result.Status.Should().Be(HealthStatus.Degraded); ((IReadOnlyList)result.Data["endpoints"]).Should().HaveCount(RouteHealthCheck.MaxListedEndpoints); result.Data["endpointsNotListed"].Should().Be(500 - RouteHealthCheck.MaxListedEndpoints); _context.GetEndpoints().Should().HaveCount(endpointsBefore, "a probe reads endpoints, it never creates one"); } [Fact] public async Task AnIdleSendSideEndpoint_DoesNotDegradeTheContext() { // Only a state that says "broken" counts; a Warning (idle, a few recent errors) on the send side does not. _context.AddComponent(new ConditionComponent()); _context.AddRoutes(r => r.From("direct://health-idle").Process(_ => { })); await _context.Start(); ((ConditionEndpoint)_context.GetEndpoint("cond://idle")).Condition = (EndpointHealthStatus.Warning, "No activity for 30 min"); var result = await new RouteHealthCheck(_context).CheckHealthAsync(CreateContext()); result.Status.Should().Be(HealthStatus.Healthy); result.Data.Should().NotContainKey("endpoints"); } /// An endpoint whose transport condition the test sets. private sealed class ConditionComponent : ComponentBase { public override string Scheme => "cond"; public override IEndpoint CreateEndpoint(EndpointUri uri) => new ConditionEndpoint(uri, this); } private sealed class ConditionOptions : EndpointOptions { public override void Validate() { } } private sealed class ConditionEndpoint(EndpointUri uri, IComponent component) : EndpointBase(uri, component, new ConditionOptions()) { public (EndpointHealthStatus Status, string Reason)? Condition { get; set; } protected override (EndpointHealthStatus Status, string Reason)? TransportCondition => Condition; public override IProducer CreateProducer() => throw new NotSupportedException(); public override IConsumer CreateConsumer(IProcessor processor) => throw new NotSupportedException(); } private static HealthCheckContext CreateContext() { return new HealthCheckContext { Registration = new HealthCheckRegistration( "test", Substitute.For(), HealthStatus.Unhealthy, Array.Empty()) }; } } Path: redb-route/tests/redb.Route.Tests/Extensions/RouteHostedServiceTests.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/Extensions/RouteHostedServiceTests.cs ---- using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using redb.Route.Core; using redb.Route.Extensions; namespace redb.Route.Tests.Extensions; /// /// Tests for . /// public class RouteHostedServiceTests : IAsyncLifetime { private readonly RouteContext _context = new(); private readonly ILogger _logger = NullLogger.Instance; public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { await _context.DisposeAsync(); GC.SuppressFinalize(this); } [Fact] public void Constructor_NullEngine_Throws() { var act = () => new RouteHostedService( null!, Array.Empty(), _logger); act.Should().Throw(); } [Fact] public void Constructor_NullConfigurators_Throws() { var act = () => new RouteHostedService( _context, null!, _logger); act.Should().Throw(); } [Fact] public void Constructor_NullLogger_Throws() { var act = () => new RouteHostedService( _context, Array.Empty(), null!); act.Should().Throw(); } [Fact] public async Task StartAsync_CallsConfiguratorsAndStartsEngine() { var configured = false; var configurator = Substitute.For(); configurator.When(c => c.Configure(Arg.Any())) .Do(_ => { configured = true; _context.AddRoutes(r => { r.From("direct://hosted") .Process(e => { }); }); }); var service = new RouteHostedService(_context, new[] { configurator }, _logger); await service.StartAsync(CancellationToken.None); configured.Should().BeTrue(); _context.Routes.Should().HaveCount(1); configurator.Received(1).Configure(_context); } [Fact] public async Task StopAsync_StopsEngine() { _context.AddRoutes(r => { r.From("direct://stop-test") .Process(e => { }); }); var service = new RouteHostedService( _context, Array.Empty(), _logger); await service.StartAsync(CancellationToken.None); _context.Routes.Should().HaveCount(1); await service.StopAsync(CancellationToken.None); // Routes are cleared on Stop — recompiled from builders on next Start _context.Routes.Should().BeEmpty(); } [Fact] public async Task DisposeAsync_DisposesEngine() { var service = new RouteHostedService( _context, Array.Empty(), _logger); // Should not throw await service.DisposeAsync(); } [Fact] public async Task StartAsync_NoConfigurators_StartsEmpty() { var service = new RouteHostedService( _context, Array.Empty(), _logger); await service.StartAsync(CancellationToken.None); _context.Routes.Should().BeEmpty(); } [Fact] public async Task StartAsync_MultipleConfigurators_AllApplied() { var c1 = Substitute.For(); var c2 = Substitute.For(); var service = new RouteHostedService(_context, new[] { c1, c2 }, _logger); await service.StartAsync(CancellationToken.None); c1.Received(1).Configure(_context); c2.Received(1).Configure(_context); } } Path: redb-route/tests/redb.Route.Tests/Extensions/ServiceCollectionExtensionsTests.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/Extensions/ServiceCollectionExtensionsTests.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Diagnostics.HealthChecks; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Extensions; namespace redb.Route.Tests.Extensions; /// /// Tests for DI registration via . /// public class ServiceCollectionExtensionsTests { [Fact] public void AddRedbRoute_RegistersEngine() { var services = new ServiceCollection(); services.AddLogging(); services.AddRedbRoute(); var sp = services.BuildServiceProvider(); var ctx = sp.GetService(); ctx.Should().NotBeNull(); } [Fact] public void AddRedbRoute_RegistersIRouteContext() { var services = new ServiceCollection(); services.AddLogging(); services.AddRedbRoute(); var sp = services.BuildServiceProvider(); var ctx = sp.GetService(); ctx.Should().NotBeNull(); } [Fact] public void AddRedbRoute_EngineSingleton_ReturnsSameInstance() { var services = new ServiceCollection(); services.AddLogging(); services.AddRedbRoute(); var sp = services.BuildServiceProvider(); var e1 = sp.GetRequiredService(); var e2 = sp.GetRequiredService(); e1.Should().BeSameAs(e2); } [Fact] public void AddRedbRoute_WithInlineRoutes_RegistersConfigurator() { var services = new ServiceCollection(); services.AddLogging(); services.AddRedbRoute(route => { route.AddRoutes(r => { r.From("direct://di-test") .Process(_ => { }); }); }); var sp = services.BuildServiceProvider(); var configurators = sp.GetServices(); configurators.Should().NotBeEmpty(); } [Fact] public void AddRouteBuilder_StartsWithoutResolutionError() // repro for GitHub issue #5 { var services = new ServiceCollection(); services.AddLogging(); services.AddRedbRoute(route => route.AddRouteBuilder()); var sp = services.BuildServiceProvider(); // The builder was registered only under the base type, but the configurator resolves the concrete // one — so host startup threw "No service for type 'Probe' has been registered". sp.GetRequiredService().Should().NotBeNull(); sp.GetRequiredService().Should().BeSameAs(sp.GetRequiredService()); // The actual startup path: running the configurators must not throw. var ctx = sp.GetRequiredService(); var act = () => { foreach (var c in sp.GetServices()) c.Configure(ctx); }; act.Should().NotThrow(); } [Fact] public void AddComponent_StartsWithoutResolutionError() // same defect as AddRouteBuilder { var services = new ServiceCollection(); services.AddLogging(); services.AddRedbRoute(route => route.AddComponent()); var sp = services.BuildServiceProvider(); sp.GetRequiredService().Should().NotBeNull(); var ctx = sp.GetRequiredService(); var act = () => { foreach (var c in sp.GetServices()) c.Configure(ctx); }; act.Should().NotThrow(); } private sealed class Probe : RouteBuilder { protected override void Configure() => From("direct://probe").Process(_ => { }); } private sealed class ProbeComponent : IComponent { public string Scheme => "probe"; public IEndpoint CreateEndpoint(EndpointUri uri) => throw new NotSupportedException(); } [Fact] public void AddRedbRouteCheck_RegistersHealthCheck() { var services = new ServiceCollection(); services.AddLogging(); services.AddRedbRoute(); services.AddHealthChecks() .AddRedbRouteCheck(); var sp = services.BuildServiceProvider(); var healthCheckProvider = sp.GetService(); healthCheckProvider.Should().NotBeNull(); } } Path: redb-route/tests/redb.Route.Tests/Fluent/CoreBuilderTests.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/Fluent/CoreBuilderTests.cs ---- using redb.Route.Core; namespace redb.Route.Tests.Fluent; public class DirectBuilderTests { [Fact] public void Endpoint_StartsWithDirectScheme() { var uri = Direct.Endpoint("myQueue").Build(); uri.Should().Be("direct:myQueue"); } [Fact] public void NullName_Throws() { var act = () => Direct.Endpoint(null!); act.Should().Throw(); } [Fact] public void EmptyName_Throws() { var act = () => Direct.Endpoint(""); act.Should().Throw(); } [Fact] public void ImplicitConversion_ReturnsUri() { string uri = Direct.Endpoint("test"); uri.Should().Be("direct:test"); } [Fact] public void ToString_ReturnsSameAsBuild() { var builder = Direct.Endpoint("abc"); builder.ToString().Should().Be(builder.Build()); } [Fact] public void RoundTrip_ParseAndReconstruct() { var original = Direct.Endpoint("my-queue").Build(); var parsed = EndpointUriParser.Parse(original); parsed.Scheme.Should().Be("direct"); parsed.Path.Should().Be("my-queue"); parsed.ToUriString().Should().Be(original); } } public class SedaBuilderTests { [Fact] public void Consume_StartsWithSedaScheme() { var uri = Seda.Consume("orders").Build(); uri.Should().StartWith("seda:orders"); } [Fact] public void Send_StartsWithSedaScheme() { var uri = Seda.Send("orders").Build(); uri.Should().StartWith("seda:orders"); } [Fact] public void NullName_Throws() { var act = () => Seda.Consume(null!); act.Should().Throw(); } [Fact] public void ConcurrentConsumers_SetsParam() { var uri = Seda.Consume("q").ConcurrentConsumers(4).Build(); uri.Should().Contain("concurrentConsumers=4"); } [Fact] public void Size_SetsParam() { var uri = Seda.Consume("q").Size(1000).Build(); uri.Should().Contain("size=1000"); } [Fact] public void Timeout_SetsParam() { var uri = Seda.Consume("q").Timeout(30000).Build(); uri.Should().Contain("timeout=30000"); } [Fact] public void FullChain_BuildsCorrectUri() { var uri = Seda.Consume("order-queue") .ConcurrentConsumers(4) .Size(500) .Timeout(60000) .Build(); uri.Should().StartWith("seda:order-queue?"); uri.Should().Contain("concurrentConsumers=4"); uri.Should().Contain("size=500"); uri.Should().Contain("timeout=60000"); } [Fact] public void ImplicitConversion_ReturnsUri() { string uri = Seda.Consume("test").ConcurrentConsumers(2); uri.Should().StartWith("seda:test?"); uri.Should().Contain("concurrentConsumers=2"); } [Fact] public void ToString_ReturnsSameAsBuild() { var builder = Seda.Send("q").Size(100); builder.ToString().Should().Be(builder.Build()); } [Fact] public void RoundTrip_ParseAndReconstruct() { var original = Seda.Consume("q").ConcurrentConsumers(4).Size(500).Build(); var parsed = EndpointUriParser.Parse(original); parsed.Scheme.Should().Be("seda"); parsed.Path.Should().Be("q"); parsed.RawParameters.Should().ContainKey("concurrentConsumers"); parsed.RawParameters.Should().ContainKey("size"); } [Fact] public void NoParams_ProducesCleanUri() { var uri = Seda.Consume("simple").Build(); uri.Should().Be("seda:simple"); } } public class TimerBuilderTests { [Fact] public void Every_StartsWithTimerScheme() { var uri = TimerDsl.Every("tick").Build(); uri.Should().StartWith("timer:tick"); } [Fact] public void Once_SetsRepeatCountToOne() { var uri = TimerDsl.Once("startup").Build(); uri.Should().Contain("repeatCount=1"); } [Fact] public void Period_SetsParam() { var uri = TimerDsl.Every("poll").Period(5000).Build(); uri.Should().Contain("period=5000"); } [Fact] public void Delay_SetsParam() { var uri = TimerDsl.Every("poll").Delay(2000).Build(); uri.Should().Contain("delay=2000"); } [Fact] public void RepeatCount_SetsParam() { var uri = TimerDsl.Every("poll").RepeatCount(10).Build(); uri.Should().Contain("repeatCount=10"); } [Fact] public void FullChain_BuildsCorrectUri() { var uri = TimerDsl.Every("heartbeat") .Period(5000) .Delay(1000) .Build(); uri.Should().StartWith("timer:heartbeat?"); uri.Should().Contain("period=5000"); uri.Should().Contain("delay=1000"); } [Fact] public void RoundTrip_ParseAndReconstruct() { var original = TimerDsl.Every("t").Period(1000).Build(); var parsed = EndpointUriParser.Parse(original); parsed.Scheme.Should().Be("timer"); parsed.Path.Should().Be("t"); parsed.RawParameters["period"].Should().Be("1000"); } } public class LogBuilderTests { [Fact] public void Info_SetsLogSchemeAndLevel() { var uri = LogDsl.Info("myLogger").Build(); uri.Should().StartWith("log:myLogger"); uri.Should().Contain("level=Info"); } [Fact] public void Debug_SetsLevel() { var uri = LogDsl.Debug("test").Build(); uri.Should().Contain("level=Debug"); } [Fact] public void Warn_SetsLevel() { var uri = LogDsl.Warn("test").Build(); uri.Should().Contain("level=Warn"); } [Fact] public void ShowHeaders_SetsParam() { var uri = LogDsl.Info("test").ShowHeaders().Build(); uri.Should().Contain("showHeaders=true"); } [Fact] public void ShowBody_SetsParam() { var uri = LogDsl.Info("test").ShowBody().Build(); uri.Should().Contain("showBody=true"); } [Fact] public void RoundTrip_ParseAndReconstruct() { var original = LogDsl.Info("app").ShowHeaders().ShowBody().Build(); var parsed = EndpointUriParser.Parse(original); parsed.Scheme.Should().Be("log"); parsed.RawParameters["level"].Should().Be("Information"); parsed.RawParameters["showHeaders"].Should().Be("true"); } } public class MockBuilderTests { [Fact] public void Endpoint_StartsWithMockScheme() { var uri = MockDsl.Endpoint("test").Build(); uri.Should().StartWith("mock:test"); } [Fact] public void ExpectedMessageCount_SetsParam() { var uri = MockDsl.Endpoint("test").ExpectedMessageCount(5).Build(); uri.Should().Contain("expectedMessageCount=5"); } [Fact] public void RoundTrip_ParseAndReconstruct() { var original = MockDsl.Endpoint("verify").ExpectedMessageCount(10).Build(); var parsed = EndpointUriParser.Parse(original); parsed.Scheme.Should().Be("mock"); parsed.Path.Should().Be("verify"); parsed.RawParameters["expectedMessageCount"].Should().Be("10"); } } Path: redb-route/tests/redb.Route.Tests/Idempotent/IdempotentClaimTests.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/Idempotent/IdempotentClaimTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Processors; namespace redb.Route.Tests.Idempotent; /// /// : a held key is told apart as in flight or confirmed, an abandoned claim is /// taken over by one caller only, and a repository that does not override it keeps what Add always meant. /// public class IdempotentClaimTests { [Fact] public async Task InMemory_NewKey_IsClaimed_ThenInFlight_ThenConfirmed() { var repository = new InMemoryIdempotentRepository(); (await repository.Claim("k", TimeSpan.FromMinutes(10))).Should().Be(IdempotentClaim.Claimed); (await repository.Claim("k", TimeSpan.FromMinutes(10))).Should().Be(IdempotentClaim.InFlight); await repository.Confirm("k"); (await repository.Claim("k", TimeSpan.FromMinutes(10))).Should().Be(IdempotentClaim.Confirmed); } [Fact] public async Task InMemory_AReleasedKey_IsClaimedAgain() { var repository = new InMemoryIdempotentRepository(); await repository.Claim("k", null); await repository.Remove("k"); (await repository.Claim("k", null)).Should().Be(IdempotentClaim.Claimed); } [Fact] public async Task InMemory_AnUnconfirmedClaimOlderThanTheAge_IsTakenOver_AndTheNewClaimIsInFlight() { var repository = new InMemoryIdempotentRepository(); await repository.Add("k"); await Task.Delay(60); (await repository.Claim("k", TimeSpan.FromMilliseconds(20))).Should().Be(IdempotentClaim.TakenOver); (await repository.Claim("k", TimeSpan.FromMinutes(1))).Should().Be(IdempotentClaim.InFlight, "the takeover is a fresh claim"); } [Fact] public async Task InMemory_WithoutAnAge_AnOldUnconfirmedClaim_StaysInFlight() { var repository = new InMemoryIdempotentRepository(); await repository.Add("k"); await Task.Delay(30); (await repository.Claim("k", null)).Should().Be(IdempotentClaim.InFlight); } [Fact] public async Task InMemory_AConfirmedClaim_IsNeverTakenOver() { var repository = new InMemoryIdempotentRepository(); await repository.Add("k"); await repository.Confirm("k"); await Task.Delay(30); (await repository.Claim("k", TimeSpan.FromMilliseconds(1))).Should().Be(IdempotentClaim.Confirmed); } [Fact] public async Task InMemory_ManyCallersTakingOverOneAbandonedClaim_OneWins() { var repository = new InMemoryIdempotentRepository(); await repository.Add("k"); await Task.Delay(60); var outcomes = await Task.WhenAll(Enumerable.Range(0, 32) .Select(_ => Task.Run(() => repository.Claim("k", TimeSpan.FromMilliseconds(20))))); outcomes.Count(o => o == IdempotentClaim.TakenOver).Should().Be(1); outcomes.Where(o => o != IdempotentClaim.TakenOver).Should().AllBeEquivalentTo(IdempotentClaim.InFlight); } [Fact] public async Task ARepositoryThatDoesNotOverrideClaim_TakesAHeldKeyForConfirmed_AsAddAlwaysMeant() { IIdempotentRepository repository = new AddOnlyRepository(); (await repository.Claim("k", TimeSpan.FromMilliseconds(1))).Should().Be(IdempotentClaim.Claimed); (await repository.Claim("k", TimeSpan.FromMilliseconds(1))).Should().Be(IdempotentClaim.Confirmed); } [Fact] public async Task InMemory_StaleHolderAfterATakeover_SettlesNothing_TheNewHolderSettles() { var repository = new InMemoryIdempotentRepository(); var first = await repository.Lease("k", TimeSpan.FromMinutes(1)); first.Outcome.Should().Be(IdempotentClaim.Claimed); await Task.Delay(30); var second = await repository.Lease("k", TimeSpan.FromMilliseconds(1)); second.Outcome.Should().Be(IdempotentClaim.TakenOver); second.Token.Should().NotBe(first.Token); (await repository.Release("k", first.Token)).Should().BeFalse("the first holder's claim was taken over"); (await repository.Confirm("k", first.Token)).Should().BeFalse(); (await repository.Lease("k", null)).Outcome.Should().Be(IdempotentClaim.InFlight, "the new holder's claim stays, unconfirmed"); (await repository.Confirm("k", second.Token)).Should().BeTrue(); (await repository.Lease("k", null)).Should().Be(new IdempotentLease(IdempotentClaim.Confirmed, null)); } [Fact] public async Task InMemory_AKeyTakenByAdd_HasNoToken_AndNoTokenSettlesIt() { var repository = new InMemoryIdempotentRepository(); await repository.Add("k"); (await repository.Release("k", Guid.NewGuid().ToString("N"))).Should().BeFalse(); (await repository.Contains("k")).Should().BeTrue(); (await repository.Release("k", null)).Should().BeTrue("a null token removes the key as Remove does"); (await repository.Contains("k")).Should().BeFalse(); } [Fact] public async Task ARepositoryThatDoesNotOverrideLease_LeasesWithoutAToken_AndSettlesTheKey() { IIdempotentRepository repository = new AddOnlyRepository(); var lease = await repository.Lease("k", TimeSpan.FromMinutes(1)); lease.Should().Be(new IdempotentLease(IdempotentClaim.Claimed, null)); (await repository.Release("k", lease.Token)).Should().BeTrue(); (await repository.Contains("k")).Should().BeFalse("the default Release removes the key"); } /// A repository written before Claim: it implements the members it had then. private sealed class AddOnlyRepository : IIdempotentRepository { private readonly HashSet _keys = []; public Task Add(string key, CancellationToken ct = default) => Task.FromResult(_keys.Add(key)); public Task Confirm(string key, CancellationToken ct = default) => Task.CompletedTask; public Task Remove(string key, CancellationToken ct = default) => Task.FromResult(_keys.Remove(key)); public Task Contains(string key, CancellationToken ct = default) => Task.FromResult(_keys.Contains(key)); public Task Clear(CancellationToken ct = default) { _keys.Clear(); return Task.CompletedTask; } } } Path: redb-route/tests/redb.Route.Tests/Idempotent/IdempotentUnitOfWorkTests.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/Idempotent/IdempotentUnitOfWorkTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Processors; namespace redb.Route.Tests.Idempotent; /// /// When the idempotent consumer confirms or removes its key (Apache Camel's defaults, completionEager=false and /// removeOnFailure=true): at the end of the exchange's unit of work, not at the end of the block. A failure anywhere /// in the exchange takes the key back, so the redelivery is processed again; a key claimed inside a transaction follows /// the transaction instead. /// public class IdempotentUnitOfWorkTests { private static Exchange Delivery(string id) => new(new Message("order") { Headers = { ["messageId"] = id } }); private static string MessageId(IExchange ex) => ex.In.GetHeader("messageId")!; private static async Task Start(RouteContext context, string uri) { await context.Start(); var producer = context.GetEndpoint(uri).CreateProducer(); await producer.Start(); return producer; } [Fact] public async Task A_failure_after_the_block_takes_the_key_back() { var repo = new InMemoryIdempotentRepository(); var work = 0; var failNext = true; await using var context = new RouteContext(); context.AddRoutes(r => r .From("direct://uow-after") .IdempotentConsumer(repo, MessageId) .Process(_ => work++) .EndIdempotentConsumer() .Process(_ => { if (!failNext) return; failNext = false; throw new InvalidOperationException("a step after the block"); })); var producer = await Start(context, "direct://uow-after"); var first = () => producer.Process(Delivery("m-1")); await first.Should().ThrowAsync(); (await repo.Contains("m-1")).Should().BeFalse("the exchange failed, so its message must be processed again"); await producer.Process(Delivery("m-1")); work.Should().Be(2, "the redelivery is not a duplicate: the first attempt did not complete"); (await repo.Contains("m-1")).Should().BeTrue(); } [Fact] public async Task RollbackAll_in_the_block_takes_the_key_back() { var repo = new InMemoryIdempotentRepository(); var work = 0; await using var context = new RouteContext(); context.AddRoutes(r => r .From("direct://uow-rollback") .IdempotentConsumer(repo, MessageId) .Process(_ => work++) .RollbackAll() .EndIdempotentConsumer()); var producer = await Start(context, "direct://uow-rollback"); await producer.Process(Delivery("m-2")); work.Should().Be(1); (await repo.Contains("m-2")).Should().BeFalse( "a rollback-only exchange is not acknowledged; a key left behind would skip its redelivery as a duplicate"); } [Fact] public async Task A_route_called_with_the_exchange_shares_the_callers_unit_of_work() { var repo = new InMemoryIdempotentRepository(); await using var context = new RouteContext(); context.AddRoutes(r => { r.From("direct://uow-caller") .To("direct://uow-callee") .Process(_ => throw new InvalidOperationException("the caller fails after the callee returned")); r.From("direct://uow-callee") .IdempotentConsumer(repo, MessageId) .Process(_ => { }) .EndIdempotentConsumer(); }); var producer = await Start(context, "direct://uow-caller"); var send = () => producer.Process(Delivery("m-3")); await send.Should().ThrowAsync(); (await repo.Contains("m-3")).Should().BeFalse("the unit of work is the caller's, and the caller failed"); } [Fact] public async Task The_key_is_back_before_the_exchange_is_reported_failed() { var repo = new InMemoryIdempotentRepository(); var listener = new KeyAtFailure(repo, "m-4"); await using var context = new RouteContext(); context.AddLifecycleListener(listener); context.AddRoutes(r => r .From("direct://uow-order") .IdempotentConsumer(repo, MessageId) .Process(_ => { }) .EndIdempotentConsumer() .Process(_ => throw new InvalidOperationException("after the block"))); var producer = await Start(context, "direct://uow-order"); var send = () => producer.Process(Delivery("m-4")); await send.Should().ThrowAsync(); // The consumer settles the message after this point; a key still present here could skip a redelivery that // another consumer picks up at once. listener.KeyPresentAtFailure.Should().BeFalse(); } [Fact] public async Task A_redelivery_of_the_route_runs_a_block_that_failed_again() { var repo = new InMemoryIdempotentRepository(); var attempts = 0; IExchange? seen = null; await using var context = new RouteContext(); context.AddRoutes(r => r .From("direct://uow-redeliver-block") .OnException() .MaximumRedeliveries(1) .RedeliveryDelay(TimeSpan.FromMilliseconds(1)) .End() .IdempotentConsumer(repo, MessageId) .Process(ex => { seen = ex; if (++attempts == 1) throw new InvalidOperationException("the block fails once"); }) .EndIdempotentConsumer()); var producer = await Start(context, "direct://uow-redeliver-block"); await producer.Process(Delivery("m-5")); attempts.Should().Be(2, "the exchange holding the key is not a duplicate of itself"); seen!.Properties.Should().NotContainKey(IdempotentConsumerProcessor.DuplicatePropertyKey); (await repo.Contains("m-5")).Should().BeTrue(); } [Fact] public async Task A_redelivery_of_the_route_does_not_redo_a_block_that_succeeded() { var repo = new InMemoryIdempotentRepository(); var work = 0; var tail = 0; IExchange? seen = null; await using var context = new RouteContext(); context.AddRoutes(r => r .From("direct://uow-redeliver-tail") .OnException() .MaximumRedeliveries(1) .RedeliveryDelay(TimeSpan.FromMilliseconds(1)) .End() .IdempotentConsumer(repo, MessageId) .Process(_ => work++) .EndIdempotentConsumer() .Process(ex => { seen = ex; if (++tail == 1) throw new InvalidOperationException("a step after the block fails once"); })); var producer = await Start(context, "direct://uow-redeliver-tail"); await producer.Process(Delivery("m-6")); work.Should().Be(1, "Camel redelivers the failed step, not the block before it"); tail.Should().Be(2); seen!.Properties.Should().NotContainKey(IdempotentConsumerProcessor.DuplicatePropertyKey, "the redelivery is the same exchange, not a duplicate message"); (await repo.Contains("m-6")).Should().BeTrue(); } [Fact] public async Task A_split_branch_has_its_own_unit_of_work() { var repo = new InMemoryIdempotentRepository(); await using var context = new RouteContext(); context.AddRoutes(r => r .From("direct://uow-split") .Split(e => (IEnumerable)e.In.Body!, b => b .IdempotentConsumer(e => (string)e.In.Body!, repo, ib => ib .Process(_ => { })) .Process(e => { if ((string)e.In.Body! == "b") throw new InvalidOperationException("branch b fails after its block"); }))); var producer = await Start(context, "direct://uow-split"); // Split stops on the first failed branch and fails the exchange (stopOnException defaults to true). var send = () => producer.Process(new Exchange(new Message(new object?[] { "a", "b", "c" }))); await send.Should().ThrowAsync(); (await repo.Contains("a")).Should().BeTrue("branch a completed; its redelivery is skipped"); (await repo.Contains("b")).Should().BeFalse("its branch failed after the block"); (await repo.Contains("c")).Should().BeFalse("the split stopped before branch c"); } [Fact] public async Task A_rollback_takes_back_a_key_the_repository_keeps_outside_the_transaction() { var repo = new InMemoryIdempotentRepository(); var work = 0; await using var context = new RouteContext(); context.AddRoutes(r => r .From("direct://uow-tx-rollback") .Transacted() .IdempotentConsumer(repo, MessageId) .Process(_ => { if (++work == 1) throw new InvalidOperationException("the work fails, the transaction rolls back"); }) .EndIdempotentConsumer() .End()); var producer = await Start(context, "direct://uow-tx-rollback"); var first = () => producer.Process(Delivery("m-7")); await first.Should().ThrowAsync(); (await repo.Contains("m-7")).Should().BeFalse( "the work rolled back; an in-memory key is not part of the transaction and has to be removed"); await producer.Process(Delivery("m-7")); work.Should().Be(2); } /// /// A failure an error handler marked handled (Handled(true)) takes the key back, like any other failure: the /// handler answered the exchange, but the work the key guards never happened. Camel's IdempotentOnCompletion /// asks ExchangeHelper.isFailureHandled for exactly this case. /// [Fact] public async Task A_handled_failure_in_the_block_takes_the_key_back() { var repo = new InMemoryIdempotentRepository(); var work = 0; var failNext = true; await using var context = new RouteContext(); context.AddRoutes(r => r .From("direct://uow-handled-block") .OnException() .Handled(true) .End() .IdempotentConsumer(repo, MessageId) .Process(_ => { if (!failNext) { work++; return; } failNext = false; throw new InvalidOperationException("the block fails once"); }) .EndIdempotentConsumer()); var producer = await Start(context, "direct://uow-handled-block"); await producer.Process(Delivery("m-8")); (await repo.Contains("m-8")).Should().BeFalse( "the handler only answered the exchange; the redelivery has to run the work"); await producer.Process(Delivery("m-8")); work.Should().Be(1, "the redelivery is not a duplicate: the first attempt did not do the work"); (await repo.Contains("m-8")).Should().BeTrue(); } /// A handled failure after the block takes the key back too. [Fact] public async Task A_handled_failure_after_the_block_takes_the_key_back() { var repo = new InMemoryIdempotentRepository(); var work = 0; var failNext = true; await using var context = new RouteContext(); context.AddRoutes(r => r .From("direct://uow-handled-tail") .OnException() .Handled(true) .End() .IdempotentConsumer(repo, MessageId) .Process(_ => work++) .EndIdempotentConsumer() .Process(_ => { if (!failNext) return; failNext = false; throw new InvalidOperationException("a step after the block"); })); var producer = await Start(context, "direct://uow-handled-tail"); await producer.Process(Delivery("m-9")); (await repo.Contains("m-9")).Should().BeFalse( "the exchange did not get through, whatever the handler answered"); await producer.Process(Delivery("m-9")); work.Should().Be(2, "the block has to be redone"); (await repo.Contains("m-9")).Should().BeTrue(); } /// A handled failure after the last redelivery takes the key back. [Fact] public async Task A_handled_failure_after_the_redeliveries_takes_the_key_back() { var repo = new InMemoryIdempotentRepository(); var attempts = 0; await using var context = new RouteContext(); context.AddRoutes(r => r .From("direct://uow-handled-redelivery") .OnException() .MaximumRedeliveries(1) .RedeliveryDelay(TimeSpan.FromMilliseconds(1)) .Handled(true) .End() .IdempotentConsumer(repo, MessageId) .Process(_ => { attempts++; throw new InvalidOperationException("every attempt fails"); }) .EndIdempotentConsumer()); var producer = await Start(context, "direct://uow-handled-redelivery"); await producer.Process(Delivery("m-10")); attempts.Should().Be(2, "the handler answered after the redelivery, not before it"); (await repo.Contains("m-10")).Should().BeFalse( "the attempt the handler answered last still did no work"); } /// /// Continued(true) is not a handled failure (Camel clears failureHandled on continue): the route carries on /// with the exchange, so the key stays confirmed. /// [Fact] public async Task A_continued_failure_keeps_the_key() { var repo = new InMemoryIdempotentRepository(); await using var context = new RouteContext(); context.AddRoutes(r => r .From("direct://uow-continued") .OnException() .Continued(true) .End() .IdempotentConsumer(repo, MessageId) .Process(_ => throw new InvalidOperationException("continued")) .EndIdempotentConsumer()); var producer = await Start(context, "direct://uow-continued"); await producer.Process(Delivery("m-11")); (await repo.Contains("m-11")).Should().BeTrue( "a continued handler sets exceptionHandled, not failureHandled, so the key is confirmed"); } /// A failure caught by DoCatch is not a handled failure: the key stays. [Fact] public async Task A_failure_caught_by_do_catch_keeps_the_key() { var repo = new InMemoryIdempotentRepository(); await using var context = new RouteContext(); context.AddRoutes(r => r .From("direct://uow-docatch") .DoTry() .IdempotentConsumer(repo, MessageId) .Process(_ => throw new InvalidOperationException("caught inside the block")) .EndIdempotentConsumer() .DoCatch() .Process(_ => { }) .End()); var producer = await Start(context, "direct://uow-docatch"); await producer.Process(Delivery("m-12")); (await repo.Contains("m-12")).Should().BeTrue( "DoCatch sets exceptionHandled only — it says nothing about the work, so the key is not taken back"); } /// /// A key claimed inside a transaction follows the transaction: a failure inside .Transacted() rolls the /// transaction back before the route's handler runs, so the key goes with it, handled or not. The redelivery has to /// do the work again and take the key again. /// [Fact] public async Task A_handled_failure_inside_a_transaction_still_rolls_the_transaction_back() { var repo = new InMemoryIdempotentRepository(); var work = 0; await using var context = new RouteContext(); context.AddRoutes(r => r .From("direct://uow-handled-tx") .OnException() .Handled(true) .End() .Transacted() .IdempotentConsumer(repo, MessageId) .Process(_ => { work++; throw new InvalidOperationException("the work fails inside the transaction"); }) .EndIdempotentConsumer() .End()); var producer = await Start(context, "direct://uow-handled-tx"); await producer.Process(Delivery("m-13")); work.Should().Be(1); (await repo.Contains("m-13")).Should().BeFalse( "the transaction rolled back before the handler answered, so the redelivery has to do the work again"); } private sealed class KeyAtFailure(IIdempotentRepository repo, string key) : IRouteLifecycleListener { public bool? KeyPresentAtFailure { get; private set; } public async Task OnExchangeFailed(string routeId, IExchange exchange, Exception exception, CancellationToken ct) => KeyPresentAtFailure = await repo.Contains(key, ct); } } Path: redb-route/tests/redb.Route.Tests/Idempotent/NamedIdempotentRegistryTests.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/Idempotent/NamedIdempotentRegistryTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Components; using redb.Route.Core; using redb.Route.Processors; using Xunit; namespace redb.Route.Tests.Idempotent; /// /// Tests for the named IIdempotentRepositoryProvider registry (S1.1): /// AddIdempotentRepository, named DSL overload, default provider behavior. /// public class NamedIdempotentRegistryTests { [Fact] public void AddIdempotentRepository_RegistersUnderTheBareName() { var ctx = new RouteContext(); var repo = new InMemoryIdempotentRepository(); ctx.AddIdempotentRepository("orders", repo); var stored = ctx.GetFromRegistry("orders"); stored.Should().BeSameAs(repo); } [Fact] public void DefaultProvider_Get_ReturnsRegisteredRepository() { var ctx = new RouteContext(); var repo = new InMemoryIdempotentRepository(); ctx.AddIdempotentRepository("foo", repo); var provider = ctx.GetIdempotentRepositoryProvider(); var resolved = provider.Get("foo"); resolved.Should().BeSameAs(repo); } [Fact] public void DefaultProvider_Get_MissingName_ThrowsHelpfulMessage() { var ctx = new RouteContext(); var provider = ctx.GetIdempotentRepositoryProvider(); var act = () => provider.Get("missing"); act.Should().Throw() .WithMessage("*'missing'*") .WithMessage("*AddIdempotentRepository(\"missing\"*"); } [Fact] public void DefaultProvider_TryGet_ReturnsFalseOnMissing() { var ctx = new RouteContext(); var provider = ctx.GetIdempotentRepositoryProvider(); var ok = provider.TryGet("missing", out var repo); ok.Should().BeFalse(); repo.Should().BeNull(); } [Fact] public void DefaultProvider_TryGet_ReturnsTrueOnHit() { var ctx = new RouteContext(); var registered = new InMemoryIdempotentRepository(); ctx.AddIdempotentRepository("hit", registered); var provider = ctx.GetIdempotentRepositoryProvider(); var ok = provider.TryGet("hit", out var repo); ok.Should().BeTrue(); repo.Should().BeSameAs(registered); } [Fact] public void GetIdempotentRepositoryProvider_RespectsCustomServiceOverride() { var ctx = new RouteContext(); var custom = new StubProvider(); ctx.AddService(typeof(IIdempotentRepositoryProvider), custom); var resolved = ctx.GetIdempotentRepositoryProvider(); resolved.Should().BeSameAs(custom); } [Fact] public async Task NamedDsl_ResolvesAtCompile_AndDeduplicates() { await using var ctx = new RouteContext(); var repo = new InMemoryIdempotentRepository(); ctx.AddIdempotentRepository("orders", repo); var seen = new List(); ctx.AddRoutes(r => { r.From("direct://named-dedup") .IdempotentConsumer(e => e.In.Headers["MessageId"]?.ToString()!, "orders") .Process(e => seen.Add(e.In.Body)); }); await ctx.Start(); var producer = ctx.GetEndpoint("direct://named-dedup").CreateProducer(); await producer.Start(); var m1 = new Message { Body = "a" }; m1.Headers["MessageId"] = "k1"; var m2 = new Message { Body = "b" }; m2.Headers["MessageId"] = "k1"; var m3 = new Message { Body = "c" }; m3.Headers["MessageId"] = "k2"; await producer.Process(new Exchange(m1)); await producer.Process(new Exchange(m2)); await producer.Process(new Exchange(m3)); seen.Should().HaveCount(2); seen[0].Should().Be("a"); seen[1].Should().Be("c"); } [Fact] public async Task NamedDsl_MissingRegistration_ThrowsAtStart() { await using var ctx = new RouteContext(); ctx.AddRoutes(r => { r.From("direct://missing-named") .IdempotentConsumer(e => "x", "not-registered") .Process(_ => { }); }); var act = async () => await ctx.Start(); await act.Should().ThrowAsync() .WithMessage("*'not-registered'*"); } private sealed class StubProvider : IIdempotentRepositoryProvider { public IIdempotentRepository Get(string name) => throw new NotImplementedException(); public bool TryGet(string name, out IIdempotentRepository repository) { repository = null!; return false; } } } Path: redb-route/tests/redb.Route.Tests/Idempotent/RepositoryRegistryNameTests.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/Idempotent/RepositoryRegistryNameTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Components; using redb.Route.Core; using redb.Route.Processors; namespace redb.Route.Tests.Idempotent; /// /// Idempotent and claim-check repositories are found as every other registry reference is: by the bare name, checked /// for type (Camel's lookupByNameAndType). A bean declared in markup under dedup is the repository /// repository="#dedup" names; no idempotent: or claimcheck: key prefix exists. /// public class RepositoryRegistryNameTests : IAsyncLifetime { private readonly RouteContext _context = new(); public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { await _context.DisposeAsync(); GC.SuppressFinalize(this); } // ── Idempotent ──────────────────────────────────────────────────────── [Fact] public void A_repository_registered_under_its_bare_name_is_found() { var repo = new InMemoryIdempotentRepository(); _context.AddToRegistry("dedup", repo); _context.GetIdempotentRepositoryProvider().Get("dedup").Should().BeSameAs(repo); _context.GetIdempotentRepositoryProvider().Get("#dedup").Should().BeSameAs(repo, "#name is the registry key as is"); } [Fact] public void AddIdempotentRepository_registers_under_the_bare_name() { var repo = new InMemoryIdempotentRepository(); _context.AddIdempotentRepository("orders", repo); _context.GetFromRegistry("orders").Should().BeSameAs(repo); } [Fact] public void Nothing_under_the_name_is_named_as_such_with_the_ways_to_register() { var act = () => _context.GetIdempotentRepositoryProvider().Get("missing"); act.Should().Throw() .WithMessage("*Nothing is registered under 'missing'*AddIdempotentRepository* _context.GetIdempotentRepositoryProvider().Get("dedup"); act.Should().Throw() .WithMessage("*'dedup'*System.String*not an IIdempotentRepository*"); } [Fact] public void TryGet_is_false_for_nothing_and_loud_for_another_type() { _context.GetIdempotentRepositoryProvider().TryGet("missing", out _).Should().BeFalse(); _context.AddToRegistry("dedup", 42); var act = () => _context.GetIdempotentRepositoryProvider().TryGet("dedup", out _); act.Should().Throw().WithMessage("*System.Int32*"); } // ── Claim check ─────────────────────────────────────────────────────── [Fact] public void A_claim_check_repository_is_found_by_its_bare_name() { var repo = new InMemoryClaimCheckRepository(); _context.AddToRegistry("payloads", repo); _context.ResolveClaimCheckRepository("payloads").Should().BeSameAs(repo); } [Fact] public void AddClaimCheckRepository_registers_under_the_bare_name() { var repo = new InMemoryClaimCheckRepository(); _context.AddClaimCheckRepository("payloads", repo); _context.GetFromRegistry("payloads").Should().BeSameAs(repo); } [Fact] public void Another_type_under_a_claim_check_name_is_named_by_its_type() { _context.AddToRegistry("payloads", new InMemoryIdempotentRepository()); var act = () => _context.ResolveClaimCheckRepository("payloads"); act.Should().Throw() .WithMessage("*'payloads'*InMemoryIdempotentRepository*not an IClaimCheckRepository*"); } [Fact] public void The_default_claim_check_repository_is_a_context_service_not_a_registry_key() { var repo = new InMemoryClaimCheckRepository(); _context.SetDefaultClaimCheckRepository(repo); _context.ResolveClaimCheckRepository().Should().BeSameAs(repo); _context.GetService().Should().BeSameAs(repo); _context.GetFromRegistry("claimcheck:__default").Should().BeNull(); } [Fact] public void Without_a_default_every_step_shares_one_in_memory_repository() { var first = _context.ResolveClaimCheckRepository(); var second = _context.ResolveClaimCheckRepository(); first.Should().BeOfType().And.BeSameAs(second); _context.GetFromRegistry("claimcheck:__default").Should().BeNull(); } } Path: redb-route/tests/redb.Route.Tests/Processors/AggregatorOwnershipTests.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/Processors/AggregatorOwnershipTests.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.Processors; /// /// An aggregation group outlives the calls that fed it, so it holds exchanges of its own, as Camel copies an exchange /// into its aggregation repository: the body of a message waiting in a group stays open until the group is done, the /// completed group runs on in a DI scope of its own, and everything the group held is released once, after it has gone /// on down the route. The aggregator used to keep the caller's exchange itself, which the caller disposes as soon as /// the aggregator returns: a group completing later went on with closed streams and a released scope. /// public class AggregatorOwnershipTests { private sealed class TrackedStream() : MemoryStream("payload"u8.ToArray()) { public int Disposals; protected override void Dispose(bool disposing) { if (disposing) Interlocked.Increment(ref Disposals); base.Dispose(disposing); } } private sealed class ScopedProbe { public bool Used; } private sealed record Outcome(int FirstBodyDisposalsWhenCompleted, bool ScopeWorked); private static async Task<(RouteContext Context, ConcurrentQueue Completed)> Route() { var services = new ServiceCollection(); services.AddScoped(); var provider = services.BuildServiceProvider(); var context = new RouteContext($"aggregator-owner-{Guid.NewGuid():N}"); context.SetServiceProvider(provider); context.AddComponent(new DirectComponent()); var completed = new ConcurrentQueue(); context.AddRoutes(r => r.From("direct://owner-in") .Aggregate(_ => "g", static (acc, next) => { var bodies = acc.In.Body as List ?? [acc.In.Body]; bodies.Add(next.In.Body); acc.In.Body = bodies; return acc; }, e => e.In.Body is List { Count: 2 }) .Process(e => { var first = (TrackedStream)((List)e.In.Body!)[0]!; var scopeWorked = false; try { if (e.ServiceProvider is { } services) { services.GetRequiredService().Used = true; scopeWorked = true; } } catch (ObjectDisposedException) { } // a released scope: the assertion reports it completed.Enqueue(new Outcome(first.Disposals, scopeWorked)); })); await context.Start(); return (context, completed); } private static async Task Send(RouteContext context, object body) { var template = new ProducerTemplate(context); template.Start(); await template.SendAsync("direct://owner-in", body); // the caller disposes its exchange right after await template.DisposeAsync(); } [Fact] public async Task A_body_waiting_in_a_group_stays_open_until_the_group_is_done_and_is_then_disposed_once() { var (context, completed) = await Route(); var first = new TrackedStream(); await Send(context, first); await Send(context, "second"); completed.Single().FirstBodyDisposalsWhenCompleted.Should().Be(0, "the group still carries it"); first.Disposals.Should().Be(1, "and releases it once it has gone on down the route"); await context.DisposeAsync(); } [Fact] public async Task A_completed_group_runs_on_in_a_live_DI_scope() { var (context, completed) = await Route(); await Send(context, new TrackedStream()); await Send(context, "second"); completed.Single().ScopeWorked.Should().BeTrue(); await context.DisposeAsync(); } } Path: redb-route/tests/redb.Route.Tests/Processors/AggregatorProcessorTests.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/Processors/AggregatorProcessorTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Processors; namespace redb.Route.Tests.Processors; /// Tests for . public class AggregatorProcessorTests { /// Aggregates exchanges by correlation key and fires on completion. [Fact] public async Task Process_AggregatesByKey_FiresOnCompletion() { IExchange? result = null; var target = new DelegateProcessor(ex => result = ex); var aggregator = new AggregatorProcessor( correlationKey: ex => ex.In.GetHeader("orderId")!, aggregationStrategy: (old, @new) => { var count = old.GetProperty("count") + 1; old.Properties["count"] = count; return old; }, completionPredicate: ex => ex.GetProperty("count") >= 2, target: target); var ex1 = new Exchange(new Message("item-1")); ex1.In.Headers["orderId"] = "order-123"; ex1.Properties["count"] = 1; await aggregator.Process(ex1); result.Should().BeNull(); // Not complete yet var ex2 = new Exchange(new Message("item-2")); ex2.In.Headers["orderId"] = "order-123"; await aggregator.Process(ex2); result.Should().NotBeNull(); // Now complete } /// Different correlation keys aggregate independently. [Fact] public async Task Process_DifferentKeys_IndependentAggregation() { var results = new List(); var target = new DelegateProcessor(ex => results.Add(ex.In.GetHeader("key")!)); var aggregator = new AggregatorProcessor( correlationKey: ex => ex.In.GetHeader("key")!, aggregationStrategy: (old, _) => old, completionPredicate: _ => true, // Complete immediately target: target); var ex1 = new Exchange(new Message("a")); ex1.In.Headers["key"] = "A"; await aggregator.Process(ex1); var ex2 = new Exchange(new Message("b")); ex2.In.Headers["key"] = "B"; await aggregator.Process(ex2); results.Should().Equal("A", "B"); } /// PendingGroupCount tracks active groups. [Fact] public async Task PendingGroupCount_TracksActiveGroups() { var target = new DelegateProcessor(_ => { }); var aggregator = new AggregatorProcessor( correlationKey: ex => ex.In.GetHeader("key")!, aggregationStrategy: (old, @new) => old, completionPredicate: ex => ex.GetProperty("done") == 1, target: target); var ex1 = new Exchange(new Message("a")); ex1.In.Headers["key"] = "group-1"; await aggregator.Process(ex1); aggregator.PendingGroupCount.Should().Be(1); var ex2 = new Exchange(new Message("b")); ex2.In.Headers["key"] = "group-2"; await aggregator.Process(ex2); aggregator.PendingGroupCount.Should().Be(2); } /// Single exchange completing immediately fires target once. [Fact] public async Task Process_ImmediateCompletion_FiresTarget() { var fired = 0; var target = new DelegateProcessor(_ => fired++); var aggregator = new AggregatorProcessor( correlationKey: _ => "single", aggregationStrategy: (old, _) => old, completionPredicate: _ => true, target: target); await aggregator.Process(new Exchange(new Message("data"))); fired.Should().Be(1); aggregator.PendingGroupCount.Should().Be(0); } // ────────────────── DSL compilation ────────────────── /// /// T0.3a — Symptom A: completed aggregate must reach the next step in the route. /// Today CompileAggregate wires a no-op DelegateProcessor as the AggregatorProcessor /// target, so completed aggregates silently disappear. Will be fixed in Phase 2. /// [Fact] public async Task RouteDsl_Aggregate_CompletedExchange_FlowsToNextStep() { await using var context = new RouteContext(); var downstream = new List(); context.AddRoutes(r => { r.From("direct://agg-complete") .Aggregate( correlationKey: _ => "k", aggregationStrategy: (old, neu) => { var sum = (int)(old.In.Body ?? 0) + (int)(neu.In.Body ?? 0); old.In.Body = sum; return old; }, completionPredicate: ex => (int)(ex.In.Body ?? 0) >= 3) .Process(e => downstream.Add((int)e.In.Body!)); }); await context.Start(); var producer = context.GetEndpoint("direct://agg-complete").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message(1))); await producer.Process(new Exchange(new Message(2))); downstream.Should().ContainSingle().Which.Should().Be(3); } /// /// T0.3b — Symptom B: pre-completion input exchanges must NOT leak past the /// aggregate step into downstream processors. Today the aggregator consumes the /// exchange into its group but PipelineProcessor still routes the original input /// further. Will be fixed in Phase 2 (tail-consuming wiring + exchange.Stop()). /// [Fact] public async Task RouteDsl_Aggregate_PreCompletionExchange_DoesNotLeakToTail() { await using var context = new RouteContext(); var downstream = new List(); context.AddRoutes(r => { r.From("direct://agg-leak") .Aggregate( correlationKey: _ => "k", aggregationStrategy: (old, neu) => { var sum = (int)(old.In.Body ?? 0) + (int)(neu.In.Body ?? 0); old.In.Body = sum; return old; }, completionPredicate: ex => (int)(ex.In.Body ?? 0) >= 100) .Process(e => downstream.Add((int)e.In.Body!)); }); await context.Start(); var producer = context.GetEndpoint("direct://agg-leak").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message(1))); await producer.Process(new Exchange(new Message(2))); // Group is not complete (sum=3 < 100), so nothing should flow downstream. downstream.Should().BeEmpty(); } /// /// The completed aggregate carries its size, its key and what completed it, as Camel's aggregate; the size is /// there while it collects too, for the completion predicate. /// [Fact] public async Task Process_PublishesAggregatedProperties_CompletedByPredicate() { IExchange? result = null; var aggregator = new AggregatorProcessor( correlationKey: ex => ex.In.GetHeader("orderId")!, aggregationStrategy: (old, _) => old, completionPredicate: ex => ex.GetProperty(ExchangePropertyKeys.AggregatedSize) >= 3, target: new DelegateProcessor(ex => result = ex)); for (var i = 0; i < 3; i++) { var ex = new Exchange(new Message(i)); ex.In.Headers["orderId"] = "o-1"; await aggregator.Process(ex); } result.Should().NotBeNull(); result!.GetProperty(ExchangePropertyKeys.AggregatedSize).Should().Be(3); result.GetProperty(ExchangePropertyKeys.AggregatedCorrelationKey).Should().Be("o-1"); result.GetProperty(ExchangePropertyKeys.AggregatedCompletedBy).Should().Be("predicate"); } /// A group completed by completionSize says so. [Fact] public async Task Process_CompletionSize_CompletesAndSaysSize() { var results = new List(); var aggregator = new AggregatorProcessor( correlationKey: _ => "k", aggregationStrategy: (old, _) => old, completionPredicate: _ => false, target: new DelegateProcessor(results.Add)) { CompletionSize = 2, }; for (var i = 0; i < 5; i++) await aggregator.Process(new Exchange(new Message(i))); results.Should().HaveCount(2); results.Should().OnlyContain(r => r.GetProperty(ExchangePropertyKeys.AggregatedSize) == 2 && r.GetProperty(ExchangePropertyKeys.AggregatedCompletedBy) == "size"); aggregator.PendingGroupCount.Should().Be(1); } /// A completion size below one is refused. [Fact] public void CompletionSize_BelowOne_Throws() { var act = () => new AggregatorProcessor(_ => "k", (o, _) => o, _ => false, new DelegateProcessor(_ => { })) { CompletionSize = 0, }; act.Should().Throw(); } } Path: redb-route/tests/redb.Route.Tests/Processors/AggregatorStopTests.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/Processors/AggregatorStopTests.cs ---- using System.Collections.Concurrent; using AwesomeAssertions; using Microsoft.Extensions.Logging; using redb.Route.Components; using redb.Route.Core; using redb.Route.Tests.Cluster; namespace redb.Route.Tests.Processors; /// /// An aggregation group still open when the context stops is completed (Camel forceCompletionOnStop) once the /// consumers have stopped — no more arrivals, producers still alive for what the completion sends on — or, without the /// option, dropped with a warning naming how many, as Camel drops an in-memory repository on stop. It used to be dropped /// without a word: the next start compiles a new aggregator and the old one's groups were simply gone. /// public class AggregatorStopTests { private static async Task<(RouteContext Context, ConcurrentQueue Completed, CapturingLoggerProvider Logs)> Route(bool force) { var logs = new CapturingLoggerProvider(); var context = new RouteContext($"aggregator-stop-{Guid.NewGuid():N}"); context.AddService(typeof(ILoggerFactory), LoggerFactory.Create(b => b.AddProvider(logs))); context.AddComponent(new DirectComponent()); var completed = new ConcurrentQueue(); context.AddRoutes(r => { var aggregate = r.From("direct://aggregate-in") .Aggregate(e => e.In.GetHeader("group") ?? "", static (acc, next) => { acc.In.Body = $"{acc.In.Body}+{next.In.Body}"; return acc; }, e => ((string?)e.In.Body)?.Split('+').Length >= 3); if (force) aggregate.ForceCompletionOnStop(); aggregate.Process(e => completed.Enqueue(e.In.Body)); }); await context.Start(); return (context, completed, logs); } private static async Task Send(RouteContext context, string body, string group) { var template = new ProducerTemplate(context); template.Start(); var message = new Message(body); message.Headers["group"] = group; await template.SendAsync("direct://aggregate-in", message); await template.DisposeAsync(); } [Fact] public async Task With_forceCompletionOnStop_an_open_group_completes_when_the_context_stops() { var (context, completed, _) = await Route(force: true); await Send(context, "a", "g1"); await Send(context, "b", "g1"); completed.Should().BeEmpty("the group is not complete yet"); await context.Stop(); completed.Should().Equal("a+b"); await context.DisposeAsync(); } [Fact] public async Task Without_it_an_open_group_is_dropped_on_stop_with_a_warning_naming_how_many() { var (context, completed, logs) = await Route(force: false); await Send(context, "a", "g1"); await Send(context, "b", "g2"); await context.Stop(); completed.Should().BeEmpty(); logs.Entries.Should().Contain(e => e.Level == LogLevel.Warning && e.Message.Contains("2 aggregation group")); await context.DisposeAsync(); } } Path: redb-route/tests/redb.Route.Tests/Processors/BeanIntegrationTests.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/Processors/BeanIntegrationTests.cs ---- using System; using System.Threading; using System.Threading.Tasks; using AwesomeAssertions; using Microsoft.Extensions.DependencyInjection; using redb.Route.Abstractions; using redb.Route.Components; using redb.Route.Core; using redb.Route.Definitions; using redb.Route.Processors; namespace redb.Route.Tests.Processors; /// /// Integration tests for Bean / Service Activator using full route pipeline with DirectComponent. /// [Trait("Category", "Integration")] public class BeanIntegrationTests : IAsyncLifetime { private readonly ServiceProvider _serviceProvider; private readonly RouteContext _context; public BeanIntegrationTests() { var services = new ServiceCollection() .AddSingleton(new OrderService()) .AddScoped() .AddSingleton(new PricingService()); _serviceProvider = services.BuildServiceProvider(); _context = new RouteContext(); } /// Creates an exchange with DI scope from the test ServiceProvider. private IExchange CreateExchange(object? body = null) { var factory = _serviceProvider.GetRequiredService(); return Exchange.Create(new Message(body), factory); } // ══════════════════════════════════════════════════════════════ // Async + CancellationToken — full pipeline // ══════════════════════════════════════════════════════════════ [Fact] public async Task AsyncWithCt_ResolvesServiceAndInvokes() { var def = new RouteDefinition(); def.From("direct://bean-async-ct"); def.Bean(async (svc, exchange, ct) => { var input = exchange.In.Body!.ToString()!; exchange.In.Body = await svc.ProcessOrderAsync(input, ct); }); var pipeline = def.CreateProcessor(_context); var exchange = CreateExchange("order-123"); await pipeline.Process(exchange); exchange.In.Body.Should().Be("processed:order-123"); } // ══════════════════════════════════════════════════════════════ // Async without CancellationToken // ══════════════════════════════════════════════════════════════ [Fact] public async Task AsyncNoCt_ResolvesServiceAndInvokes() { var def = new RouteDefinition(); def.From("direct://bean-async"); def.Bean(async (svc, exchange) => { var input = exchange.In.Body!.ToString()!; exchange.In.Body = await svc.ValidateOrderAsync(input); }); var pipeline = def.CreateProcessor(_context); var exchange = CreateExchange("order-456"); await pipeline.Process(exchange); exchange.In.Body.Should().Be("valid:order-456"); } // ══════════════════════════════════════════════════════════════ // Sync — header enrichment // ══════════════════════════════════════════════════════════════ [Fact] public async Task Sync_ResolvesServiceAndEnrichesHeaders() { var def = new RouteDefinition(); def.From("direct://bean-sync"); def.Bean((svc, exchange) => { var productId = exchange.In.Body!.ToString()!; exchange.In.Headers["price"] = svc.GetPrice(productId); }); var pipeline = def.CreateProcessor(_context); var exchange = CreateExchange("prod-A"); await pipeline.Process(exchange); exchange.In.Headers["price"].Should().Be(99.99m); } // ══════════════════════════════════════════════════════════════ // Missing ServiceProvider — throws // ══════════════════════════════════════════════════════════════ [Fact] public async Task NullServiceProvider_ThrowsInvalidOperation() { var def = new RouteDefinition(); def.From("direct://bean-no-sp"); def.Bean(async (svc, exchange, ct) => { exchange.In.Body = await svc.ProcessOrderAsync("x", ct); }); var pipeline = def.CreateProcessor(_context); // Exchange without DI scope var exchange = Exchange.Create(new Message("test"), null); var act = () => pipeline.Process(exchange); await act.Should().ThrowAsync() .WithMessage("*ServiceProvider*"); } // ══════════════════════════════════════════════════════════════ // Scoped service — new instance per exchange // ══════════════════════════════════════════════════════════════ [Fact] public async Task ScopedService_NewInstancePerExchange() { var def = new RouteDefinition(); def.From("direct://bean-scoped"); def.Bean((svc, exchange) => { svc.Increment(); exchange.Properties["count"] = svc.Count; exchange.Properties["instanceId"] = svc.InstanceId; }); var pipeline = def.CreateProcessor(_context); var ex1 = CreateExchange(); var ex2 = CreateExchange(); await pipeline.Process(ex1); await pipeline.Process(ex2); // Each exchange gets its own scoped instance ex1.Properties["count"].Should().Be(1); ex2.Properties["count"].Should().Be(1); ex1.Properties["instanceId"].Should().NotBe(ex2.Properties["instanceId"]); } // ══════════════════════════════════════════════════════════════ // Chained beans — multiple services in pipeline // ══════════════════════════════════════════════════════════════ [Fact] public async Task ChainedBeans_MultipleServicesInPipeline() { var def = new RouteDefinition(); def.From("direct://bean-chain"); def.Bean(async (svc, exchange, ct) => { exchange.In.Body = await svc.ProcessOrderAsync(exchange.In.Body!.ToString()!, ct); }); def.Bean((svc, exchange) => { exchange.In.Headers["price"] = svc.GetPrice(exchange.In.Body!.ToString()!); }); var pipeline = def.CreateProcessor(_context); var exchange = CreateExchange("item-X"); await pipeline.Process(exchange); exchange.In.Body.Should().Be("processed:item-X"); exchange.In.Headers["price"].Should().Be(99.99m); } // ══════════════════════════════════════════════════════════════ // CancellationToken — propagates to service method // ══════════════════════════════════════════════════════════════ [Fact] public async Task CancellationToken_PropagatedToServiceMethod() { using var cts = new CancellationTokenSource(); cts.Cancel(); var def = new RouteDefinition(); def.From("direct://bean-cancel"); def.Bean(async (svc, exchange, ct) => { exchange.In.Body = await svc.ProcessOrderAsync("x", ct); }); var pipeline = def.CreateProcessor(_context); var exchange = CreateExchange("test"); var act = () => pipeline.Process(exchange, cts.Token); await act.Should().ThrowAsync(); } // ══════════════════════════════════════════════════════════════ // Service throws — exception propagates through pipeline // ══════════════════════════════════════════════════════════════ [Fact] public async Task ServiceThrows_ExceptionPropagates() { var def = new RouteDefinition(); def.From("direct://bean-error"); def.Bean(async (svc, exchange, ct) => { await svc.FailAsync(ct); }); var pipeline = def.CreateProcessor(_context); var exchange = CreateExchange(); var act = () => pipeline.Process(exchange); await act.Should().ThrowAsync() .WithMessage("Service failure"); } // ══════════════════════════════════════════════════════════════ // Bean with downstream To — full route pattern // ══════════════════════════════════════════════════════════════ [Fact] public async Task BeanWithDownstream_FullRoutePattern() { // Register a consumer that captures the output string? captured = null; var endpoint = (DirectEndpoint)_context.GetEndpoint("direct:bean-sink"); var consumer = endpoint.CreateConsumer(new DelegateProcessor((e, _) => { captured = e.In.Body?.ToString(); return Task.CompletedTask; })); await consumer.Start(); try { var def = new RouteDefinition(); def.From("direct://bean-full"); def.Bean(async (svc, exchange, ct) => { exchange.In.Body = await svc.ProcessOrderAsync(exchange.In.Body!.ToString()!, ct); }); def.To("direct:bean-sink"); var pipeline = def.CreateProcessor(_context); var exchange = CreateExchange("order-789"); await pipeline.Process(exchange); captured.Should().Be("processed:order-789"); } finally { await consumer.Stop(); } } // ══════════════════════════════════════════════════════════════ // Properties preserved through Bean // ══════════════════════════════════════════════════════════════ [Fact] public async Task Bean_PreservesExchangeProperties() { var def = new RouteDefinition(); def.From("direct://bean-props"); def.Bean(async (svc, exchange, ct) => { exchange.In.Body = await svc.ProcessOrderAsync(exchange.In.Body!.ToString()!, ct); }); var pipeline = def.CreateProcessor(_context); var exchange = CreateExchange("test"); exchange.Properties["tenant"] = "acme"; exchange.In.Headers["correlationId"] = "abc-123"; await pipeline.Process(exchange); exchange.Properties["tenant"].Should().Be("acme"); exchange.In.Headers["correlationId"].Should().Be("abc-123"); exchange.In.Body.Should().Be("processed:test"); } // ══════════════════════════════════════════════════════════════ // Dispose // ══════════════════════════════════════════════════════════════ public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { await _context.DisposeAsync(); await _serviceProvider.DisposeAsync(); } // ══════════════════════════════════════════════════════════════ // Test services // ══════════════════════════════════════════════════════════════ public interface IOrderService { Task ProcessOrderAsync(string orderId, CancellationToken ct); Task ValidateOrderAsync(string orderId); Task FailAsync(CancellationToken ct); } public interface IPricingService { decimal GetPrice(string productId); } public interface IScopedCounter { Guid InstanceId { get; } int Count { get; } void Increment(); } private sealed class OrderService : IOrderService { public async Task ProcessOrderAsync(string orderId, CancellationToken ct) { ct.ThrowIfCancellationRequested(); await Task.Yield(); return $"processed:{orderId}"; } public async Task ValidateOrderAsync(string orderId) { await Task.Yield(); return $"valid:{orderId}"; } public Task FailAsync(CancellationToken ct) => throw new InvalidOperationException("Service failure"); } private sealed class PricingService : IPricingService { public decimal GetPrice(string productId) => 99.99m; } private sealed class ScopedCounter : IScopedCounter { public Guid InstanceId { get; } = Guid.NewGuid(); public int Count { get; private set; } public void Increment() => Count++; } } Path: redb-route/tests/redb.Route.Tests/Processors/BeanTests.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/Processors/BeanTests.cs ---- using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using AwesomeAssertions; using Microsoft.Extensions.DependencyInjection; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Definitions; namespace redb.Route.Tests.Processors; /// /// Unit tests for Bean / Service Activator DSL, step creation, and method invocation. /// public class BeanTests { // ══════════════════════════════════════════════════════════════ // DSL — async with CancellationToken // ══════════════════════════════════════════════════════════════ [Fact] public void DSL_AsyncWithCt_AddsBeanStep() { var def = new RouteDefinition(); def.Bean(async (svc, exchange, ct) => { exchange.In.Body = await svc.ProcessAsync(exchange.In.Body!.ToString()!, ct); }); var beanDef = def.Outputs.Should().ContainSingle().Which.Should().BeOfType().Subject; beanDef.ServiceType.Should().Be(typeof(ITestService)); beanDef.Method.Should().NotBeNull(); } [Fact] public void DSL_AsyncWithCt_NullMethod_Throws() { var def = new RouteDefinition(); var act = () => def.Bean((Func)null!); act.Should().Throw(); } // ══════════════════════════════════════════════════════════════ // DSL — async without CancellationToken // ══════════════════════════════════════════════════════════════ [Fact] public void DSL_AsyncNoCt_AddsBeanStep() { var def = new RouteDefinition(); def.Bean(async (svc, exchange) => { exchange.In.Body = await svc.ValidateAsync(exchange.In.Body!.ToString()!); }); var beanDef = def.Outputs.Should().ContainSingle().Which.Should().BeOfType().Subject; beanDef.ServiceType.Should().Be(typeof(ITestService)); } [Fact] public void DSL_AsyncNoCt_NullMethod_Throws() { var def = new RouteDefinition(); var act = () => def.Bean((Func)null!); act.Should().Throw(); } // ══════════════════════════════════════════════════════════════ // DSL — synchronous // ══════════════════════════════════════════════════════════════ [Fact] public void DSL_Sync_AddsBeanStep() { var def = new RouteDefinition(); def.Bean((svc, exchange) => { exchange.In.Headers["value"] = svc.GetValue(); }); var beanDef = def.Outputs.Should().ContainSingle().Which.Should().BeOfType().Subject; beanDef.ServiceType.Should().Be(typeof(ITestService)); } [Fact] public void DSL_Sync_NullMethod_Throws() { var def = new RouteDefinition(); var act = () => def.Bean((Action)null!); act.Should().Throw(); } // ══════════════════════════════════════════════════════════════ // BeanStep — normalized method delegates // ══════════════════════════════════════════════════════════════ [Fact] public async Task BeanStep_AsyncWithCt_InvokesMethod() { var service = new TestService(); var exchange = Exchange.Create(new Message("hello"), null); var def = new RouteDefinition(); def.From("direct://test"); def.Bean(async (svc, e, ct) => { e.In.Body = await svc.ProcessAsync(e.In.Body!.ToString()!, ct); }); var step = def.Outputs.OfType().Single(); await step.Method(service, exchange, CancellationToken.None); exchange.In.Body.Should().Be("hello_processed"); } [Fact] public async Task BeanStep_AsyncNoCt_InvokesMethod() { var service = new TestService(); var exchange = Exchange.Create(new Message("data"), null); var def = new RouteDefinition(); def.From("direct://test"); def.Bean(async (svc, e) => { e.In.Body = await svc.ValidateAsync(e.In.Body!.ToString()!); }); var step = def.Outputs.OfType().Single(); await step.Method(service, exchange, CancellationToken.None); exchange.In.Body.Should().Be("data_validated"); } [Fact] public async Task BeanStep_Sync_InvokesMethod() { var service = new TestService(); var exchange = Exchange.Create(new Message("test"), null); var def = new RouteDefinition(); def.From("direct://test"); def.Bean((svc, e) => { e.In.Headers["value"] = svc.GetValue(); }); var step = def.Outputs.OfType().Single(); await step.Method(service, exchange, CancellationToken.None); exchange.In.Headers["value"].Should().Be(42); } // ══════════════════════════════════════════════════════════════ // BeanStep — service type correctly captured // ══════════════════════════════════════════════════════════════ [Fact] public void BeanStep_CapturesCorrectServiceType_ForEachOverload() { var def = new RouteDefinition(); def.Bean(async (svc, e, ct) => { await Task.CompletedTask; }); def.Bean(async (svc, e) => { await Task.CompletedTask; }); def.Bean((svc, e) => { }); var beanDefs = def.Outputs.OfType().ToList(); beanDefs.Should().HaveCount(3); beanDefs[0].ServiceType.Should().Be(typeof(ITestService)); beanDefs[1].ServiceType.Should().Be(typeof(IAnotherService)); beanDefs[2].ServiceType.Should().Be(typeof(ITestService)); } // ══════════════════════════════════════════════════════════════ // DSL — chaining // ══════════════════════════════════════════════════════════════ [Fact] public void DSL_Bean_ReturnsSameDefinitionForChaining() { var def = new RouteDefinition(); var result = def.Bean((svc, e) => { }); result.Should().BeSameAs(def); } // ══════════════════════════════════════════════════════════════ // Test helpers // ══════════════════════════════════════════════════════════════ public interface ITestService { Task ProcessAsync(string input, CancellationToken ct); Task ValidateAsync(string input); int GetValue(); } public interface IAnotherService { void DoWork(); } private sealed class TestService : ITestService { public Guid InstanceId { get; } = Guid.NewGuid(); public Task ProcessAsync(string input, CancellationToken ct) => Task.FromResult($"{input}_processed"); public Task ValidateAsync(string input) => Task.FromResult($"{input}_validated"); public int GetValue() => 42; } } Path: redb-route/tests/redb.Route.Tests/Processors/ChoiceProcessorTests.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/Processors/ChoiceProcessorTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Processors; namespace redb.Route.Tests.Processors; /// Tests for and . public class ChoiceProcessorTests { /// First matching when-clause executes. [Fact] public async Task Process_FirstMatchingWhen_Executes() { var result = ""; var choice = new ChoiceProcessor() .When(ex => ex.In.Body is "A", new DelegateProcessor(_ => result = "branch-A")) .When(ex => ex.In.Body is "B", new DelegateProcessor(_ => result = "branch-B")); await choice.Process(new Exchange(new Message("A"))); result.Should().Be("branch-A"); } /// Second match is used when first doesn't match. [Fact] public async Task Process_SecondMatch_WhenFirstFails() { var result = ""; var choice = new ChoiceProcessor() .When(ex => ex.In.Body is "A", new DelegateProcessor(_ => result = "branch-A")) .When(ex => ex.In.Body is "B", new DelegateProcessor(_ => result = "branch-B")); await choice.Process(new Exchange(new Message("B"))); result.Should().Be("branch-B"); } /// Only first matching executes (short-circuit). [Fact] public async Task Process_OnlyFirstMatch_ShortCircuits() { var count = 0; var choice = new ChoiceProcessor() .When(_ => true, new DelegateProcessor(_ => count++)) .When(_ => true, new DelegateProcessor(_ => count++)); await choice.Process(new Exchange()); count.Should().Be(1); } /// Otherwise executes when no when-clause matches. [Fact] public async Task Process_NoMatch_Otherwise_Executes() { var result = ""; var choice = new ChoiceProcessor() .When(ex => ex.In.Body is "A", new DelegateProcessor(_ => result = "A")) .SetOtherwise(new DelegateProcessor(_ => result = "otherwise")); await choice.Process(new Exchange(new Message("X"))); result.Should().Be("otherwise"); } /// No match and no otherwise — nothing happens. [Fact] public async Task Process_NoMatch_NoOtherwise_DoesNothing() { var executed = false; var choice = new ChoiceProcessor() .When(ex => ex.In.Body is "A", new DelegateProcessor(_ => executed = true)); await choice.Process(new Exchange(new Message("X"))); executed.Should().BeFalse(); } /// WhenClauses property returns added clauses. [Fact] public void WhenClauses_ReturnsAll() { var choice = new ChoiceProcessor() .When(_ => true, new DelegateProcessor(_ => { })) .When(_ => false, new DelegateProcessor(_ => { })); choice.WhenClauses.Should().HaveCount(2); } /// WhenClause validates arguments. [Fact] public void WhenClause_NullPredicate_Throws() { // The cast only picks the overload: both the predicate and the delegate constructors reject null. var act = () => new WhenClause((redb.Route.Abstractions.IPredicate)null!, new DelegateProcessor(_ => { })); act.Should().Throw(); } } Path: redb-route/tests/redb.Route.Tests/Processors/CircuitBreakerProcessorTests.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/Processors/CircuitBreakerProcessorTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Processors; namespace redb.Route.Tests.Processors; /// Tests for . public class CircuitBreakerProcessorTests { [Fact] public async Task Process_Closed_PassesThrough() { var processed = false; var next = new DelegateProcessor(_ => processed = true); var cb = new CircuitBreakerProcessor(next, failureThreshold: 3); await cb.Process(new Exchange(new Message("data"))); processed.Should().BeTrue(); cb.State.Should().Be(CircuitState.Closed); } [Fact] public async Task Process_BelowThreshold_StaysClosed() { var callCount = 0; var next = new DelegateProcessor(_ => { callCount++; throw new InvalidOperationException("boom"); }); var cb = new CircuitBreakerProcessor(next, failureThreshold: 3); // 2 failures — still below threshold of 3 for (int i = 0; i < 2; i++) await cb.Process(new Exchange()); callCount.Should().Be(2); cb.State.Should().Be(CircuitState.Closed); } [Fact] public async Task Process_ReachesThreshold_OpensCircuit() { var next = new DelegateProcessor(_ => throw new InvalidOperationException("fail")); var cb = new CircuitBreakerProcessor(next, failureThreshold: 3); for (int i = 0; i < 3; i++) await cb.Process(new Exchange()); cb.State.Should().Be(CircuitState.Open); } [Fact] public async Task Process_Open_SetsCircuitBreakerOpenException() { var next = new DelegateProcessor(_ => throw new InvalidOperationException("fail")); var cb = new CircuitBreakerProcessor(next, failureThreshold: 2, resetTimeout: TimeSpan.FromMinutes(5)); // Trip the breaker for (int i = 0; i < 2; i++) await cb.Process(new Exchange()); cb.State.Should().Be(CircuitState.Open); // Next call should set CircuitBreakerOpenException var exchange = new Exchange(new Message("blocked")); await cb.Process(exchange); exchange.Exception.Should().BeOfType(); } [Fact] public async Task Process_Open_UsesFallback() { var fallbackUsed = false; var fallback = new DelegateProcessor(_ => fallbackUsed = true); var next = new DelegateProcessor(_ => throw new InvalidOperationException("fail")); var cb = new CircuitBreakerProcessor(next, failureThreshold: 2, resetTimeout: TimeSpan.FromMinutes(5), fallback: fallback); for (int i = 0; i < 2; i++) await cb.Process(new Exchange()); cb.State.Should().Be(CircuitState.Open); await cb.Process(new Exchange()); fallbackUsed.Should().BeTrue(); } [Fact] public async Task Process_Open_TransitionsToHalfOpen_AfterTimeout() { var next = new DelegateProcessor(_ => throw new InvalidOperationException("fail")); var cb = new CircuitBreakerProcessor(next, failureThreshold: 2, resetTimeout: TimeSpan.FromMilliseconds(100)); for (int i = 0; i < 2; i++) await cb.Process(new Exchange()); cb.State.Should().Be(CircuitState.Open); // Wait for reset timeout await Task.Delay(150); // Next call should be allowed (HalfOpen probe) var probe = new Exchange(new Message("probe")); await cb.Process(probe); // It will fail (our next still throws), so back to Open // But the state should have transitioned to HalfOpen first probe.Exception.Should().NotBeNull(); } [Fact] public async Task Process_HalfOpen_SuccessClosesCircuit() { var shouldFail = true; var next = new DelegateProcessor(_ => { if (shouldFail) throw new InvalidOperationException("fail"); }); var cb = new CircuitBreakerProcessor(next, failureThreshold: 2, resetTimeout: TimeSpan.FromMilliseconds(50)); // Trip breaker for (int i = 0; i < 2; i++) await cb.Process(new Exchange()); cb.State.Should().Be(CircuitState.Open); // Wait for timeout await Task.Delay(100); // Now make next succeed shouldFail = false; await cb.Process(new Exchange(new Message("recovery"))); cb.State.Should().Be(CircuitState.Closed); } [Fact] public async Task Process_ExchangeException_CountsAsFailure() { var next = new DelegateProcessor(ex => { ex.Exception = new InvalidOperationException("exchange-level failure"); }); var cb = new CircuitBreakerProcessor(next, failureThreshold: 2); for (int i = 0; i < 2; i++) await cb.Process(new Exchange()); cb.State.Should().Be(CircuitState.Open); } [Fact] public async Task Process_SuccessResetsFailureCount() { var callIndex = 0; var next = new DelegateProcessor(_ => { callIndex++; // Fail on calls 1,2 then succeed on call 3 then fail on 4,5 if (callIndex <= 2 || callIndex >= 4) throw new InvalidOperationException("fail"); }); var cb = new CircuitBreakerProcessor(next, failureThreshold: 3); // 2 failures await cb.Process(new Exchange()); await cb.Process(new Exchange()); cb.State.Should().Be(CircuitState.Closed); // 2 < 3 // 1 success — resets counter await cb.Process(new Exchange()); cb.State.Should().Be(CircuitState.Closed); // 2 more failures — total consecutive is only 2 await cb.Process(new Exchange()); await cb.Process(new Exchange()); cb.State.Should().Be(CircuitState.Closed); // still 2 < 3 } [Fact] public void Constructor_NullNext_Throws() { var act = () => new CircuitBreakerProcessor(null!); act.Should().Throw().WithParameterName("next"); } [Fact] public void Constructor_ZeroThreshold_Throws() { var act = () => new CircuitBreakerProcessor(new DelegateProcessor(_ => { }), failureThreshold: 0); act.Should().Throw(); } [Fact] public async Task Process_PreservesBody() { object? captured = null; var next = new DelegateProcessor(ex => captured = ex.In.Body); var cb = new CircuitBreakerProcessor(next, failureThreshold: 5); await cb.Process(new Exchange(new Message("important"))); captured.Should().Be("important"); } } /// Tests for . public class CircuitBreakerOpenExceptionTests { [Fact] public void Ctor_Message_SetsMessage() { var ex = new CircuitBreakerOpenException("circuit open"); ex.Message.Should().Be("circuit open"); } [Fact] public void Ctor_MessageAndInner_SetsInner() { var inner = new InvalidOperationException("root"); var ex = new CircuitBreakerOpenException("circuit open", inner); ex.InnerException.Should().BeSameAs(inner); } } Path: redb-route/tests/redb.Route.Tests/Processors/ClaimCheckDslTests.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/Processors/ClaimCheckDslTests.cs ---- using redb.Route.Abstractions; using redb.Route.Components; using redb.Route.Core; using redb.Route.Processors; namespace redb.Route.Tests.Processors; /// /// Tests for the .ClaimCheck(...) DSL: the Claim Check EIP reached from a route, /// including repository resolution (explicit instance, named registry entry, context default). /// public class ClaimCheckDslTests : IAsyncLifetime { private readonly RouteContext _context = new(); public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { await _context.DisposeAsync(); GC.SuppressFinalize(this); } /// Builds a route ending in a collector, runs one exchange through it. private async Task RunAsync(Action configure, object body) { IExchange? seen = null; _context.AddRoutes(r => { var def = r.From("direct://claim-in"); configure(def); def.Process(e => seen = e); }); await _context.Start(); var producer = _context.GetEndpoint("direct://claim-in").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message { Body = body })); seen.Should().NotBeNull("the route must reach its final step"); return seen!; } // ── Set / Get ─────────────────────────────────────────────────── [Fact] public async Task Set_ReplacesBodyWithClaimKey_AndStoresThePayload() { var repository = new InMemoryClaimCheckRepository(); var exchange = await RunAsync( def => def.ClaimCheck(repository, ClaimCheckOperation.Set, "order-42"), "a very large payload"); exchange.In.Body.Should().Be("order-42", "the body travels on as the claim key"); exchange.In.Headers[ClaimCheckHeaders.Key].Should().Be("order-42"); (await repository.Retrieve("order-42")).Should().NotBeNull(); } [Fact] public async Task SetThenGet_RestoresTheOriginalBody() { var repository = new InMemoryClaimCheckRepository(); var exchange = await RunAsync( def => def .ClaimCheck(repository, ClaimCheckOperation.Set, "order-42") .ClaimCheck(repository, ClaimCheckOperation.Get, "order-42"), "a very large payload"); exchange.In.Body.Should().Be("a very large payload"); } [Fact] public async Task GetAndRemove_DropsThePayloadFromTheStore() { var repository = new InMemoryClaimCheckRepository(); await RunAsync( def => def .ClaimCheck(repository, ClaimCheckOperation.Set, "order-42") .ClaimCheck(repository, ClaimCheckOperation.GetAndRemove, "order-42"), "payload"); (await repository.Retrieve("order-42")).Should().BeNull(); } // ── Push / Pop ────────────────────────────────────────────────── [Fact] public async Task PushThenPop_RoundTripsTheBodyWithoutAKey() { var repository = new InMemoryClaimCheckRepository(); var exchange = await RunAsync( def => def .ClaimCheck(repository, ClaimCheckOperation.Push) .Process(e => e.In.Body = "replaced while the real body was checked in") .ClaimCheck(repository, ClaimCheckOperation.Pop), "original payload"); exchange.In.Body.Should().Be("original payload"); } [Fact] public async Task PushPop_NestsLikeAStack() { var repository = new InMemoryClaimCheckRepository(); var exchange = await RunAsync( def => def .ClaimCheck(repository, ClaimCheckOperation.Push) // outer body checked in .Process(e => e.In.Body = "middle") .ClaimCheck(repository, ClaimCheckOperation.Push) // "middle" checked in .Process(e => e.In.Body = "inner-work") .ClaimCheck(repository, ClaimCheckOperation.Pop) // back to "middle" .ClaimCheck(repository, ClaimCheckOperation.Pop), // back to the original "outer"); exchange.In.Body.Should().Be("outer"); } // ── Repository resolution ─────────────────────────────────────── [Fact] public async Task WithoutARepository_TheContextDefaultIsSharedAcrossSteps() { var exchange = await RunAsync( def => def .ClaimCheck(ClaimCheckOperation.Push) .Process(e => e.In.Body = "scratch") .ClaimCheck(ClaimCheckOperation.Pop), "original payload"); exchange.In.Body.Should().Be("original payload", "steps that name no repository must land in the same context-wide store"); } [Fact] public async Task NamedRepository_IsResolvedFromTheRegistry() { var named = new InMemoryClaimCheckRepository(); _context.AddClaimCheckRepository("big-payloads", named); var exchange = await RunAsync( def => def .ClaimCheck(ClaimCheckOperation.Set, "k", repositoryName: "big-payloads") .ClaimCheck(ClaimCheckOperation.Get, "k", repositoryName: "big-payloads"), "payload"); exchange.In.Body.Should().Be("payload"); (await named.Retrieve("k")).Should().NotBeNull("the named repository is the one that was used"); } [Fact] public async Task UnknownRepositoryName_FailsWithANamingError() { _context.AddRoutes(r => r .From("direct://claim-missing") .ClaimCheck(ClaimCheckOperation.Set, "k", repositoryName: "not-registered")); var act = () => _context.Start(); (await act.Should().ThrowAsync()) .WithMessage("*not-registered*"); } [Fact] public async Task ExplicitDefaultRepository_WinsOverTheImplicitOne() { var mine = new InMemoryClaimCheckRepository(); _context.SetDefaultClaimCheckRepository(mine); await RunAsync(def => def.ClaimCheck(ClaimCheckOperation.Set, "k"), "payload"); (await mine.Retrieve("k")).Should().NotBeNull(); } } Path: redb-route/tests/redb.Route.Tests/Processors/ClaimCheckTests.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/Processors/ClaimCheckTests.cs ---- using System.Text; using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Processors; namespace redb.Route.Tests.Processors; /// /// Unit tests for and . /// public class ClaimCheckTests { // ══════════════════════════════════════════════════════════════ // InMemoryClaimCheckRepository // ══════════════════════════════════════════════════════════════ [Fact] public async Task Repository_Store_ReturnsUniqueKey() { var repo = new InMemoryClaimCheckRepository(); var data = Encoding.UTF8.GetBytes("hello"); var key1 = await repo.Store(data); var key2 = await repo.Store(data); key1.Should().NotBeNullOrEmpty(); key2.Should().NotBeNullOrEmpty(); key1.Should().NotBe(key2); } [Fact] public async Task Repository_StoreAndRetrieve_Roundtrip() { var repo = new InMemoryClaimCheckRepository(); var data = Encoding.UTF8.GetBytes("test payload"); var key = await repo.Store(data); var retrieved = await repo.Retrieve(key); retrieved.Should().BeEquivalentTo(data); } [Fact] public async Task Repository_StoreWithExplicitKey_Roundtrip() { var repo = new InMemoryClaimCheckRepository(); var data = Encoding.UTF8.GetBytes("keyed data"); await repo.Store("my-key", data); var retrieved = await repo.Retrieve("my-key"); retrieved.Should().BeEquivalentTo(data); } [Fact] public async Task Repository_StoreWithExplicitKey_Overwrites() { var repo = new InMemoryClaimCheckRepository(); await repo.Store("same-key", Encoding.UTF8.GetBytes("first")); await repo.Store("same-key", Encoding.UTF8.GetBytes("second")); var retrieved = await repo.Retrieve("same-key"); Encoding.UTF8.GetString(retrieved!).Should().Be("second"); } [Fact] public async Task Repository_Retrieve_ReturnsNull_ForMissingKey() { var repo = new InMemoryClaimCheckRepository(); var result = await repo.Retrieve("nonexistent"); result.Should().BeNull(); } [Fact] public async Task Repository_RetrieveAndRemove_RemovesEntry() { var repo = new InMemoryClaimCheckRepository(); var key = await repo.Store(Encoding.UTF8.GetBytes("temp")); var data = await repo.RetrieveAndRemove(key); data.Should().NotBeNull(); var second = await repo.Retrieve(key); second.Should().BeNull(); } [Fact] public async Task Repository_Remove_DeletesEntry() { var repo = new InMemoryClaimCheckRepository(); var key = await repo.Store(Encoding.UTF8.GetBytes("remove me")); await repo.Remove(key); var result = await repo.Retrieve(key); result.Should().BeNull(); } [Fact] public async Task Repository_Remove_NoOpForMissingKey() { var repo = new InMemoryClaimCheckRepository(); var act = async () => await repo.Remove("missing"); await act.Should().NotThrowAsync(); } [Fact] public async Task Repository_WithTtl_ReturnsNull_AfterExpiry() { var repo = new InMemoryClaimCheckRepository(TimeSpan.FromMilliseconds(50)); var key = await repo.Store(Encoding.UTF8.GetBytes("ttl data")); (await repo.Retrieve(key)).Should().NotBeNull(); await Task.Delay(80); (await repo.Retrieve(key)).Should().BeNull(); } [Fact] public async Task Repository_WithTtl_RetrieveAndRemove_ReturnsNull_AfterExpiry() { var repo = new InMemoryClaimCheckRepository(TimeSpan.FromMilliseconds(50)); var key = await repo.Store(Encoding.UTF8.GetBytes("ttl data")); await Task.Delay(80); (await repo.RetrieveAndRemove(key)).Should().BeNull(); } [Fact] public async Task Repository_ExplicitTtl_OverridesDefault() { var repo = new InMemoryClaimCheckRepository(TimeSpan.FromSeconds(30)); var key = await repo.Store(Encoding.UTF8.GetBytes("short"), ttl: TimeSpan.FromMilliseconds(50)); await Task.Delay(80); (await repo.Retrieve(key)).Should().BeNull(); } [Fact] public async Task Repository_NullKey_Throws() { var repo = new InMemoryClaimCheckRepository(); var act = async () => await repo.Retrieve(null!); await act.Should().ThrowAsync(); } [Fact] public async Task Repository_Count_TracksEntries() { var repo = new InMemoryClaimCheckRepository(); repo.Count.Should().Be(0); await repo.Store(Encoding.UTF8.GetBytes("a")); await repo.Store(Encoding.UTF8.GetBytes("b")); repo.Count.Should().Be(2); } // ══════════════════════════════════════════════════════════════ // ClaimCheckProcessor — Set / Get / GetAndRemove // ══════════════════════════════════════════════════════════════ [Fact] public void Processor_Ctor_ThrowsOnNullRepository() { var act = () => new ClaimCheckProcessor(null!, ClaimCheckOperation.Set); act.Should().Throw(); } [Fact] public async Task Processor_Set_ReplacesBodyWithKey() { var repo = new InMemoryClaimCheckRepository(); var processor = new ClaimCheckProcessor(repo, ClaimCheckOperation.Set, "mykey"); var exchange = new Exchange(new Message { Body = "large payload" }); await processor.Process(exchange); exchange.In.Body.Should().Be("mykey"); exchange.In.Headers[ClaimCheckHeaders.Key].Should().Be("mykey"); repo.Count.Should().Be(1); } [Fact] public async Task Processor_Set_SavesOriginalBodyType() { var repo = new InMemoryClaimCheckRepository(); var processor = new ClaimCheckProcessor(repo, ClaimCheckOperation.Set, "k1"); var exchange = new Exchange(new Message { Body = "string body" }); await processor.Process(exchange); exchange.In.Headers[ClaimCheckHeaders.OriginalBodyType].Should().Be(typeof(string).FullName); } [Fact] public async Task Processor_GetAndRemove_RestoresBody() { var repo = new InMemoryClaimCheckRepository(); // Store var setProc = new ClaimCheckProcessor(repo, ClaimCheckOperation.Set, "k1"); var exchange = new Exchange(new Message { Body = "original data" }); await setProc.Process(exchange); // Retrieve var getProc = new ClaimCheckProcessor(repo, ClaimCheckOperation.GetAndRemove, "k1"); await getProc.Process(exchange); exchange.In.Body.Should().Be("original data"); exchange.In.Headers.Should().NotContainKey(ClaimCheckHeaders.Key); repo.Count.Should().Be(0); } [Fact] public async Task Processor_Get_KeepsDataInStore() { var repo = new InMemoryClaimCheckRepository(); var setProc = new ClaimCheckProcessor(repo, ClaimCheckOperation.Set, "k1"); var exchange = new Exchange(new Message { Body = "keep me" }); await setProc.Process(exchange); var getProc = new ClaimCheckProcessor(repo, ClaimCheckOperation.Get, "k1"); await getProc.Process(exchange); exchange.In.Body.Should().Be("keep me"); repo.Count.Should().Be(1); // still in store } [Fact] public async Task Processor_Get_MissingKey_LeavesBodyUnchanged() { var repo = new InMemoryClaimCheckRepository(); var processor = new ClaimCheckProcessor(repo, ClaimCheckOperation.Get, "nonexistent"); var exchange = new Exchange(new Message { Body = "untouched" }); await processor.Process(exchange); exchange.In.Body.Should().Be("untouched"); } // ══════════════════════════════════════════════════════════════ // ClaimCheckProcessor — Push / Pop (stack semantics) // ══════════════════════════════════════════════════════════════ [Fact] public async Task Processor_PushPop_Roundtrip() { var repo = new InMemoryClaimCheckRepository(); // Push var pushProc = new ClaimCheckProcessor(repo, ClaimCheckOperation.Push); var exchange = new Exchange(new Message { Body = "stashed body" }); await pushProc.Process(exchange); exchange.In.Body.Should().NotBe("stashed body"); // body replaced with key // Modify body in between exchange.In.Body = "temporary data"; // Pop var popProc = new ClaimCheckProcessor(repo, ClaimCheckOperation.Pop); await popProc.Process(exchange); exchange.In.Body.Should().Be("stashed body"); } [Fact] public async Task Processor_PushPush_PopPop_LIFO() { var repo = new InMemoryClaimCheckRepository(); var push = new ClaimCheckProcessor(repo, ClaimCheckOperation.Push); var pop = new ClaimCheckProcessor(repo, ClaimCheckOperation.Pop); var exchange = new Exchange(new Message { Body = "first" }); await push.Process(exchange); exchange.In.Body = "second"; await push.Process(exchange); // Pop should return "second" first (LIFO) await pop.Process(exchange); exchange.In.Body.Should().Be("second"); await pop.Process(exchange); exchange.In.Body.Should().Be("first"); } [Fact] public async Task Processor_Pop_EmptyStack_LeavesBodyUnchanged() { var repo = new InMemoryClaimCheckRepository(); var popProc = new ClaimCheckProcessor(repo, ClaimCheckOperation.Pop); var exchange = new Exchange(new Message { Body = "original" }); await popProc.Process(exchange); exchange.In.Body.Should().Be("original"); } // ══════════════════════════════════════════════════════════════ // ClaimCheckProcessor — byte[] body roundtrip // ══════════════════════════════════════════════════════════════ [Fact] public async Task Processor_ByteArray_Roundtrip() { var repo = new InMemoryClaimCheckRepository(); var originalBytes = new byte[] { 0x00, 0xFF, 0x42, 0x13 }; var setProc = new ClaimCheckProcessor(repo, ClaimCheckOperation.Set, "bin"); var exchange = new Exchange(new Message { Body = originalBytes }); await setProc.Process(exchange); var getProc = new ClaimCheckProcessor(repo, ClaimCheckOperation.GetAndRemove, "bin"); await getProc.Process(exchange); exchange.In.Body.Should().BeOfType(); ((byte[])exchange.In.Body!).Should().BeEquivalentTo(originalBytes); } // ══════════════════════════════════════════════════════════════ // ClaimCheckProcessor — auto-key (no explicit key, uses header) // ══════════════════════════════════════════════════════════════ [Fact] public async Task Processor_AutoKey_SetAndGetViaHeader() { var repo = new InMemoryClaimCheckRepository(); // Set without explicit key -> auto-generates key, stores in header var setProc = new ClaimCheckProcessor(repo, ClaimCheckOperation.Set); var exchange = new Exchange(new Message { Body = "auto keyed data" }); await setProc.Process(exchange); var autoKey = exchange.In.Headers[ClaimCheckHeaders.Key] as string; autoKey.Should().NotBeNullOrEmpty(); // Get without explicit key -> reads key from header var getProc = new ClaimCheckProcessor(repo, ClaimCheckOperation.GetAndRemove); await getProc.Process(exchange); exchange.In.Body.Should().Be("auto keyed data"); } // ══════════════════════════════════════════════════════════════ // ClaimCheckSerializer // ══════════════════════════════════════════════════════════════ [Fact] public void Serializer_Null_ReturnsEmpty() { var result = ClaimCheckSerializer.Serialize(null); result.Should().BeEmpty(); } [Fact] public void Serializer_ByteArray_ReturnsSameBytes() { var bytes = new byte[] { 1, 2, 3 }; var result = ClaimCheckSerializer.Serialize(bytes); result.Should().BeSameAs(bytes); } [Fact] public void Serializer_String_ReturnsUtf8() { var result = ClaimCheckSerializer.Serialize("hello"); result.Should().BeEquivalentTo(Encoding.UTF8.GetBytes("hello")); } [Fact] public void Deserializer_Empty_ReturnsNull() { var result = ClaimCheckSerializer.Deserialize([], null); result.Should().BeNull(); } [Fact] public void Deserializer_ByteArrayType_ReturnsBytes() { var data = new byte[] { 1, 2, 3 }; var result = ClaimCheckSerializer.Deserialize(data, typeof(byte[]).FullName); result.Should().BeOfType(); ((byte[])result!).Should().BeEquivalentTo(data); } [Fact] public void Deserializer_Default_ReturnsString() { var data = Encoding.UTF8.GetBytes("hello world"); var result = ClaimCheckSerializer.Deserialize(data, null); result.Should().Be("hello world"); } } Path: redb-route/tests/redb.Route.Tests/Processors/DebounceIntegrationTests.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/Processors/DebounceIntegrationTests.cs ---- using System.Collections.Concurrent; using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Definitions; namespace redb.Route.Tests.Processors; /// /// Integration tests for Debounce using full route compilation and pipeline execution. /// [Trait("Category", "Integration")] public class DebounceIntegrationTests { private readonly RouteContext _context = new(); private static IExchange CreateExchange(object? body = null, string? key = null) { var ex = Exchange.Create(new Message(body), null); if (key != null) ex.In.Headers["DebounceKey"] = key; return ex; } private static Func KeyFromHeader => e => e.In.Headers.TryGetValue("DebounceKey", out var v) ? v?.ToString() ?? "" : ""; // ══════════════════════════════════════════════════════════════ // Compiled pipeline // ══════════════════════════════════════════════════════════════ [Fact] public async Task CompiledPipeline_SingleMessage_ForwardedAfterQuiet() { var forwarded = new ConcurrentBag(); var def = new RouteDefinition(); def.From("direct://debounce"); def.Debounce(KeyFromHeader, TimeSpan.FromMilliseconds(100)) .Process(e => forwarded.Add(e.In.Body)) .End(); var pipeline = def.CreateProcessor(_context); await pipeline.Process(CreateExchange("hello", "A")); forwarded.Should().BeEmpty(); await Task.Delay(350); forwarded.Should().ContainSingle().Which.Should().Be("hello"); } [Fact] public async Task CompiledPipeline_RapidFire_OnlyLastForwarded() { var forwarded = new ConcurrentBag(); var def = new RouteDefinition(); def.From("direct://debounce"); // The window is wide against the 30 ms gaps: with 150 ms a slow machine stretched a gap past the window and // forwarded v1 as well. def.Debounce(KeyFromHeader, TimeSpan.FromSeconds(1)) .Process(e => forwarded.Add(e.In.Body)) .End(); var pipeline = def.CreateProcessor(_context); await pipeline.Process(CreateExchange("v1", "A")); await Task.Delay(30); await pipeline.Process(CreateExchange("v2", "A")); await Task.Delay(30); await pipeline.Process(CreateExchange("v3", "A")); await Task.Delay(2_000); forwarded.Should().ContainSingle().Which.Should().Be("v3"); } [Fact] public async Task CompiledPipeline_DifferentKeys_Independent() { var forwarded = new ConcurrentBag(); var def = new RouteDefinition(); def.From("direct://debounce"); def.Debounce(KeyFromHeader, TimeSpan.FromMilliseconds(100)) .Process(e => { var k = e.In.Headers["DebounceKey"]?.ToString() ?? ""; forwarded.Add($"{k}:{e.In.Body}"); }) .End(); var pipeline = def.CreateProcessor(_context); await pipeline.Process(CreateExchange("a1", "A")); await pipeline.Process(CreateExchange("b1", "B")); await Task.Delay(350); forwarded.Should().HaveCount(2); forwarded.Should().Contain("A:a1"); forwarded.Should().Contain("B:b1"); } [Fact] public async Task CompiledPipeline_DebounceWrapsDownstreamSteps() { var forwarded = new ConcurrentBag(); var def = new RouteDefinition(); def.From("direct://debounce"); def.Debounce(KeyFromHeader, TimeSpan.FromMilliseconds(100)) .Transform(e => $"transformed:{e.In.Body}") .Process(e => forwarded.Add(e.In.Body)) .End(); var pipeline = def.CreateProcessor(_context); await pipeline.Process(CreateExchange("raw", "X")); await Task.Delay(350); forwarded.Should().ContainSingle().Which.Should().Be("transformed:raw"); } [Fact] public async Task CompiledPipeline_DebounceAfterOtherSteps() { var forwarded = new ConcurrentBag(); var preProcessed = new ConcurrentBag(); var def = new RouteDefinition(); def.From("direct://debounce"); def.Process(e => preProcessed.Add(e.In.Body)); // Wide against the 30 ms gap, as in RapidFire: a slow machine stretched the gap past 100 ms. def.Debounce(KeyFromHeader, TimeSpan.FromSeconds(1)) .Process(e => forwarded.Add(e.In.Body)) .End(); var pipeline = def.CreateProcessor(_context); await pipeline.Process(CreateExchange("msg1", "A")); await Task.Delay(30); await pipeline.Process(CreateExchange("msg2", "A")); // Pre-debounce processor runs for every message preProcessed.Should().HaveCount(2); await Task.Delay(2_000); // Post-debounce only gets the last forwarded.Should().ContainSingle().Which.Should().Be("msg2"); } [Fact] public async Task CompiledPipeline_MultipleKeysBurstThenQuiet() { var forwarded = new ConcurrentBag(); var def = new RouteDefinition(); def.From("direct://debounce"); // Wide against the burst: five calls in a row may take longer than 150 ms on a slow machine. def.Debounce(KeyFromHeader, TimeSpan.FromSeconds(1)) .Process(e => { var k = e.In.Headers["DebounceKey"]?.ToString() ?? ""; forwarded.Add($"{k}:{e.In.Body}"); }) .End(); var pipeline = def.CreateProcessor(_context); // Burst on A await pipeline.Process(CreateExchange("a1", "A")); await pipeline.Process(CreateExchange("a2", "A")); await pipeline.Process(CreateExchange("a3", "A")); // Burst on B await pipeline.Process(CreateExchange("b1", "B")); await pipeline.Process(CreateExchange("b2", "B")); await Task.Delay(2_000); forwarded.Should().HaveCount(2); forwarded.Should().Contain("A:a3"); forwarded.Should().Contain("B:b2"); } [Fact] public async Task CompiledPipeline_HeaderModifiedByDebounce() { var forwarded = new ConcurrentBag(); var def = new RouteDefinition(); def.From("direct://debounce"); def.Debounce(KeyFromHeader, TimeSpan.FromMilliseconds(100)) .SetHeader("Debounced", "true") .Process(e => forwarded.Add(e.In.Headers["Debounced"])) .End(); var pipeline = def.CreateProcessor(_context); await pipeline.Process(CreateExchange("test", "A")); await Task.Delay(350); forwarded.Should().ContainSingle().Which.Should().Be("true"); } } Path: redb-route/tests/redb.Route.Tests/Processors/DebounceTests.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/Processors/DebounceTests.cs ---- using System.Collections.Concurrent; using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Definitions; using Microsoft.Extensions.Time.Testing; using redb.Route.Processors; namespace redb.Route.Tests.Processors; /// /// Unit tests for DebounceProcessor, DSL, and step creation. /// public class DebounceTests { private static IExchange CreateExchange(object? body = null, string? key = null) { var ex = Exchange.Create(new Message(body), null); if (key != null) ex.In.Headers["DebounceKey"] = key; return ex; } private static Func KeyFromHeader => e => e.In.Headers.TryGetValue("DebounceKey", out var v) ? v?.ToString() ?? "" : ""; // ══════════════════════════════════════════════════════════════ // Constructor validation // ══════════════════════════════════════════════════════════════ [Fact] public void Constructor_NullNext_Throws() { var act = () => new DebounceProcessor(null!, KeyFromHeader, TimeSpan.FromMilliseconds(100)); act.Should().Throw().WithParameterName("next"); } [Fact] public void Constructor_NullKeyExtractor_Throws() { var next = new DelegateProcessor(_ => { }); var act = () => new DebounceProcessor(next, null!, TimeSpan.FromMilliseconds(100)); act.Should().Throw().WithParameterName("keyExtractor"); } [Fact] public void Constructor_ZeroQuietPeriod_Throws() { var next = new DelegateProcessor(_ => { }); var act = () => new DebounceProcessor(next, KeyFromHeader, TimeSpan.Zero); act.Should().Throw().WithParameterName("quietPeriod"); } [Fact] public void Constructor_NegativeQuietPeriod_Throws() { var next = new DelegateProcessor(_ => { }); var act = () => new DebounceProcessor(next, KeyFromHeader, TimeSpan.FromMilliseconds(-1)); act.Should().Throw().WithParameterName("quietPeriod"); } // ══════════════════════════════════════════════════════════════ // Processor behavior. The quiet period runs on a FakeTimeProvider (findings register row 21): time moves only // when a test advances it, so no assertion depends on how loaded the machine is. A forward runs as a // continuation on the thread pool after its timer fires, so Forwarded waits for it to be observed. // ══════════════════════════════════════════════════════════════ private static readonly TimeSpan Quiet = TimeSpan.FromMilliseconds(100); private static async Task Forwarded(ConcurrentBag forwarded, int count) { var deadline = DateTime.UtcNow.AddSeconds(5); while (forwarded.Count < count && DateTime.UtcNow < deadline) await Task.Delay(5); } [Fact] public async Task SingleMessage_ForwardedAfterQuietPeriod() { var time = new FakeTimeProvider(); var forwarded = new ConcurrentBag(); var next = new DelegateProcessor(ex => forwarded.Add(ex.In.Body)); using var debounce = new DebounceProcessor(next, KeyFromHeader, Quiet, timeProvider: time); await debounce.Process(CreateExchange("hello", "A")); time.Advance(Quiet - TimeSpan.FromMilliseconds(1)); forwarded.Should().BeEmpty("the quiet period has not passed"); time.Advance(TimeSpan.FromMilliseconds(1)); await Forwarded(forwarded, 1); forwarded.Should().ContainSingle().Which.Should().Be("hello"); } [Fact] public async Task RapidMessages_SameKey_OnlyLastForwarded() { var time = new FakeTimeProvider(); var forwarded = new ConcurrentBag(); var next = new DelegateProcessor(ex => forwarded.Add(ex.In.Body)); using var debounce = new DebounceProcessor(next, KeyFromHeader, Quiet, timeProvider: time); await debounce.Process(CreateExchange("first", "A")); time.Advance(TimeSpan.FromMilliseconds(30)); await debounce.Process(CreateExchange("second", "A")); time.Advance(TimeSpan.FromMilliseconds(30)); await debounce.Process(CreateExchange("third", "A")); time.Advance(Quiet); await Forwarded(forwarded, 1); forwarded.Should().ContainSingle().Which.Should().Be("third"); } [Fact] public async Task DifferentKeys_Independent() { var time = new FakeTimeProvider(); var forwarded = new ConcurrentBag(); var next = new DelegateProcessor(ex => { var key = ex.In.Headers["DebounceKey"]?.ToString() ?? ""; forwarded.Add($"{key}:{ex.In.Body}"); }); using var debounce = new DebounceProcessor(next, KeyFromHeader, Quiet, timeProvider: time); await debounce.Process(CreateExchange("a1", "A")); await debounce.Process(CreateExchange("b1", "B")); time.Advance(Quiet); await Forwarded(forwarded, 2); forwarded.Should().HaveCount(2); forwarded.Should().Contain("A:a1"); forwarded.Should().Contain("B:b1"); } [Fact] public async Task DifferentKeys_OnlyLatestPerKey() { var time = new FakeTimeProvider(); var forwarded = new ConcurrentBag(); var next = new DelegateProcessor(ex => { var key = ex.In.Headers["DebounceKey"]?.ToString() ?? ""; forwarded.Add($"{key}:{ex.In.Body}"); }); using var debounce = new DebounceProcessor(next, KeyFromHeader, Quiet, timeProvider: time); await debounce.Process(CreateExchange("a1", "A")); await debounce.Process(CreateExchange("b1", "B")); time.Advance(TimeSpan.FromMilliseconds(30)); await debounce.Process(CreateExchange("a2", "A")); await debounce.Process(CreateExchange("b2", "B")); time.Advance(TimeSpan.FromMilliseconds(30)); await debounce.Process(CreateExchange("a3", "A")); time.Advance(Quiet); await Forwarded(forwarded, 2); forwarded.Should().Contain("A:a3"); forwarded.Should().Contain("B:b2"); forwarded.Where(f => f.StartsWith("A:")).Should().ContainSingle(); forwarded.Where(f => f.StartsWith("B:")).Should().ContainSingle(); } [Fact] public void Process_ReturnsImmediately() { var next = new DelegateProcessor(async (_, ct) => await Task.Delay(500, ct)); // slow downstream using var debounce = new DebounceProcessor(next, KeyFromHeader, Quiet, timeProvider: new FakeTimeProvider()); // Neither the quiet period nor the downstream call is awaited by Process. debounce.Process(CreateExchange("fast", "A")).IsCompletedSuccessfully.Should().BeTrue(); } [Fact] public async Task TimerReset_ExtendsQuietPeriod() { var time = new FakeTimeProvider(); var forwarded = new ConcurrentBag(); var next = new DelegateProcessor(ex => forwarded.Add(ex.In.Body)); using var debounce = new DebounceProcessor(next, KeyFromHeader, TimeSpan.FromMilliseconds(200), timeProvider: time); await debounce.Process(CreateExchange("msg1", "A")); time.Advance(TimeSpan.FromMilliseconds(100)); await debounce.Process(CreateExchange("msg2", "A")); // resets the timer to 200 ms time.Advance(TimeSpan.FromMilliseconds(120)); // 200 ms after msg1 have passed forwarded.Should().BeEmpty("the timer was reset by the second message"); time.Advance(TimeSpan.FromMilliseconds(80)); // 200 ms after msg2 await Forwarded(forwarded, 1); forwarded.Should().ContainSingle().Which.Should().Be("msg2"); } [Fact] public async Task Dispose_CancelsTimers() { var time = new FakeTimeProvider(); var forwarded = new ConcurrentBag(); var next = new DelegateProcessor(ex => forwarded.Add(ex.In.Body)); var debounce = new DebounceProcessor(next, KeyFromHeader, TimeSpan.FromMilliseconds(200), timeProvider: time); await debounce.Process(CreateExchange("hello", "A")); debounce.Dispose(); time.Advance(TimeSpan.FromMilliseconds(400)); await Task.Yield(); forwarded.Should().BeEmpty("the timer was cancelled"); } [Fact] public async Task DisposedProcessor_ThrowsOnProcess() { var next = new DelegateProcessor(_ => { }); var debounce = new DebounceProcessor(next, KeyFromHeader, TimeSpan.FromMilliseconds(100)); debounce.Dispose(); var act = () => debounce.Process(CreateExchange("nope", "A")); await act.Should().ThrowAsync(); } [Fact] public async Task FlushAsync_ForwardsAllPending() { var forwarded = new ConcurrentBag(); var next = new DelegateProcessor(ex => { var key = ex.In.Headers["DebounceKey"]?.ToString() ?? ""; forwarded.Add($"{key}:{ex.In.Body}"); }); var debounce = new DebounceProcessor(next, KeyFromHeader, TimeSpan.FromSeconds(10), timeProvider: new FakeTimeProvider()); await debounce.Process(CreateExchange("a-val", "A")); await debounce.Process(CreateExchange("b-val", "B")); // Flush without waiting for timers await debounce.FlushAsync(); forwarded.Should().HaveCount(2); forwarded.Should().Contain("A:a-val"); forwarded.Should().Contain("B:b-val"); debounce.Dispose(); } [Fact] public async Task DisposeAsync_FlushesAndCleans() { var forwarded = new ConcurrentBag(); var next = new DelegateProcessor(ex => forwarded.Add(ex.In.Body)); var debounce = new DebounceProcessor(next, KeyFromHeader, TimeSpan.FromSeconds(10), timeProvider: new FakeTimeProvider()); await debounce.Process(CreateExchange("flushed", "A")); await debounce.DisposeAsync(); forwarded.Should().ContainSingle().Which.Should().Be("flushed"); } [Fact] public async Task NullKey_UsesEmptyString() { var time = new FakeTimeProvider(); var forwarded = new ConcurrentBag(); var next = new DelegateProcessor(ex => forwarded.Add(ex.In.Body)); Func nullKey = _ => null!; using var debounce = new DebounceProcessor(next, nullKey, Quiet, timeProvider: time); await debounce.Process(CreateExchange("val1")); await debounce.Process(CreateExchange("val2")); time.Advance(Quiet); await Forwarded(forwarded, 1); time.Advance(Quiet); // nothing else is pending await Task.Yield(); // Both go to empty-string key, only last forwarded forwarded.Should().ContainSingle().Which.Should().Be("val2"); } [Fact] public async Task SequentialBursts_SameKey_ForwardsEachBurst() { var time = new FakeTimeProvider(); var forwarded = new ConcurrentBag(); var next = new DelegateProcessor(ex => forwarded.Add(ex.In.Body)); using var debounce = new DebounceProcessor(next, KeyFromHeader, Quiet, timeProvider: time); await debounce.Process(CreateExchange("burst1-a", "K")); time.Advance(TimeSpan.FromMilliseconds(20)); await debounce.Process(CreateExchange("burst1-b", "K")); time.Advance(Quiet); await Forwarded(forwarded, 1); forwarded.Should().ContainSingle().Which.Should().Be("burst1-b"); await debounce.Process(CreateExchange("burst2-a", "K")); time.Advance(TimeSpan.FromMilliseconds(20)); await debounce.Process(CreateExchange("burst2-b", "K")); time.Advance(Quiet); await Forwarded(forwarded, 2); forwarded.Should().HaveCount(2); forwarded.Should().Contain("burst2-b"); } // ══════════════════════════════════════════════════════════════ // DSL — step recording // ══════════════════════════════════════════════════════════════ [Fact] public void DSL_Debounce_RecordsStep() { var def = new RouteDefinition(); Func key = e => "k"; def.Debounce(key, TimeSpan.FromMilliseconds(500)); var node = def.Outputs.Should().ContainSingle().Which.Should().BeOfType().Subject; node.KeyExtractor.Should().BeSameAs(key); node.QuietPeriod.Should().Be(TimeSpan.FromMilliseconds(500)); } [Fact] public void DSL_Debounce_NullKeyExtractor_Throws() { var def = new RouteDefinition(); var act = () => def.Debounce(null!, TimeSpan.FromMilliseconds(100)); act.Should().Throw().WithParameterName("keyExtractor"); } [Fact] public void DSL_Debounce_ZeroQuietPeriod_Throws() { var def = new RouteDefinition(); var act = () => def.Debounce(e => "k", TimeSpan.Zero); act.Should().Throw().WithParameterName("quietPeriod"); } [Fact] public void DSL_Debounce_NegativeQuietPeriod_Throws() { var def = new RouteDefinition(); var act = () => def.Debounce(e => "k", TimeSpan.FromMilliseconds(-50)); act.Should().Throw().WithParameterName("quietPeriod"); } [Fact] public void DSL_Debounce_Chaining() { var def = new RouteDefinition(); var scope = def.Debounce(e => "k", TimeSpan.FromMilliseconds(200)); scope.To("direct:out"); var result = scope.EndDebounce(); result.Should().BeSameAs(def); def.Outputs.Should().ContainSingle().Which.Should().BeOfType() .Which.Outputs.Should().ContainSingle().Which.Should().BeOfType(); } } Path: redb-route/tests/redb.Route.Tests/Processors/DelayProcessorTests.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/Processors/DelayProcessorTests.cs ---- using AwesomeAssertions; using redb.Route.Core; using redb.Route.Processors; namespace redb.Route.Tests.Processors; /// Tests for . public class DelayProcessorTests { /// Delay actually waits approximately the specified time. [Fact] public async Task Process_DelaysApproximately() { var processor = new DelayProcessor(TimeSpan.FromMilliseconds(100)); var sw = System.Diagnostics.Stopwatch.StartNew(); await processor.Process(new Exchange()); sw.Elapsed.Should().BeGreaterThanOrEqualTo(TimeSpan.FromMilliseconds(80)); } /// Zero delay completes immediately. [Fact] public async Task Process_ZeroDelay_Immediate() { var processor = new DelayProcessor(TimeSpan.Zero); var sw = System.Diagnostics.Stopwatch.StartNew(); await processor.Process(new Exchange()); sw.Elapsed.Should().BeLessThan(TimeSpan.FromMilliseconds(50)); } /// Cancellation during delay throws OperationCanceledException. [Fact] public async Task Process_Cancelled_Throws() { var processor = new DelayProcessor(TimeSpan.FromSeconds(10)); using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(50)); var act = () => processor.Process(new Exchange(), cts.Token); await act.Should().ThrowAsync(); } /// Negative delay throws ArgumentOutOfRangeException. [Fact] public void Constructor_NegativeDelay_Throws() { var act = () => new DelayProcessor(TimeSpan.FromSeconds(-1)); act.Should().Throw(); } /// Delay property returns configured value. [Fact] public void Delay_ReturnsConfigured() { var delay = TimeSpan.FromMilliseconds(250); var processor = new DelayProcessor(delay); processor.Delay.Should().Be(delay); } } Path: redb-route/tests/redb.Route.Tests/Processors/DelegateProcessorTests.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/Processors/DelegateProcessorTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Processors; namespace redb.Route.Tests.Processors; /// Tests for . public class DelegateProcessorTests { /// Async delegate receives the exchange. [Fact] public async Task Process_AsyncDelegate_Executes() { IExchange? captured = null; var processor = new DelegateProcessor(async (ex, ct) => { captured = ex; await Task.CompletedTask; }); var exchange = new Exchange(new Message("hello")); await processor.Process(exchange); captured.Should().BeSameAs(exchange); } /// Sync delegate receives the exchange. [Fact] public async Task Process_SyncDelegate_Executes() { object? capturedBody = null; var processor = new DelegateProcessor(ex => { capturedBody = ex.In.Body; }); var exchange = new Exchange(new Message("test")); await processor.Process(exchange); capturedBody.Should().Be("test"); } /// Delegate can modify the exchange body. [Fact] public async Task Process_CanModifyExchange() { var processor = new DelegateProcessor(ex => { ex.In.Body = "modified"; }); var exchange = new Exchange(new Message("original")); await processor.Process(exchange); exchange.In.Body.Should().Be("modified"); } /// Null async delegate throws ArgumentNullException. [Fact] public void Constructor_NullAsyncDelegate_Throws() { var act = () => new DelegateProcessor((Func)null!); act.Should().Throw(); } /// Null sync delegate throws ArgumentNullException. [Fact] public void Constructor_NullSyncDelegate_Throws() { var act = () => new DelegateProcessor((Action)null!); act.Should().Throw(); } /// CancellationToken is passed through to the delegate. [Fact] public async Task Process_CancellationToken_PassedThrough() { CancellationToken capturedToken = default; var processor = new DelegateProcessor((ex, ct) => { capturedToken = ct; return Task.CompletedTask; }); using var cts = new CancellationTokenSource(); var exchange = new Exchange(); await processor.Process(exchange, cts.Token); capturedToken.Should().Be(cts.Token); } } Path: redb-route/tests/redb.Route.Tests/Processors/DetachedContextIsolationTests.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/Processors/DetachedContextIsolationTests.cs ---- using System.Diagnostics; using System.Transactions; using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Processors; using redb.Route.Telemetry; using redb.Route.Transactions; namespace redb.Route.Tests.Processors; /// /// Verifies that detached branches (WireTap fire-and-forget, Debounce flush) do NOT inherit the /// caller's ambient transaction / trace, and that WireTap does not share the transacted-action /// dictionary with its clone. Covers the -based fix. /// [Collection("Telemetry")] public class DetachedContextIsolationTests { [Fact] public async Task WireTap_StripsTransactActionFromClone_OriginalUntouched() { IExchange? tapped = null; var tcs = new TaskCompletionSource(); var tap = new DelegateProcessor((ex, _) => { tapped = ex; tcs.SetResult(); return Task.CompletedTask; }); var processor = new WireTapProcessor(tap); var original = new Exchange(new Message("data")); original.Properties[TransactedProcessor.TransactActionPropertyKey] = new object(); await processor.Process(original); await tcs.Task.WaitAsync(TimeSpan.FromSeconds(5)); tapped!.Properties.ContainsKey(TransactedProcessor.TransactActionPropertyKey).Should().BeFalse( "the tap clone must not share the owning TransactedProcessor's deferred-action dictionary"); original.Properties.ContainsKey(TransactedProcessor.TransactActionPropertyKey).Should().BeTrue( "stripping happens on the clone only — the original is untouched"); } [Fact] public async Task WireTap_Tap_RunsWithAmbientTransactionSuppressed() { Transaction? txInTap = null; var ran = false; var tcs = new TaskCompletionSource(); var tap = new DelegateProcessor((ex, _) => { txInTap = Transaction.Current; ran = true; tcs.SetResult(); return Task.CompletedTask; }); var processor = new WireTapProcessor(tap); using (var scope = new TransactionScope( TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Enabled)) { await processor.Process(new Exchange(new Message("data"))); scope.Complete(); } await tcs.Task.WaitAsync(TimeSpan.FromSeconds(5)); ran.Should().BeTrue(); txInTap.Should().BeNull("the tap must run detached from the originating transaction"); } [Fact] public async Task WireTap_TapSpan_IsRootLinkedToOriginatingTrace() { var listener = new ActivityListener { ShouldListenTo = s => s.Name == RouteActivitySource.SourceName, Sample = (ref ActivityCreationOptions _) => ActivitySamplingResult.AllDataAndRecorded, }; ActivitySource.AddActivityListener(listener); try { Activity? tapActivity = null; var tcs = new TaskCompletionSource(); var tap = new DelegateProcessor((ex, _) => { tapActivity = Activity.Current; tcs.SetResult(); return Task.CompletedTask; }); var processor = new WireTapProcessor(tap); using var parent = RouteActivitySource.Source.StartActivity("test-parent"); parent.Should().NotBeNull("listener samples the route source"); var parentTraceId = parent!.TraceId; await processor.Process(new Exchange(new Message("data"))); await tcs.Task.WaitAsync(TimeSpan.FromSeconds(5)); tapActivity.Should().NotBeNull(); tapActivity!.DisplayName.Should().Be("redb.route.wiretap"); tapActivity.Parent.Should().BeNull("the tap span is re-rooted, not an implicit child of the stopped request span"); tapActivity.TraceId.Should().NotBe(parentTraceId, "a fresh root trace is started for the detached branch"); tapActivity.Links.Should().Contain(l => l.Context.TraceId == parentTraceId, "correlation to the originating trace is preserved via an ActivityLink"); } finally { listener.Dispose(); } } [Fact] public async Task Debounce_Flush_RunsWithAmbientTransactionSuppressed() { Transaction? txInFlush = null; var ran = false; var tcs = new TaskCompletionSource(); var next = new DelegateProcessor((ex, _) => { txInFlush = Transaction.Current; ran = true; tcs.SetResult(); return Task.CompletedTask; }); await using var debounce = new DebounceProcessor(next, _ => "k", TimeSpan.FromMilliseconds(50)); using (var scope = new TransactionScope( TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Enabled)) { await debounce.Process(new Exchange(new Message("data"))); scope.Complete(); } await tcs.Task.WaitAsync(TimeSpan.FromSeconds(5)); ran.Should().BeTrue(); txInFlush.Should().BeNull("the debounced flush must run detached from the originating transaction"); } } Path: redb-route/tests/redb.Route.Tests/Processors/DetachedPoolTests.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/Processors/DetachedPoolTests.cs ---- using System.Transactions; using redb.Route.Abstractions; using redb.Route.Configuration; using redb.Route.Core; using redb.Route.Processors; using redb.Route.Transactions; namespace redb.Route.Tests.Processors; /// /// The bounded pool of a detached step (Camel's thread pool profile): a WireTap runs at most /// MaxConcurrency branches and queues at most MaxQueueSize; a branch that finds both full is run by the /// caller (the default), dropped or refused. A caller-run branch is still detached from the caller's transaction. /// public class DetachedPoolTests { private static DetachedExecutor Pool(int concurrency, int queue, ThreadPoolRejectedPolicy policy) => new("test", new ThreadPoolProfile { MaxConcurrency = concurrency, MaxQueueSize = queue, RejectedPolicy = policy }, "wireTap", "pool-route", null); private static Func Blocked(TaskCompletionSource gate, Action? started = null) => async () => { started?.Invoke(); await gate.Task; }; [Fact] public async Task AtMostMaxConcurrencyRun_TheNextWait_AndAllRunOnceSlotsFree() { var pool = Pool(2, 3, ThreadPoolRejectedPolicy.CallerRuns); var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var started = 0; var running = 0; var peak = 0; for (var i = 0; i < 5; i++) { (await pool.Execute(async () => { Interlocked.Increment(ref started); var now = Interlocked.Increment(ref running); int seen; while ((seen = Volatile.Read(ref peak)) < now && Interlocked.CompareExchange(ref peak, now, seen) != seen) { } await gate.Task; Interlocked.Decrement(ref running); })).Should().BeTrue(); } await WaitFor(() => Volatile.Read(ref started) == 2); pool.Active.Should().Be(2); pool.Queued.Should().Be(3); gate.SetResult(); await pool.DrainAsync(new CancellationTokenSource(TimeSpan.FromSeconds(10)).Token); started.Should().Be(5); peak.Should().Be(2, "never more than MaxConcurrency at a time"); pool.Active.Should().Be(0); pool.Queued.Should().Be(0); } [Fact] public async Task WhenThePoolAndQueueAreFull_TheCallerRunsTheBranch() { var pool = Pool(1, 1, ThreadPoolRejectedPolicy.CallerRuns); var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); await pool.Execute(Blocked(gate)); await pool.Execute(Blocked(gate)); var callerThread = Environment.CurrentManagedThreadId; var ranOn = -1; var third = pool.Execute(() => { ranOn = Environment.CurrentManagedThreadId; return Task.CompletedTask; }); third.IsCompleted.Should().BeTrue("the caller ran the branch before Execute returned"); (await third).Should().BeTrue(); ranOn.Should().Be(callerThread); gate.SetResult(); await pool.DrainAsync(new CancellationTokenSource(TimeSpan.FromSeconds(10)).Token); } [Fact] public async Task Discard_DropsTheBranchAndCountsIt() { var pool = Pool(1, 0, ThreadPoolRejectedPolicy.Discard); var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); await pool.Execute(Blocked(gate)); var ran = false; (await pool.Execute(() => { ran = true; return Task.CompletedTask; })).Should().BeFalse(); ran.Should().BeFalse(); pool.Rejected.Should().Be(1); gate.SetResult(); } [Fact] public async Task Abort_RefusesTheBranch() { var pool = Pool(1, 0, ThreadPoolRejectedPolicy.Abort); var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); await pool.Execute(Blocked(gate)); var act = async () => await pool.Execute(() => Task.CompletedTask); await act.Should().ThrowAsync().WithMessage("*pool-route*"); pool.Rejected.Should().Be(1); gate.SetResult(); } [Fact] public async Task Drain_WaitsForWhatRunsAndWaits_AndStopsAtTheToken() { var pool = Pool(1, 5, ThreadPoolRejectedPolicy.CallerRuns); var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); await pool.Execute(Blocked(gate)); await pool.Execute(() => Task.CompletedTask); // The shutdown window runs out: the drain returns and leaves the count behind (logged, not dropped). await pool.DrainAsync(new CancellationTokenSource(TimeSpan.FromMilliseconds(200)).Token); (pool.Active + pool.Queued).Should().Be(2); gate.SetResult(); await pool.DrainAsync(new CancellationTokenSource(TimeSpan.FromSeconds(10)).Token); (pool.Active + pool.Queued).Should().Be(0, "the branches were not cancelled, they ran to the end"); } [Fact] public async Task AFailingBranch_IsCountedAndDoesNotStopThePool() { var pool = Pool(1, 5, ThreadPoolRejectedPolicy.CallerRuns); var ran = 0; await pool.Execute(() => throw new InvalidOperationException("a branch fails")); await pool.Execute(() => { Interlocked.Increment(ref ran); return Task.CompletedTask; }); await pool.DrainAsync(new CancellationTokenSource(TimeSpan.FromSeconds(10)).Token); ran.Should().Be(1); } [Theory] [InlineData(ThreadPoolRejectedPolicy.CallerRuns)] [InlineData(ThreadPoolRejectedPolicy.Discard)] [InlineData(ThreadPoolRejectedPolicy.Abort)] public async Task UnderManyProducers_EveryBranchRunsOnceOrIsCountedAsRejected_AndNothingIsLeftBehind( ThreadPoolRejectedPolicy policy) { const int producers = 16; const int perProducer = 2_000; const int offered = producers * perProducer; var pool = Pool(2, 3, policy); var runs = new int[offered]; var accepted = new bool[offered]; var discarded = 0; var aborted = 0; await Task.WhenAll(Enumerable.Range(0, producers).Select(p => Task.Run(async () => { for (var i = 0; i < perProducer; i++) { var id = p * perProducer + i; try { var taken = await pool.Execute(async () => { Interlocked.Increment(ref runs[id]); if (id % 7 == 0) await Task.Yield(); }); if (taken) accepted[id] = true; else Interlocked.Increment(ref discarded); } catch (RejectedExecutionException) { Interlocked.Increment(ref aborted); } } }))); await pool.DrainAsync(new CancellationTokenSource(TimeSpan.FromSeconds(30)).Token); pool.Active.Should().Be(0); pool.Queued.Should().Be(0, "no branch is left in the queue"); var ran = runs.Count(r => r == 1); runs.Should().OnlyContain(r => r == 0 || r == 1, "no branch runs twice"); Enumerable.Range(0, offered).Where(id => accepted[id]).Should().OnlyContain(id => runs[id] == 1, "every accepted branch ran"); (ran + discarded + aborted).Should().Be(offered, "every branch either ran or was counted as rejected"); pool.Rejected.Should().Be(discarded + aborted); if (policy == ThreadPoolRejectedPolicy.CallerRuns) ran.Should().Be(offered, "nothing is lost under CallerRuns"); } // ── Profiles ── [Fact] public async Task ANamedProfile_RegisteredTwiceWithOtherBounds_Throws_NamingBoth() { await using var context = new RouteContext(); context.AddThreadPoolProfile("audit", new ThreadPoolProfile { MaxConcurrency = 4 }); context.AddThreadPoolProfile("audit", new ThreadPoolProfile { MaxConcurrency = 4 }); var act = () => context.AddThreadPoolProfile("audit", new ThreadPoolProfile { MaxConcurrency = 8 }); act.Should().Throw().WithMessage("*'audit'*MaxConcurrency=4*MaxConcurrency=8*"); } [Fact] public async Task AProfileFromTheOptions_IsKnownToTheContext() { var options = new RouteEngineOptions(); options.ThreadPoolProfiles["audit"] = new ThreadPoolProfile { MaxConcurrency = 3 }; await using var context = new RouteContext(options: options); context.GetThreadPoolProfile("audit").MaxConcurrency.Should().Be(3); context.GetThreadPoolProfile(null).Should().BeSameAs(options.DefaultThreadPoolProfile); } [Fact] public async Task AnUnknownProfile_FailsTheRouteBuild_NamingIt() { await using var context = new RouteContext(); context.AddRoutes(r => r.From("direct://pool-unknown").WireTap("direct://pool-sink", executorService: "no-such-pool")); var act = () => context.Start(); await act.Should().ThrowAsync().Where(e => ContainsMessage(e, "no-such-pool")); } [Fact] public async Task ATap_UsesItsNamedProfile() { await using var context = new RouteContext(); context.AddThreadPoolProfile("tiny", new ThreadPoolProfile { MaxConcurrency = 1, MaxQueueSize = 0 }); var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var tapped = 0; context.AddRoutes(r => r.From("direct://pool-sink").Process(async (_, _) => { Interlocked.Increment(ref tapped); await gate.Task; })); context.AddRoutes(r => r.From("direct://pool-named").WireTap("direct://pool-sink", executorService: "tiny")); var producer = await Start(context, "direct://pool-named"); await producer.Process(new Exchange(new Message("first"))); await WaitFor(() => Volatile.Read(ref tapped) == 1); // The one slot is taken and there is no queue: the caller runs the second tap and waits for it. var second = producer.Process(new Exchange(new Message("second"))); await WaitFor(() => Volatile.Read(ref tapped) == 2); second.IsCompleted.Should().BeFalse("the caller is running the tap itself"); gate.SetResult(); await second; } // ── A caller-run tap is still detached ── /// A database stand-in: a resource enlisted in the ambient transaction that logs its outcome. private sealed class LoggedDatabase(List log) : IEnlistmentNotification { public void Prepare(PreparingEnlistment enlistment) => enlistment.Prepared(); public void Commit(Enlistment enlistment) { lock (log) log.Add("db:commit"); enlistment.Done(); } public void Rollback(Enlistment enlistment) { lock (log) log.Add("db:rollback"); enlistment.Done(); } public void InDoubt(Enlistment enlistment) => enlistment.Done(); } private static RouteEngineOptions CallerRunsAlways() => new() { DefaultThreadPoolProfile = new ThreadPoolProfile { MaxConcurrency = 1, MaxQueueSize = 0 }, }; [Theory] [InlineData(true, false)] [InlineData(false, true)] public async Task ACallerRunTap_RunsOutsideTheCallersTransaction_OnACopyWithoutItsSends(bool tapFails, bool mainFails) { var log = new List(); var occupy = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); await using var context = new RouteContext(options: CallerRunsAlways()); context.AddRoutes(r => r.From("direct://tx-tap-sink").Process(async (e, _) => { if (e.In.Body is "occupy") { await occupy.Task; return; } lock (log) { log.Add(Transaction.Current is null ? "tap:no-transaction" : "tap:in-transaction"); log.Add(e.Properties.ContainsKey(TransactedProcessor.TransactActionPropertyKey) ? "tap:has-sends" : "tap:no-sends"); } if (tapFails) throw new InvalidOperationException("the tap fails"); })); context.AddRoutes(r => r .From("direct://tx-tap") .Transacted() .Process(_ => { Transaction.Current!.EnlistVolatile(new LoggedDatabase(log), EnlistmentOptions.None); }) .WireTap("direct://tx-tap-sink") .Process(_ => { if (mainFails) throw new InvalidOperationException("the main work fails after the tap"); }) .End()); // The tap's only slot is taken by a branch that waits; with no queue the next tap runs in the caller. var occupier = await Start(context, "direct://tx-tap"); var tapProducer = context.GetEndpoint("direct://tx-tap-sink").CreateProducer(); await tapProducer.Start(); var pool = FindWireTap(context); _ = pool.Executor.Execute(() => tapProducer.Process(new Exchange(new Message("occupy")))); await WaitFor(() => pool.Executor.Active == 1); var send = () => occupier.Process(new Exchange(new Message("work"))); if (mainFails) await send.Should().ThrowAsync().WithMessage("the main work fails after the tap"); else await send.Should().NotThrowAsync("a failing tap never fails the main flow"); occupy.SetResult(); pool.Executor.CallerRuns.Should().Be(1, "the pool was full, so the caller ran the tap before it went on"); lock (log) { log.Should().Contain("tap:no-transaction", "the caller-run tap is detached from the caller's transaction"); log.Should().Contain("tap:no-sends", "the copy does not carry the caller's deferred sends"); log.Should().Contain(mainFails ? "db:rollback" : "db:commit", mainFails ? "the main transaction rolls back although the tap ran" : "the main transaction commits although the tap failed"); } } private static WireTapProcessor FindWireTap(RouteContext context) => context.DisposableProcessors.OfType().Single(); private static async Task Start(RouteContext context, string uri) { await context.Start(); var producer = context.GetEndpoint(uri).CreateProducer(); await producer.Start(); return producer; } private static bool ContainsMessage(Exception? e, string text) { for (; e is not null; e = e.InnerException) if (e.Message.Contains(text, StringComparison.Ordinal)) return true; return false; } private static async Task WaitFor(Func condition) { var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(10); while (!condition()) { DateTime.UtcNow.Should().BeBefore(deadline); await Task.Delay(10); } } } Path: redb-route/tests/redb.Route.Tests/Processors/DynamicRouterProcessorTests.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/Processors/DynamicRouterProcessorTests.cs ---- using AwesomeAssertions; using NSubstitute; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Processors; namespace redb.Route.Tests.Processors; /// Tests for . public class DynamicRouterProcessorTests { private static (IRouteContext context, Dictionary> received) SetupContext( params string[] uris) { var received = new Dictionary>(); var context = Substitute.For(); foreach (var uri in uris) { received[uri] = []; var capturedUri = uri; var producer = Substitute.For(); producer.When(p => p.Process(Arg.Any(), Arg.Any())) .Do(ci => received[capturedUri].Add(ci.Arg())); var endpoint = Substitute.For(); endpoint.CreateProducer().Returns(producer); context.GetEndpoint(uri).Returns(endpoint); } return (context, received); } [Fact] public async Task Process_SingleHop_RoutesToUri() { var (context, received) = SetupContext("direct://step1"); var callCount = 0; var router = new DynamicRouterProcessor(context, _ => { callCount++; return callCount == 1 ? "direct://step1" : null; }); await router.Process(new Exchange(new Message("data"))); received["direct://step1"].Should().HaveCount(1); } [Fact] public async Task Process_MultipleHops_VisitsEachUri() { var (context, received) = SetupContext("direct://a", "direct://b", "direct://c"); var hops = new Queue(["direct://a", "direct://b", "direct://c", null]); var router = new DynamicRouterProcessor(context, _ => hops.Dequeue()); await router.Process(new Exchange(new Message("slip"))); received["direct://a"].Should().HaveCount(1); received["direct://b"].Should().HaveCount(1); received["direct://c"].Should().HaveCount(1); } [Fact] public async Task Process_NullOnFirstCall_DoesNothing() { var context = Substitute.For(); var router = new DynamicRouterProcessor(context, _ => null); await router.Process(new Exchange()); context.DidNotReceive().GetEndpoint(Arg.Any()); } [Fact] public async Task Process_RoutingFunctionSeesModifiedExchange() { var bodies = new List(); var producer = Substitute.For(); producer.When(p => p.Process(Arg.Any(), Arg.Any())) .Do(ci => ci.Arg().In.Body = "modified"); var endpoint = Substitute.For(); endpoint.CreateProducer().Returns(producer); var context = Substitute.For(); context.GetEndpoint(Arg.Any()).Returns(endpoint); var callCount = 0; var router = new DynamicRouterProcessor(context, ex => { bodies.Add(ex.In.Body); callCount++; return callCount <= 2 ? "direct://step" : null; }); await router.Process(new Exchange(new Message("original"))); bodies[0].Should().Be("original"); bodies[1].Should().Be("modified"); // After first hop modified the body } [Fact] public async Task Process_ExceedsMaxHops_ThrowsInvalidOperation() { var producer = Substitute.For(); var endpoint = Substitute.For(); endpoint.CreateProducer().Returns(producer); var context = Substitute.For(); context.GetEndpoint(Arg.Any()).Returns(endpoint); // Always returns a URI → infinite loop var router = new DynamicRouterProcessor(context, _ => "direct://infinite"); var act = () => router.Process(new Exchange()); await act.Should().ThrowAsync() .WithMessage("*maximum hop count*"); } [Fact] public async Task Process_StoppedExchange_BreaksLoop() { var (context, received) = SetupContext("direct://a", "direct://b"); // Producer for "a" stops the exchange var producerA = Substitute.For(); producerA.When(p => p.Process(Arg.Any(), Arg.Any())) .Do(ci => ci.Arg().Stop()); var endpointA = Substitute.For(); endpointA.CreateProducer().Returns(producerA); context.GetEndpoint("direct://a").Returns(endpointA); var hops = new Queue(["direct://a", "direct://b", null]); var router = new DynamicRouterProcessor(context, _ => hops.Dequeue()); await router.Process(new Exchange()); // "b" should not be reached because exchange was stopped after "a" received["direct://b"].Should().BeEmpty(); } [Fact] public async Task Process_CachesProducerPerUri() { var producer = Substitute.For(); var endpoint = Substitute.For(); endpoint.CreateProducer().Returns(producer); var context = Substitute.For(); context.GetEndpoint("direct://x").Returns(endpoint); var callCount = 0; var router = new DynamicRouterProcessor(context, _ => ++callCount <= 2 ? "direct://x" : null); // 2 hops to same URI await router.Process(new Exchange()); // Should create producer only once despite 2 hops endpoint.Received(1).CreateProducer(); } [Fact] public void Constructor_NullContext_Throws() { var act = () => new DynamicRouterProcessor(null!, _ => null); act.Should().Throw().WithParameterName("context"); } [Fact] public void Constructor_NullRoutingFunction_Throws() { var act = () => new DynamicRouterProcessor(Substitute.For(), null!); act.Should().Throw().WithParameterName("routingFunction"); } [Fact] public async Task Process_Cancellation_StopsRouting() { var producer = Substitute.For(); var endpoint = Substitute.For(); endpoint.CreateProducer().Returns(producer); var context = Substitute.For(); context.GetEndpoint(Arg.Any()).Returns(endpoint); using var cts = new CancellationTokenSource(); var callCount = 0; var router = new DynamicRouterProcessor(context, _ => { callCount++; if (callCount == 2) cts.Cancel(); return "direct://loop"; }); // Should stop after cancellation await router.Process(new Exchange(), cts.Token); callCount.Should().Be(2); // Called twice, cancelled before 3rd } } Path: redb-route/tests/redb.Route.Tests/Processors/EipEndStyleScopeTests.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/Processors/EipEndStyleScopeTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Components; using redb.Route.Core; using redb.Route.Processors; namespace redb.Route.Tests.Processors; /// /// W4.5 variant-C demos: end-style scope form for Filter() / /// IdempotentConsumer(). The opener pushes a block frame; the body /// is closed either by an explicit EndFilter() / EndIdempotentConsumer() /// / End(), or auto-drained at freeze (mirroring legacy tail-consuming). /// public class EipEndStyleScopeTests { /// Filter end-style: body runs only when predicate is true; tail after EndFilter runs always. [Fact] public async Task Filter_EndStyle_BodyConditional_TailAfterEndUnconditional() { await using var context = new RouteContext(); var inFilter = new List(); var afterEnd = new List(); context.AddRoutes(r => { r.From("direct://flt-end") .Filter(e => (int)e.In.Body! % 2 == 0) .Process(e => inFilter.Add((int)e.In.Body!)) .EndFilter() .Process(e => afterEnd.Add((int)e.In.Body!)); }); await context.Start(); var producer = context.GetEndpoint("direct://flt-end").CreateProducer(); await producer.Start(); foreach (var i in new[] { 1, 2, 3, 4 }) await producer.Process(new Exchange(new Message(i))); inFilter.Should().Equal(2, 4); afterEnd.Should().Equal(1, 2, 3, 4); } /// Filter end-style with generic End(): same semantics as EndFilter(). [Fact] public async Task Filter_EndStyle_GenericEnd_AlsoCloses() { await using var context = new RouteContext(); var inFilter = new List(); var afterEnd = new List(); context.AddRoutes(r => { r.From("direct://flt-genend") .Filter(e => (int)e.In.Body! % 2 == 0) .Process(e => inFilter.Add((int)e.In.Body!)) .End() .Process(e => afterEnd.Add((int)e.In.Body!)); }); await context.Start(); var producer = context.GetEndpoint("direct://flt-genend").CreateProducer(); await producer.Start(); foreach (var i in new[] { 1, 2, 3, 4 }) await producer.Process(new Exchange(new Message(i))); inFilter.Should().Equal(2, 4); afterEnd.Should().Equal(1, 2, 3, 4); } /// Legacy implicit form (no EndFilter): tail still consumed by filter via auto-drain at freeze. [Fact] public async Task Filter_ImplicitForm_AutoDrain_StillTailConsuming() { await using var context = new RouteContext(); var seen = new List(); context.AddRoutes(r => { r.From("direct://flt-implicit") .Filter(e => (int)e.In.Body! % 2 == 0) .Process(e => seen.Add((int)e.In.Body!)); }); await context.Start(); var producer = context.GetEndpoint("direct://flt-implicit").CreateProducer(); await producer.Start(); foreach (var i in new[] { 1, 2, 3, 4, 5 }) await producer.Process(new Exchange(new Message(i))); seen.Should().Equal(2, 4); } /// IdempotentConsumer end-style: body runs only for first-seen keys; tail after End runs always. [Fact] public async Task IdempotentConsumer_EndStyle_BodyDeduped_TailUnconditional() { await using var context = new RouteContext(); var inIc = new List(); var afterEnd = new List(); var repo = new InMemoryIdempotentRepository(); context.AddRoutes(r => { r.From("direct://ic-end") .IdempotentConsumer(e => e.In.Body!.ToString()!, repo) .Process(e => inIc.Add((int)e.In.Body!)) .EndIdempotentConsumer() .Process(e => afterEnd.Add((int)e.In.Body!)); }); await context.Start(); var producer = context.GetEndpoint("direct://ic-end").CreateProducer(); await producer.Start(); foreach (var i in new[] { 1, 2, 1, 2, 3 }) await producer.Process(new Exchange(new Message(i))); inIc.Should().Equal(1, 2, 3); afterEnd.Should().Equal(1, 2, 1, 2, 3); } /// EndFilter on empty stack throws. [Fact] public void EndFilter_WithoutOpenFilter_Throws() { var def = new redb.Route.Definitions.RouteDefinition(); def.From("direct://flt-err"); var act = () => def.EndFilter(); act.Should().Throw(); } /// EndIdempotentConsumer on empty stack throws. [Fact] public void EndIdempotentConsumer_WithoutOpenIc_Throws() { var def = new redb.Route.Definitions.RouteDefinition(); def.From("direct://ic-err"); var act = () => def.EndIdempotentConsumer(); act.Should().Throw(); } /// Filter end-style with multiple processors in the body: all run together, all skipped together. [Fact] public async Task Filter_EndStyle_MultiStepBody_AllOrNothing() { await using var context = new RouteContext(); var stepA = new List(); var stepB = new List(); var stepC = new List(); var afterEnd = new List(); context.AddRoutes(r => { r.From("direct://flt-multi") .Filter(e => (int)e.In.Body! % 2 == 0) .Process(e => stepA.Add((int)e.In.Body!)) .Process(e => stepB.Add((int)e.In.Body! * 10)) .Process(e => stepC.Add((int)e.In.Body! + 100)) .EndFilter() .Process(e => afterEnd.Add((int)e.In.Body!)); }); await context.Start(); var producer = context.GetEndpoint("direct://flt-multi").CreateProducer(); await producer.Start(); foreach (var i in new[] { 1, 2, 3, 4 }) await producer.Process(new Exchange(new Message(i))); stepA.Should().Equal(2, 4); stepB.Should().Equal(20, 40); stepC.Should().Equal(102, 104); afterEnd.Should().Equal(1, 2, 3, 4); } /// Filter end-style nested inside Filter end-style: inner runs only when BOTH predicates hold (AND). [Fact] public async Task Filter_EndStyle_NestedInsideFilter_AndSemantics() { await using var context = new RouteContext(); var outerOnly = new List(); var innerBody = new List(); var outerTail = new List(); var afterAll = new List(); context.AddRoutes(r => { r.From("direct://flt-nested") .Filter(e => (int)e.In.Body! % 2 == 0) // even .Process(e => outerOnly.Add((int)e.In.Body!)) .Filter(e => (int)e.In.Body! > 3) // even AND > 3 .Process(e => innerBody.Add((int)e.In.Body!)) .EndFilter() .Process(e => outerTail.Add((int)e.In.Body!)) .EndFilter() .Process(e => afterAll.Add((int)e.In.Body!)); }); await context.Start(); var producer = context.GetEndpoint("direct://flt-nested").CreateProducer(); await producer.Start(); foreach (var i in new[] { 1, 2, 3, 4, 5, 6 }) await producer.Process(new Exchange(new Message(i))); outerOnly.Should().Equal(2, 4, 6); // even innerBody.Should().Equal(4, 6); // even AND > 3 outerTail.Should().Equal(2, 4, 6); // back in outer scope: even only afterAll.Should().Equal(1, 2, 3, 4, 5, 6); // unconditional } /// Two consecutive Filter end-style blocks compose as AND filters with a tail in between. [Fact] public async Task Filter_EndStyle_TwoSequential_ComposeIndependently() { await using var context = new RouteContext(); var first = new List(); var middle = new List(); var second = new List(); var tail = new List(); context.AddRoutes(r => { r.From("direct://flt-seq") .Filter(e => (int)e.In.Body! % 2 == 0) .Process(e => first.Add((int)e.In.Body!)) .EndFilter() .Process(e => middle.Add((int)e.In.Body!)) // unconditional middle .Filter(e => (int)e.In.Body! > 2) .Process(e => second.Add((int)e.In.Body!)) .EndFilter() .Process(e => tail.Add((int)e.In.Body!)); }); await context.Start(); var producer = context.GetEndpoint("direct://flt-seq").CreateProducer(); await producer.Start(); foreach (var i in new[] { 1, 2, 3, 4 }) await producer.Process(new Exchange(new Message(i))); first.Should().Equal(2, 4); // even middle.Should().Equal(1, 2, 3, 4); // all second.Should().Equal(3, 4); // > 2 tail.Should().Equal(1, 2, 3, 4); // all } /// IdempotentConsumer end-style with multi-step body wraps the whole body in dedupe. [Fact] public async Task IdempotentConsumer_EndStyle_MultiStepBody_DedupesAllSteps() { await using var context = new RouteContext(); var stepA = new List(); var stepB = new List(); var afterEnd = new List(); var repo = new InMemoryIdempotentRepository(); context.AddRoutes(r => { r.From("direct://ic-multi") .IdempotentConsumer(e => e.In.Body!.ToString()!, repo) .Process(e => stepA.Add((int)e.In.Body!)) .Process(e => stepB.Add((int)e.In.Body! * 10)) .EndIdempotentConsumer() .Process(e => afterEnd.Add((int)e.In.Body!)); }); await context.Start(); var producer = context.GetEndpoint("direct://ic-multi").CreateProducer(); await producer.Start(); foreach (var i in new[] { 1, 2, 1, 2, 3 }) await producer.Process(new Exchange(new Message(i))); stepA.Should().Equal(1, 2, 3); // first-seen only stepB.Should().Equal(10, 20, 30); // same dedupe scope afterEnd.Should().Equal(1, 2, 1, 2, 3); // tail every time } /// Filter end-style wrapping IdempotentConsumer end-style: even-only, then deduped by key. [Fact] public async Task Filter_EndStyle_Wrapping_IdempotentConsumer_EndStyle() { await using var context = new RouteContext(); var inFilter = new List(); var inIc = new List(); var afterIc = new List(); var afterFlt = new List(); var repo = new InMemoryIdempotentRepository(); context.AddRoutes(r => { r.From("direct://flt-wrap-ic") .Filter(e => (int)e.In.Body! % 2 == 0) .Process(e => inFilter.Add((int)e.In.Body!)) .IdempotentConsumer(e => e.In.Body!.ToString()!, repo) .Process(e => inIc.Add((int)e.In.Body!)) .EndIdempotentConsumer() .Process(e => afterIc.Add((int)e.In.Body!)) .EndFilter() .Process(e => afterFlt.Add((int)e.In.Body!)); }); await context.Start(); var producer = context.GetEndpoint("direct://flt-wrap-ic").CreateProducer(); await producer.Start(); foreach (var i in new[] { 1, 2, 3, 2, 4, 4, 5 }) await producer.Process(new Exchange(new Message(i))); inFilter.Should().Equal(2, 2, 4, 4); // every even inIc.Should().Equal(2, 4); // first-seen even keys afterIc.Should().Equal(2, 2, 4, 4); // back in filter scope (every even) afterFlt.Should().Equal(1, 2, 3, 2, 4, 4, 5); // unconditional } /// Three-level Filter nesting end-style: predicates compose as logical AND down the stack. [Fact] public async Task Filter_EndStyle_ThreeLevelNesting_AndComposition() { await using var context = new RouteContext(); var l1 = new List(); var l2 = new List(); var l3 = new List(); var tail = new List(); context.AddRoutes(r => { r.From("direct://flt-3lvl") .Filter(e => (int)e.In.Body! > 0) // positive .Process(e => l1.Add((int)e.In.Body!)) .Filter(e => (int)e.In.Body! % 2 == 0) // pos AND even .Process(e => l2.Add((int)e.In.Body!)) .Filter(e => (int)e.In.Body! >= 4) // pos AND even AND >=4 .Process(e => l3.Add((int)e.In.Body!)) .EndFilter() .EndFilter() .EndFilter() .Process(e => tail.Add((int)e.In.Body!)); }); await context.Start(); var producer = context.GetEndpoint("direct://flt-3lvl").CreateProducer(); await producer.Start(); foreach (var i in new[] { -1, 0, 1, 2, 3, 4, 5, 6 }) await producer.Process(new Exchange(new Message(i))); l1.Should().Equal(1, 2, 3, 4, 5, 6); // > 0 l2.Should().Equal(2, 4, 6); // > 0 AND even l3.Should().Equal(4, 6); // > 0 AND even AND >= 4 tail.Should().Equal(-1, 0, 1, 2, 3, 4, 5, 6); // all } } Path: redb-route/tests/redb.Route.Tests/Processors/EipNestedScopeTests.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/Processors/EipNestedScopeTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Components; using redb.Route.Core; using redb.Route.Processors; namespace redb.Route.Tests.Processors; /// /// Educational end-to-end demos of the W4.4 explicit scope-form for /// Filter(predicate, body) and IdempotentConsumer(..., body) /// nested inside other scope-EIPs (Split / Loop / Choice / Filter). /// /// These tests are intentionally minimal and assertion-rich: they document /// the Camel-canonical "body is closed, tail keeps flowing" semantics that /// the W4.4 Action-overloads introduce on top of the existing /// tail-consuming (implicit-scope) Filter / IC. /// public class EipNestedScopeTests { /// Filter scope inside a Split body: per-item filter, post-filter tail still runs for every part. [Fact] public async Task FilterScope_InsideSplit_BodyConditional_TailPerPart() { await using var context = new RouteContext(); var inFilter = new List(); var afterFilter = new List(); context.AddRoutes(r => { r.From("direct://split-flt") .Split(e => (IEnumerable)e.In.Body!, b => b .Filter(e => (int)e.In.Body! % 2 == 0, fb => fb .Process(e => inFilter.Add((int)e.In.Body!))) .Process(e => afterFilter.Add((int)e.In.Body!))); }); await context.Start(); var producer = context.GetEndpoint("direct://split-flt").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message(new object?[] { 1, 2, 3, 4, 5 }))); inFilter.Should().Equal(2, 4); afterFilter.Should().Equal(1, 2, 3, 4, 5); } /// Filter scope inside a Loop body: counter-based filter, post-filter tail runs every iteration. [Fact] public async Task FilterScope_InsideLoop_BodyConditional_TailEveryIteration() { await using var context = new RouteContext(); var inFilter = 0; var afterFilter = 0; context.AddRoutes(r => { r.From("direct://loop-flt") .Loop(5, b => b .Filter(_ => inFilter + afterFilter < 3, fb => fb .Process(_ => inFilter++)) .Process(_ => afterFilter++)); }); await context.Start(); var producer = context.GetEndpoint("direct://loop-flt").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("go"))); afterFilter.Should().Be(5); // tail runs every iteration inFilter.Should().BeGreaterThan(0).And.BeLessThan(5); } /// Filter scope inside a Choice When branch: branch tail still runs after filtered body. [Fact] public async Task FilterScope_InsideChoiceWhen_BodyConditional_BranchTailRuns() { await using var context = new RouteContext(); var inFilter = new List(); var branchTail = new List(); var afterChoice = new List(); context.AddRoutes(r => { r.From("direct://choice-flt") .Choice(c => c .When(e => (int)e.In.Body! > 0, b => b .Filter(e => (int)e.In.Body! % 2 == 0, fb => fb .Process(e => inFilter.Add((int)e.In.Body!))) .Process(e => branchTail.Add((int)e.In.Body!)))) .Process(e => afterChoice.Add((int)e.In.Body!)); }); await context.Start(); var producer = context.GetEndpoint("direct://choice-flt").CreateProducer(); await producer.Start(); foreach (var i in new[] { -1, 1, 2, 3, 4 }) await producer.Process(new Exchange(new Message(i))); inFilter.Should().Equal(2, 4); branchTail.Should().Equal(1, 2, 3, 4); // when-branch tail: positives only afterChoice.Should().Equal(-1, 1, 2, 3, 4); // after-choice tail: all } /// IdempotentConsumer scope inside a Split body: dedupe per element across the whole stream. [Fact] public async Task IcScope_InsideSplit_BodyOnFirstSeen_TailEveryPart() { await using var context = new RouteContext(); var repo = new InMemoryIdempotentRepository(); var inBody = new List(); var afterBody = new List(); context.AddRoutes(r => { r.From("direct://split-ic") .Split(e => (IEnumerable)e.In.Body!, b => b .IdempotentConsumer(e => (string)e.In.Body!, repo, ib => ib .Process(e => inBody.Add((string)e.In.Body!))) .Process(e => afterBody.Add((string)e.In.Body!))); }); await context.Start(); var producer = context.GetEndpoint("direct://split-ic").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message(new object?[] { "a", "b", "a", "c", "b" }))); inBody.Should().Equal("a", "b", "c"); afterBody.Should().Equal("a", "b", "a", "c", "b"); } /// Nested Filter scopes compose as logical AND for the inner body; outer tail still runs unconditionally. [Fact] public async Task FilterScope_InsideFilterScope_AndSemantics_OuterTailUnconditional() { await using var context = new RouteContext(); var inInner = new List(); var afterOuter = new List(); context.AddRoutes(r => { r.From("direct://flt-flt") .Filter(e => (int)e.In.Body! > 0, ob => ob .Filter(e => (int)e.In.Body! % 2 == 0, ib => ib .Process(e => inInner.Add((int)e.In.Body!)))) .Process(e => afterOuter.Add((int)e.In.Body!)); }); await context.Start(); var producer = context.GetEndpoint("direct://flt-flt").CreateProducer(); await producer.Start(); foreach (var i in new[] { -2, -1, 0, 1, 2, 3, 4 }) await producer.Process(new Exchange(new Message(i))); inInner.Should().Equal(2, 4); // positive AND even afterOuter.Should().Equal(-2, -1, 0, 1, 2, 3, 4); // outer tail: all } /// Sequential Filter then IC scopes at the same level: both bodies are independent islands, common tail runs always. [Fact] public async Task FilterScope_ThenIcScope_AtSameLevel_IndependentBodies_CommonTailAlways() { await using var context = new RouteContext(); var repo = new InMemoryIdempotentRepository(); var inFilter = new List(); var inIc = new List(); var tail = new List(); context.AddRoutes(r => { r.From("direct://flt-then-ic") .Filter(e => (int)e.In.Body! % 2 == 0, fb => fb .Process(e => inFilter.Add((int)e.In.Body!))) .IdempotentConsumer(e => e.In.Body!.ToString()!, repo, ib => ib .Process(e => inIc.Add((int)e.In.Body!))) .Process(e => tail.Add((int)e.In.Body!)); }); await context.Start(); var producer = context.GetEndpoint("direct://flt-then-ic").CreateProducer(); await producer.Start(); foreach (var i in new[] { 1, 2, 1, 2, 3 }) await producer.Process(new Exchange(new Message(i))); inFilter.Should().Equal(2, 2); // even only, no dedupe inIc.Should().Equal(1, 2, 3); // dedupe only, no filter tail.Should().Equal(1, 2, 1, 2, 3); // tail always } } Path: redb-route/tests/redb.Route.Tests/Processors/EipPatternIntegrationTests.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/Processors/EipPatternIntegrationTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Components; using redb.Route.Core; using redb.Route.Processors; namespace redb.Route.Tests.Processors; /// /// Integration tests for the 6 EIP patterns through the DSL → Compiler → Engine pipeline. /// public class EipPatternIntegrationTests : IAsyncLifetime { private readonly RouteContext _context = new(); public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { await _context.DisposeAsync(); GC.SuppressFinalize(this); } // ────────────────── Throttle ────────────────── [Fact] public async Task Throttle_InRoute_LimitsRate() { var received = new List(); _context.AddRoutes(r => { r.From("direct://throttle-in") .Throttle(5) // 5 per second .Process(e => received.Add(e.In.Body)); }); await _context.Start(); var producer = _context.GetEndpoint("direct://throttle-in").CreateProducer(); await producer.Start(); for (int i = 0; i < 5; i++) await producer.Process(new Exchange(new Message($"msg-{i}"))); received.Should().HaveCount(5); } [Fact] public async Task Throttle_WithPeriod_InRoute() { var received = new List(); _context.AddRoutes(r => { r.From("direct://throttle-period") .Throttle(10, TimeSpan.FromSeconds(2)) .Process(e => received.Add(e.In.Body)); }); await _context.Start(); var producer = _context.GetEndpoint("direct://throttle-period").CreateProducer(); await producer.Start(); for (int i = 0; i < 10; i++) await producer.Process(new Exchange(new Message(i))); received.Should().HaveCount(10); } // ────────────────── CircuitBreaker ────────────────── [Fact] public async Task CircuitBreaker_InRoute_HandlesFailures() { var processed = new List(); var shouldFail = true; _context.AddRoutes(r => { r.From("direct://cb-in") .CircuitBreaker(cb => { cb.Threshold(2) .ResetTimeout(TimeSpan.FromMilliseconds(100)); }) .Process(e => { if (shouldFail) throw new InvalidOperationException("fail"); processed.Add((string)e.In.Body!); }); }); await _context.Start(); var producer = _context.GetEndpoint("direct://cb-in").CreateProducer(); await producer.Start(); // 2 failures → circuit opens await producer.Process(new Exchange(new Message("f1"))); await producer.Process(new Exchange(new Message("f2"))); // Circuit is open — this should not reach processor, should get CircuitBreakerOpenException var blockedExchange = new Exchange(new Message("blocked")); await producer.Process(blockedExchange); blockedExchange.Exception.Should().BeOfType(); // Wait for reset timeout await Task.Delay(150); // Now let it succeed shouldFail = false; await producer.Process(new Exchange(new Message("recovery"))); processed.Should().Contain("recovery"); } [Fact] public async Task CircuitBreaker_WithFallback_InRoute() { var mainProcessed = new List(); var fallbackProcessed = new List(); _context.AddRoutes(r => { r.From("direct://cb-fallback") .CircuitBreaker(cb => { cb.Threshold(1) .ResetTimeout(TimeSpan.FromMinutes(5)) .FallBack(fb => fb.Process(e => fallbackProcessed.Add((string)e.In.Body!))); }) .Process(e => { mainProcessed.Add((string)e.In.Body!); throw new InvalidOperationException("fail"); }); }); await _context.Start(); var producer = _context.GetEndpoint("direct://cb-fallback").CreateProducer(); await producer.Start(); // First call fails → trips circuit await producer.Process(new Exchange(new Message("first"))); mainProcessed.Should().HaveCount(1); // Second call → circuit open, uses fallback await producer.Process(new Exchange(new Message("second"))); fallbackProcessed.Should().Contain("second"); } // ────────────────── Resequencer ────────────────── [Fact] public async Task Resequence_InRoute_OrdersByKey() { var received = new List(); _context.AddRoutes(r => { r.From("direct://reseq-in") .Resequence( keySelector: e => (long)e.In.Headers["seq"]!, batchSize: 3) .Process(e => received.Add((long)e.In.Headers["seq"]!)); }); await _context.Start(); var producer = _context.GetEndpoint("direct://reseq-in").CreateProducer(); await producer.Start(); // Send out-of-order foreach (var seq in new long[] { 3, 1, 2 }) { var msg = new Message("data"); msg.Headers["seq"] = seq; await producer.Process(new Exchange(msg)); } received.Should().Equal(1L, 2L, 3L); } // ────────────────── RecipientList ────────────────── [Fact] public async Task RecipientList_InRoute_RoutesToDynamicUris() { var receivedA = new List(); var receivedB = new List(); _context.AddRoutes(r => { r.From("direct://rl-in") .RecipientList(e => { var targets = (string)e.In.Headers["targets"]!; return targets.Split(','); }); r.From("direct://targetA") .Process(e => receivedA.Add(e.In.Body)); r.From("direct://targetB") .Process(e => receivedB.Add(e.In.Body)); }); await _context.Start(); var producer = _context.GetEndpoint("direct://rl-in").CreateProducer(); await producer.Start(); var msg = new Message("payload"); msg.Headers["targets"] = "direct://targetA,direct://targetB"; await producer.Process(new Exchange(msg)); receivedA.Should().HaveCount(1); receivedB.Should().HaveCount(1); receivedA[0].Should().Be("payload"); } // ────────────────── Enrich ────────────────── [Fact] public async Task Enrich_InRoute_MergesResourceData() { var result = new List(); _context.AddRoutes(r => { r.From("direct://enrich-in") .Enrich("direct://lookup", (original, enriched) => { original.In.Body = $"{original.In.Body}+{enriched.In.Body}"; return original; }) .Process(e => result.Add((string)e.In.Body!)); r.From("direct://lookup") .Process(e => e.In.Body = "extra-data"); }); await _context.Start(); var producer = _context.GetEndpoint("direct://enrich-in").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("base"))); result.Should().HaveCount(1); result[0].Should().Be("base+extra-data"); } // ────────────────── PollEnrich ────────────────── [Fact] public async Task PollEnrich_InRoute_MergesPolledData() { var result = new List(); _context.AddRoutes(r => { r.From("direct://pollenrich-in") .PollEnrich("direct://poll-source", (original, polled) => { original.In.Body = polled is not null ? $"{original.In.Body}+{polled.In.Body}" : $"{original.In.Body}+timeout"; return original; }, timeout: TimeSpan.FromSeconds(5)) .Process(e => result.Add((string)e.In.Body!)); r.From("direct://poll-source") .Process(e => e.In.Body = "polled-data"); }); await _context.Start(); var producer = _context.GetEndpoint("direct://pollenrich-in").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("base"))); result.Should().HaveCount(1); result[0].Should().Be("base+polled-data"); } // ────────────────── DynamicRouter ────────────────── [Fact] public async Task DynamicRouter_InRoute_RoutesIteratively() { var visitOrder = new List(); _context.AddRoutes(r => { r.From("direct://dynrouter-in") .DynamicRouter(e => { var hop = e.GetProperty("hop"); e.Properties["hop"] = hop + 1; return hop switch { 0 => "direct://step1", 1 => "direct://step2", _ => null }; }); r.From("direct://step1") .Process(e => visitOrder.Add("step1")); r.From("direct://step2") .Process(e => visitOrder.Add("step2")); }); await _context.Start(); var producer = _context.GetEndpoint("direct://dynrouter-in").CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("data")); exchange.Properties["hop"] = 0; await producer.Process(exchange); visitOrder.Should().Equal("step1", "step2"); } [Fact] public async Task DynamicRouter_NullOnFirst_DoesNothing() { var processed = false; _context.AddRoutes(r => { r.From("direct://dynrouter-noop") .DynamicRouter(_ => null) .Process(_ => processed = true); }); await _context.Start(); var producer = _context.GetEndpoint("direct://dynrouter-noop").CreateProducer(); await producer.Start(); await producer.Process(new Exchange()); // DynamicRouter returns null immediately, so it completes. // The Process after DynamicRouter in the pipeline may or may not be reached depending on // how the compiler chains them. This test mainly validates no exceptions. } } Path: redb-route/tests/redb.Route.Tests/Processors/EndpointUriLogMaskingTests.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/Processors/EndpointUriLogMaskingTests.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Processors; using redb.Route.Processors.LoadBalancer; using redb.Route.TestKit; using redb.Route.Tests.Cluster; namespace redb.Route.Tests.Processors; /// /// An endpoint URI that a processor resolves per message or holds from configuration is logged masked: a password in /// the user-info (user:pass@) or in a password= parameter never reaches the log or an error text. /// public class EndpointUriLogMaskingTests { private const string Secret = "s3cret-XYZ"; private const string UserInfoUri = "mock://user:" + Secret + "@target"; private static (CapturingLoggerProvider Capture, ILoggerFactory Factory) Logging() { var capture = new CapturingLoggerProvider(); return (capture, LoggerFactory.Create(b => b.AddProvider(capture).SetMinimumLevel(LogLevel.Trace))); } private static void ShouldNotLeak(CapturingLoggerProvider capture, string expectedFragment) { var messages = capture.Entries.Select(e => e.Message).ToList(); messages.Should().Contain(m => m.Contains(expectedFragment, StringComparison.Ordinal), "the processor logged the line under test"); messages.Should().NotContain(m => m.Contains(Secret, StringComparison.Ordinal)); } [Fact] public async Task DynamicRouter_HopLine_IsMasked() { var (capture, factory) = Logging(); using (factory) { await using var context = new RouteContext(loggerFactory: factory); var hops = 0; context.AddRoutes(r => r.From("direct:dr").DynamicRouter(_ => hops++ == 0 ? UserInfoUri : null)); await context.Start(); await context.SendBody("direct:dr", "x"); } ShouldNotLeak(capture, "DynamicRouter: hop"); } [Fact] public async Task RoutingSlip_HopAndInvalidEndpointLines_AreMasked() { var (capture, factory) = Logging(); using (factory) { await using var context = new RouteContext(loggerFactory: factory); context.AddRoutes(r => r.From("direct:slip").RoutingSlip( _ => new[] { "nosuchscheme://user:" + Secret + "@x?password=" + Secret, UserInfoUri }, ignoreInvalidEndpoints: true)); await context.Start(); await context.SendBody("direct:slip", "x"); } ShouldNotLeak(capture, "Routing Slip: hop"); capture.Entries.Should().Contain(e => e.Message.StartsWith("Routing Slip: ignoring invalid endpoint", StringComparison.Ordinal)); } [Fact] public async Task ScatterGather_ResponseLine_IsMasked() { var (capture, factory) = Logging(); using (factory) { await using var context = new RouteContext(loggerFactory: factory); context.AddRoutes(r => r.From("direct:sg").ScatterGather((_, latest) => latest, UserInfoUri)); await context.Start(); await context.SendBody("direct:sg", "x"); } ShouldNotLeak(capture, "Scatter-gather: received response from"); } [Fact] public async Task LoadBalancer_SentLine_IsMasked() { var (capture, factory) = Logging(); using (factory) { await using var context = new RouteContext(loggerFactory: factory); context.AddRoutes(r => r.From("direct:lb").LoadBalance(new RoundRobinStrategy(), UserInfoUri)); await context.Start(); await context.SendBody("direct:lb", "x"); } ShouldNotLeak(capture, "Load balancer: sent to"); } [Fact] public async Task DeadLetterChannel_Lines_AreMasked() { var (capture, factory) = Logging(); using (factory) { await using var context = new RouteContext(loggerFactory: factory); await context.Start(); var failing = new DelegateProcessor(_ => throw new InvalidOperationException("boom")); var dlc = new DeadLetterChannelProcessor(context, failing, UserInfoUri + "?password=" + Secret, rethrow: false, logger: factory.CreateLogger()); await dlc.Process(new Exchange(new Message("x"))); } ShouldNotLeak(capture, "Dead-lettering exchange to"); } [Fact] public void ConfigurationErrors_DoNotCarryTheSecret() { var badFormat = () => EndpointUriParser.Parse("nocolon?password=" + Secret); badFormat.Should().Throw().Which.Message.Should().NotContain(Secret); var badWeight = () => new WeightedStrategy([(UserInfoUri, 0)]); badWeight.Should().Throw().Which.Message.Should().NotContain(Secret).And.Contain("must be positive"); } } Path: redb-route/tests/redb.Route.Tests/Processors/EnrichProcessorTests.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/Processors/EnrichProcessorTests.cs ---- using AwesomeAssertions; using NSubstitute; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Processors; namespace redb.Route.Tests.Processors; /// Tests for . public class EnrichProcessorTests { private static (IRouteContext context, IProducer producer) SetupContext(string uri) { var producer = Substitute.For(); var endpoint = Substitute.For(); endpoint.CreateProducer().Returns(producer); var context = Substitute.For(); context.GetEndpoint(uri).Returns(endpoint); return (context, producer); } [Fact] public async Task Process_MergesEnrichedData() { var (context, producer) = SetupContext("direct://lookup"); producer.When(p => p.Process(Arg.Any(), Arg.Any())) .Do(ci => { var ex = ci.Arg(); ex.In.Headers["enriched"] = "yes"; ex.In.Body = "enriched-body"; }); var enricher = new EnrichProcessor(context, "direct://lookup", mergeStrategy: (original, enriched) => { original.In.Headers["enriched"] = enriched.In.Headers["enriched"]; original.In.Body = $"{original.In.Body}+{enriched.In.Body}"; return original; }); var exchange = new Exchange(new Message("original-body")); await enricher.Process(exchange); exchange.In.Body.Should().Be("original-body+enriched-body"); exchange.In.Headers["enriched"].Should().Be("yes"); } private sealed class TrackingResource : IAsyncDisposable { public int DisposeCount; public ValueTask DisposeAsync() { Interlocked.Increment(ref DisposeCount); return ValueTask.CompletedTask; } } [Fact] public async Task Process_HandsTheResourceExchangesResourcesOverToTheOriginal() { var (context, producer) = SetupContext("direct://stream"); var resource = new TrackingResource(); producer.When(p => p.Process(Arg.Any(), Arg.Any())) .Do(ci => { // A streamed SQL result: the body holds a connection that is released when its exchange ends. var ex = ci.Arg(); ExchangeResources.ReleaseWithExchange(ex, resource); ex.In.Body = "stream"; }); var enricher = new EnrichProcessor(context, "direct://stream", mergeStrategy: (original, enriched) => { original.In.Body = enriched.In.Body; return original; }); var exchange = new Exchange(new Message("original")); await enricher.Process(exchange); exchange.In.Body.Should().Be("stream"); resource.DisposeCount.Should().Be(0, "as Apache Camel's Enrich hands the resource exchange's completions over, the stream lives until the original ends"); await exchange.DisposeAsync(); resource.DisposeCount.Should().Be(1); } [Fact] public async Task Process_SendsCloneToResource() { IExchange? sentExchange = null; var (context, producer) = SetupContext("direct://resource"); producer.When(p => p.Process(Arg.Any(), Arg.Any())) .Do(ci => sentExchange = ci.Arg()); var enricher = new EnrichProcessor(context, "direct://resource", mergeStrategy: (orig, _) => orig); var original = new Exchange(new Message("data")); await enricher.Process(original); sentExchange.Should().NotBeNull(); sentExchange.Should().NotBeSameAs(original); sentExchange!.In.Body.Should().Be("data"); sentExchange.Pattern.Should().Be(ExchangePattern.InOut); } [Fact] public async Task Process_CachesProducer() { var (context, producer) = SetupContext("direct://resource"); var enricher = new EnrichProcessor(context, "direct://resource", mergeStrategy: (orig, _) => orig); await enricher.Process(new Exchange(new Message("data"))); await enricher.Process(new Exchange(new Message("data2"))); // Producer created once, reused across calls context.GetEndpoint("direct://resource") .Received(1).CreateProducer(); } [Fact] public async Task Process_PreservesOriginalWhenMergeReturnsOriginal() { var (context, producer) = SetupContext("direct://resource"); producer.When(p => p.Process(Arg.Any(), Arg.Any())) .Do(ci => ci.Arg().In.Body = "enriched"); var enricher = new EnrichProcessor(context, "direct://resource", mergeStrategy: (orig, _) => orig); // Ignore enrichment var exchange = new Exchange(new Message("keep-me")); await enricher.Process(exchange); exchange.In.Body.Should().Be("keep-me"); } [Fact] public void Constructor_NullContext_Throws() { var act = () => new EnrichProcessor(null!, "direct://a", (a, b) => a); act.Should().Throw().WithParameterName("context"); } [Fact] public void Constructor_NullUri_Throws() { var act = () => new EnrichProcessor(Substitute.For(), (string)null!, (a, b) => a); act.Should().Throw().WithParameterName("resourceUri"); } [Fact] public void Constructor_NullMerge_Throws() { var act = () => new EnrichProcessor(Substitute.For(), "direct://a", null!); act.Should().Throw().WithParameterName("mergeStrategy"); } } /// Tests for . public class PollEnrichProcessorTests { private static (IRouteContext context, IProducer producer) SetupContext(string uri) { var producer = Substitute.For(); var endpoint = Substitute.For(); endpoint.CreateProducer().Returns(producer); var context = Substitute.For(); context.GetEndpoint(uri).Returns(endpoint); return (context, producer); } [Fact] public async Task Process_SuccessfulPoll_MergesData() { var (context, producer) = SetupContext("seda://queue"); producer.When(p => p.Process(Arg.Any(), Arg.Any())) .Do(ci => ci.Arg().In.Body = "polled-data"); var pollEnricher = new PollEnrichProcessor(context, "seda://queue", mergeStrategy: (original, polled) => { original.In.Body = $"{original.In.Body}+{polled!.In.Body}"; return original; }, timeout: TimeSpan.FromSeconds(5)); var exchange = new Exchange(new Message("base")); await pollEnricher.Process(exchange); exchange.In.Body.Should().Be("base+polled-data"); } [Fact] public async Task Process_Timeout_MergeReceivesNull() { var producer = Substitute.For(); // NSubstitute's When..Do with async void doesn't delay the Task return; // use Returns with an actual async task instead. producer.Process(Arg.Any(), Arg.Any()) .Returns(async ci => { var ct = ci.Arg(); await Task.Delay(TimeSpan.FromSeconds(5), ct); }); var endpoint = Substitute.For(); endpoint.CreateProducer().Returns(producer); var context = Substitute.For(); context.GetEndpoint("seda://slow").Returns(endpoint); var pollEnricher = new PollEnrichProcessor(context, "seda://slow", mergeStrategy: (original, polled) => { original.In.Body = polled is null ? "timeout" : "got-data"; return original; }, timeout: TimeSpan.FromMilliseconds(50)); var exchange = new Exchange(new Message("base")); await pollEnricher.Process(exchange); exchange.In.Body.Should().Be("timeout"); } [Fact] public async Task Process_SetsInOutPattern() { IExchange? sent = null; var (context, producer) = SetupContext("seda://queue"); producer.When(p => p.Process(Arg.Any(), Arg.Any())) .Do(ci => sent = ci.Arg()); var pollEnricher = new PollEnrichProcessor(context, "seda://queue", mergeStrategy: (orig, _) => orig); await pollEnricher.Process(new Exchange(new Message("data"))); sent.Should().NotBeNull(); sent!.Pattern.Should().Be(ExchangePattern.InOut); } [Fact] public void Constructor_NullContext_Throws() { var act = () => new PollEnrichProcessor(null!, "seda://a", (a, b) => a); act.Should().Throw().WithParameterName("context"); } [Fact] public void Constructor_NullUri_Throws() { var act = () => new PollEnrichProcessor(Substitute.For(), (string)null!, (a, b) => a); act.Should().Throw().WithParameterName("resourceUri"); } [Fact] public void Constructor_NullMerge_Throws() { var act = () => new PollEnrichProcessor(Substitute.For(), "seda://a", null!); act.Should().Throw().WithParameterName("mergeStrategy"); } } Path: redb-route/tests/redb.Route.Tests/Processors/ExceptionAndThreadSafetyTests.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/Processors/ExceptionAndThreadSafetyTests.cs ---- using System.Collections.Concurrent; using AwesomeAssertions; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Time.Testing; using NSubstitute; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Expressions; using redb.Route.Processors; namespace redb.Route.Tests.Processors; /// /// Tests for exception propagation, thread safety, and resource disposal in processors. /// public class ExceptionAndThreadSafetyTests { // ============================================================== // Condition strings - fail-fast on an invalid expression // (LogicalExpression was removed with the second parser, 2026-08-28) // ============================================================== [Fact] public void ConditionString_InvalidExpression_ThrowsAtBuildTime() { var act = () => redb.Route.Predicates.PredicateFactory.FromString("~~~INVALID~~~ >"); act.Should().Throw(); } [Fact] public void ConditionString_ValidExpression_StillWorks() { var pred = redb.Route.Predicates.PredicateFactory.FromString("property.x > 0"); var exchange = new Exchange(new Message("body")); exchange.Properties["x"] = 5; pred.Matches(exchange).Should().BeTrue(); } // ══════════════════════════════════════════════════════════════ // DebounceProcessor — downstream errors are logged and recorded // ══════════════════════════════════════════════════════════════ [Fact] public async Task Debounce_DownstreamThrows_SetsExchangeException() { var expected = new InvalidOperationException("boom"); IExchange? capturedExchange = null; var failingNext = new DelegateProcessor(ex => { capturedExchange = ex; throw expected; }); // Row 67: the quiet period runs on a FakeTimeProvider and the test waits for the error log line, which the // processor writes after it has set the exception. A fixed 200 ms wait failed on a loaded release stand. var time = new FakeTimeProvider(); var logger = new ErrorSignalLogger(); var processor = new DebounceProcessor( failingNext, e => e.In.Headers.TryGetValue("key", out var v) ? v?.ToString() ?? "" : "", TimeSpan.FromMilliseconds(50), logger, time); var exchange = Exchange.Create(new Message("data"), null); exchange.In.Headers["key"] = "k1"; await processor.Process(exchange); time.Advance(TimeSpan.FromMilliseconds(50)); var logged = await logger.Error.Task.WaitAsync(TimeSpan.FromSeconds(10)); logged.Should().BeSameAs(expected); capturedExchange.Should().NotBeNull(); capturedExchange!.Exception.Should().BeSameAs(expected); await processor.DisposeAsync(); } /// A logger that completes with the exception of the first error it is given. private sealed class ErrorSignalLogger : ILogger { public TaskCompletionSource Error { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); 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.Error) Error.TrySetResult(exception); } } [Fact] public async Task Debounce_FlushAsync_DownstreamThrows_SetsExchangeException() { var expected = new InvalidOperationException("flush-boom"); IExchange? capturedExchange = null; var failingNext = new DelegateProcessor(ex => { capturedExchange = ex; throw expected; }); var logger = Substitute.For(); var processor = new DebounceProcessor( failingNext, e => e.In.Headers.TryGetValue("key", out var v) ? v?.ToString() ?? "" : "", TimeSpan.FromHours(1), // Long quiet period — won't fire by itself logger); var exchange = Exchange.Create(new Message("data"), null); exchange.In.Headers["key"] = "k1"; await processor.Process(exchange); // Force flush instead of waiting for timer await processor.FlushAsync(); capturedExchange.Should().NotBeNull(); capturedExchange!.Exception.Should().BeSameAs(expected); logger.ReceivedCalls().Should().NotBeEmpty(); processor.Dispose(); } // ══════════════════════════════════════════════════════════════ // DynamicRouterProcessor — thread safety under concurrent access // ══════════════════════════════════════════════════════════════ [Fact] public async Task DynamicRouter_ConcurrentAccess_NoCorruption() { var producer = Substitute.For(); var endpoint = Substitute.For(); endpoint.CreateProducer().Returns(_ => Substitute.For()); var context = Substitute.For(); context.GetEndpoint(Arg.Any()).Returns(endpoint); var exceptions = new ConcurrentBag(); // 10 concurrent tasks each routing to different URIs var tasks = Enumerable.Range(0, 10).Select(i => Task.Run(async () => { try { var router = new DynamicRouterProcessor(context, ex => { var body = ex.In.Body?.ToString(); return body == "done" ? null : $"direct://target-{i}"; }); var exchange = new Exchange(new Message("go")); // After first hop, mark as done so it stops var hop = 0; var drRouter = new DynamicRouterProcessor(context, _ => { hop++; return hop <= 1 ? $"direct://t{i}" : null; }); await drRouter.Process(new Exchange(new Message("data"))); } catch (Exception ex) { exceptions.Add(ex); } })); await Task.WhenAll(tasks); exceptions.Should().BeEmpty("concurrent access should not cause corruption"); } // ══════════════════════════════════════════════════════════════ // DynamicRouterProcessor — DisposeAsync stops cached producers // ══════════════════════════════════════════════════════════════ [Fact] public async Task DynamicRouter_DisposeAsync_StopsAllProducers() { var producerA = Substitute.For(); var producerB = Substitute.For(); var endpointA = Substitute.For(); endpointA.CreateProducer().Returns(producerA); var endpointB = Substitute.For(); endpointB.CreateProducer().Returns(producerB); var context = Substitute.For(); context.GetEndpoint("direct://a").Returns(endpointA); context.GetEndpoint("direct://b").Returns(endpointB); var hops = new Queue(["direct://a", "direct://b", null]); var router = new DynamicRouterProcessor(context, _ => hops.Dequeue()); await router.Process(new Exchange(new Message("data"))); await router.DisposeAsync(); await producerA.Received(1).Stop(Arg.Any()); await producerB.Received(1).Stop(Arg.Any()); } // ══════════════════════════════════════════════════════════════ // RecipientListProcessor — DisposeAsync stops cached producers // ══════════════════════════════════════════════════════════════ [Fact] public async Task RecipientList_DisposeAsync_StopsAllProducers() { var producerA = Substitute.For(); var producerB = Substitute.For(); var endpointA = Substitute.For(); endpointA.CreateProducer().Returns(producerA); var endpointB = Substitute.For(); endpointB.CreateProducer().Returns(producerB); var context = Substitute.For(); context.GetEndpoint("seda://a").Returns(endpointA); context.GetEndpoint("seda://b").Returns(endpointB); var processor = new RecipientListProcessor( context, _ => new[] { "seda://a", "seda://b" }); await processor.Process(new Exchange(new Message("data"))); await processor.DisposeAsync(); await producerA.Received(1).Stop(Arg.Any()); await producerB.Received(1).Stop(Arg.Any()); } [Fact] public async Task RecipientList_DisposeAsync_IdempotentAfterDispose() { var producer = Substitute.For(); var endpoint = Substitute.For(); endpoint.CreateProducer().Returns(producer); var context = Substitute.For(); context.GetEndpoint("seda://x").Returns(endpoint); var processor = new RecipientListProcessor(context, _ => new[] { "seda://x" }); await processor.Process(new Exchange(new Message("data"))); await processor.DisposeAsync(); await processor.DisposeAsync(); // Second call should be safe await producer.Received(1).Stop(Arg.Any()); } } Path: redb-route/tests/redb.Route.Tests/Processors/FilterProcessorTests.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/Processors/FilterProcessorTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Processors; namespace redb.Route.Tests.Processors; /// Tests for . public class FilterProcessorTests { /// When predicate is true, next processor executes. [Fact] public async Task Process_PredicateTrue_ExecutesNext() { var executed = false; var next = new DelegateProcessor(_ => executed = true); var filter = new FilterProcessor(_ => true, next); await filter.Process(new Exchange(new Message("data"))); executed.Should().BeTrue(); } /// When predicate is false, next processor is skipped. [Fact] public async Task Process_PredicateFalse_SkipsNext() { var executed = false; var next = new DelegateProcessor(_ => executed = true); var filter = new FilterProcessor(_ => false, next); await filter.Process(new Exchange(new Message("data"))); executed.Should().BeFalse(); } /// Predicate receives the current exchange. [Fact] public async Task Process_PredicateReceivesExchange() { var filter = new FilterProcessor( ex => ex.In.Body is string s && s.StartsWith("ok"), new DelegateProcessor(ex => ex.In.Body = "passed")); var exchange = new Exchange(new Message("ok-data")); await filter.Process(exchange); exchange.In.Body.Should().Be("passed"); } /// Predicate can inspect headers. [Fact] public async Task Process_FilterByHeader() { var executed = false; var filter = new FilterProcessor( ex => ex.In.GetHeader("type") == "important", new DelegateProcessor(_ => executed = true)); var msg = new Message("body"); msg.Headers["type"] = "important"; await filter.Process(new Exchange(msg)); executed.Should().BeTrue(); } /// Null predicate throws. [Fact] public void Constructor_NullPredicate_Throws() { // The cast only picks the overload: both the predicate and the delegate constructors reject null. var act = () => new FilterProcessor((redb.Route.Abstractions.IPredicate)null!, new DelegateProcessor(_ => { })); act.Should().Throw(); } /// Null next processor throws. [Fact] public void Constructor_NullNext_Throws() { var act = () => new FilterProcessor(_ => true, null!); act.Should().Throw(); } // ────────────────── DSL compilation ────────────────── // These tests validate end-to-end behaviour of the .Filter(...) DSL when compiled // by OldRouteCompiler and executed through PipelineProcessor. They should both PASS // once Phase 1 ships (CompileFilter wired through FilterProcessor + scope form). /// T0.1a — Filter with passing predicate must allow downstream steps to run. [Fact] public async Task RouteDsl_Filter_PassThrough_NextStepRuns() { await using var context = new RouteContext(); var received = new List(); context.AddRoutes(r => { r.From("direct://flt-pass") .Filter(_ => true) .Process(e => received.Add(e.In.Body)); }); await context.Start(); var producer = context.GetEndpoint("direct://flt-pass").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("payload"))); received.Should().ContainSingle().Which.Should().Be("payload"); } /// /// Scope-form Filter(p, body): body runs only when predicate is true, /// subsequent steps run for ALL exchanges regardless of predicate. /// [Fact] public async Task RouteDsl_FilterScope_BodyConditional_TailUnconditional() { await using var context = new RouteContext(); var inBody = new List(); var afterBody = new List(); context.AddRoutes(r => { r.From("direct://flt-scope") .Filter(e => (int)e.In.Body! % 2 == 0, b => b .Process(e => inBody.Add((int)e.In.Body!))) .Process(e => afterBody.Add((int)e.In.Body!)); }); await context.Start(); var producer = context.GetEndpoint("direct://flt-scope").CreateProducer(); await producer.Start(); foreach (var i in new[] { 1, 2, 3, 4 }) await producer.Process(new Exchange(new Message(i))); inBody.Should().Equal(2, 4); afterBody.Should().Equal(1, 2, 3, 4); } } Path: redb-route/tests/redb.Route.Tests/Processors/IdempotentConsumerIntegrationTests.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/Processors/IdempotentConsumerIntegrationTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Components; using redb.Route.Core; using redb.Route.Processors; namespace redb.Route.Tests.Processors; /// /// Integration tests for IdempotentConsumer within route definitions. /// public class IdempotentConsumerIntegrationTests : IAsyncLifetime { private readonly RouteContext _context = new(); public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { await _context.DisposeAsync(); GC.SuppressFinalize(this); } [Fact] public async Task IdempotentConsumer_InRoute_SkipsDuplicate() { var received = new List(); var repo = new InMemoryIdempotentRepository(); _context.AddRoutes(r => { r.From("direct://dedup") .IdempotentConsumer(e => e.In.Headers["MessageId"]?.ToString()!, repo) .Process(e => received.Add(e.In.Body)); }); await _context.Start(); var producer = _context.GetEndpoint("direct://dedup").CreateProducer(); await producer.Start(); var msg1 = new Message { Body = "first" }; msg1.Headers["MessageId"] = "id-1"; await producer.Process(new Exchange(msg1)); var msg2 = new Message { Body = "duplicate" }; msg2.Headers["MessageId"] = "id-1"; // same key await producer.Process(new Exchange(msg2)); var msg3 = new Message { Body = "third" }; msg3.Headers["MessageId"] = "id-2"; // different key await producer.Process(new Exchange(msg3)); received.Should().HaveCount(2); received[0].Should().Be("first"); received[1].Should().Be("third"); } [Fact] public async Task IdempotentConsumer_WithSkipFalse_PropagatesDuplicate() { var received = new List(); var duplicateFlags = new List(); var repo = new InMemoryIdempotentRepository(); _context.AddRoutes(r => { r.From("direct://noskip") .IdempotentConsumer( e => e.In.Headers["MessageId"]?.ToString()!, repo, skipDuplicate: false) .Process(e => { received.Add(e.In.Body); duplicateFlags.Add( e.Properties.TryGetValue("CamelDuplicateMessage", out var val) && val is true); }); }); await _context.Start(); var producer = _context.GetEndpoint("direct://noskip").CreateProducer(); await producer.Start(); var msg1 = new Message { Body = "original" }; msg1.Headers["MessageId"] = "ns-1"; await producer.Process(new Exchange(msg1)); var msg2 = new Message { Body = "duplicate" }; msg2.Headers["MessageId"] = "ns-1"; await producer.Process(new Exchange(msg2)); received.Should().HaveCount(2); duplicateFlags[0].Should().BeFalse(); // first message is not duplicate duplicateFlags[1].Should().BeTrue(); // second message is duplicate } [Fact] public async Task IdempotentConsumer_InRoute_WithMockEndpoint() { var repo = new InMemoryIdempotentRepository(); _context.AddRoutes(r => { r.From("direct://mock-dedup") .IdempotentConsumer(e => e.In.Body?.ToString()!, repo) .To("mock://output"); }); await _context.Start(); var mockEndpoint = (MockEndpoint)_context.GetEndpoint("mock://output"); var producer = _context.GetEndpoint("direct://mock-dedup").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message { Body = "unique-1" })); await producer.Process(new Exchange(new Message { Body = "unique-2" })); await producer.Process(new Exchange(new Message { Body = "unique-1" })); // duplicate await producer.Process(new Exchange(new Message { Body = "unique-3" })); mockEndpoint.ReceivedCount.Should().Be(3); // unique-1, unique-2, unique-3 } } Path: redb-route/tests/redb.Route.Tests/Processors/IdempotentConsumerTests.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/Processors/IdempotentConsumerTests.cs ---- using AwesomeAssertions; using NSubstitute; using redb.Route.Abstractions; using redb.Route.Components; using redb.Route.Core; using redb.Route.Processors; namespace redb.Route.Tests.Processors; /// /// Tests for IdempotentConsumerProcessor and InMemoryIdempotentRepository. /// public class IdempotentConsumerTests { // ── InMemoryIdempotentRepository ── [Fact] public async Task Repository_Add_ReturnsTrue_ForNewKey() { var repo = new InMemoryIdempotentRepository(); var result = await repo.Add("key-1"); result.Should().BeTrue(); } [Fact] public async Task Repository_Add_ReturnsFalse_ForDuplicateKey() { var repo = new InMemoryIdempotentRepository(); await repo.Add("key-1"); var result = await repo.Add("key-1"); result.Should().BeFalse(); } [Fact] public async Task Repository_Contains_ReturnsTrueAfterAdd() { var repo = new InMemoryIdempotentRepository(); await repo.Add("key-1"); (await repo.Contains("key-1")).Should().BeTrue(); } [Fact] public async Task Repository_Contains_ReturnsFalseForMissing() { var repo = new InMemoryIdempotentRepository(); (await repo.Contains("missing")).Should().BeFalse(); } [Fact] public async Task Repository_Remove_AllowsReAdd() { var repo = new InMemoryIdempotentRepository(); await repo.Add("key-1"); await repo.Remove("key-1"); var result = await repo.Add("key-1"); result.Should().BeTrue(); } [Fact] public async Task Repository_Clear_RemovesAllKeys() { var repo = new InMemoryIdempotentRepository(); await repo.Add("a"); await repo.Add("b"); await repo.Add("c"); repo.Count.Should().Be(3); await repo.Clear(); repo.Count.Should().Be(0); } [Fact] public async Task Repository_Confirm_IsNoOp() { var repo = new InMemoryIdempotentRepository(); await repo.Add("key-1"); await repo.Confirm("key-1"); (await repo.Contains("key-1")).Should().BeTrue(); } [Fact] public async Task Repository_Add_ThrowsOnNull() { var repo = new InMemoryIdempotentRepository(); var act = async () => await repo.Add(null!); await act.Should().ThrowAsync(); } // ── TTL Eviction ── [Fact] public async Task Repository_WithTtl_ContainsReturnsFalseAfterExpiry() { var repo = new InMemoryIdempotentRepository(ttl: TimeSpan.FromMilliseconds(50)); await repo.Add("key-ttl"); (await repo.Contains("key-ttl")).Should().BeTrue(); await Task.Delay(80); (await repo.Contains("key-ttl")).Should().BeFalse(); } [Fact] public async Task Repository_WithTtl_ExpiredKeyEvictedOnAdd() { var repo = new InMemoryIdempotentRepository(ttl: TimeSpan.FromMilliseconds(50)); await repo.Add("old-key"); repo.Count.Should().Be(1); await Task.Delay(80); await repo.Add("new-key"); // old-key should have been evicted during the Add call (await repo.Contains("old-key")).Should().BeFalse(); (await repo.Contains("new-key")).Should().BeTrue(); } [Fact] public async Task Repository_WithTtl_NonExpiredKeyStillValid() { var repo = new InMemoryIdempotentRepository(ttl: TimeSpan.FromSeconds(10)); await repo.Add("fresh-key"); (await repo.Contains("fresh-key")).Should().BeTrue(); var result = await repo.Add("fresh-key"); result.Should().BeFalse(); // Still there, not expired } [Fact] public async Task Repository_WithTtl_ExpiredKeyAllowsReAdd() { var repo = new InMemoryIdempotentRepository(ttl: TimeSpan.FromMilliseconds(50)); await repo.Add("re-key"); await Task.Delay(80); var result = await repo.Add("re-key"); result.Should().BeTrue(); // Expired, so re-add succeeds } [Fact] public async Task Repository_NullTtl_KeysKeptIndefinitely() { var repo = new InMemoryIdempotentRepository(); // ttl = null (default) await repo.Add("forever"); (await repo.Contains("forever")).Should().BeTrue(); repo.Count.Should().Be(1); } // ── IdempotentConsumerProcessor ── [Fact] public void Ctor_ThrowsOnNullInner() { var repo = new InMemoryIdempotentRepository(); var act = () => new IdempotentConsumerProcessor(null!, repo, e => "key"); act.Should().Throw(); } [Fact] public void Ctor_ThrowsOnNullRepository() { var inner = Substitute.For(); var act = () => new IdempotentConsumerProcessor(inner, null!, e => "key"); act.Should().Throw(); } [Fact] public void Ctor_ThrowsOnNullKeyExtractor() { var inner = Substitute.For(); var repo = new InMemoryIdempotentRepository(); var act = () => new IdempotentConsumerProcessor(inner, repo, null!); act.Should().Throw(); } [Fact] public async Task Process_NewMessage_PassesToInner() { var inner = Substitute.For(); var repo = new InMemoryIdempotentRepository(); var processor = new IdempotentConsumerProcessor( inner, repo, e => e.In.Headers["MessageId"]?.ToString()!); var msg = new Message { Body = "payload" }; msg.Headers["MessageId"] = "unique-1"; var exchange = new Exchange(msg); await processor.Process(exchange); await inner.Received(1).Process(exchange, Arg.Any()); } [Fact] public async Task Process_DuplicateMessage_SkipDuplicate_DoesNotInvokeInner() { var inner = Substitute.For(); var repo = new InMemoryIdempotentRepository(); var processor = new IdempotentConsumerProcessor( inner, repo, e => e.In.Headers["MessageId"]?.ToString()!, skipDuplicate: true); var msg1 = new Message { Body = "first" }; msg1.Headers["MessageId"] = "dup-1"; var exchange1 = new Exchange(msg1); await processor.Process(exchange1); var msg2 = new Message { Body = "second" }; msg2.Headers["MessageId"] = "dup-1"; // same key var exchange2 = new Exchange(msg2); await processor.Process(exchange2); // Inner called only once (for the first message) await inner.Received(1).Process(Arg.Any(), Arg.Any()); // Second exchange must be flagged as duplicate. // IsStopped is intentionally NOT set: tail-consuming wiring in OldRouteCompiler // owns the tail, so flagging the exchange would only pollute downstream reuse // (see Aggregate seed-reuse regression in AggregatorProcessor). exchange2.IsStopped.Should().BeFalse(); exchange2.Properties[IdempotentConsumerProcessor.DuplicatePropertyKey].Should().Be(true); } [Fact] public async Task Process_DuplicateMessage_NoSkip_PropagatesWithFlag() { var inner = Substitute.For(); var repo = new InMemoryIdempotentRepository(); var processor = new IdempotentConsumerProcessor( inner, repo, e => e.In.Headers["MessageId"]?.ToString()!, skipDuplicate: false); var msg1 = new Message { Body = "first" }; msg1.Headers["MessageId"] = "dup-2"; var exchange1 = new Exchange(msg1); await processor.Process(exchange1); var msg2 = new Message { Body = "duplicate" }; msg2.Headers["MessageId"] = "dup-2"; // same key var exchange2 = new Exchange(msg2); await processor.Process(exchange2); // Inner called twice (both messages processed) await inner.Received(2).Process(Arg.Any(), Arg.Any()); // Second exchange should have the duplicate flag but NOT be stopped exchange2.IsStopped.Should().BeFalse(); exchange2.Properties[IdempotentConsumerProcessor.DuplicatePropertyKey].Should().Be(true); } [Fact] public async Task Process_NullKey_ProcessesWithoutDedup() { var inner = Substitute.For(); var repo = new InMemoryIdempotentRepository(); var processor = new IdempotentConsumerProcessor( inner, repo, _ => null!, skipDuplicate: true); var exchange = new Exchange(new Message { Body = "test" }); await processor.Process(exchange); await inner.Received(1).Process(exchange, Arg.Any()); repo.Count.Should().Be(0); } [Fact] public async Task Process_EmptyKey_ProcessesWithoutDedup() { var inner = Substitute.For(); var repo = new InMemoryIdempotentRepository(); var processor = new IdempotentConsumerProcessor( inner, repo, _ => "", skipDuplicate: true); var exchange = new Exchange(new Message { Body = "test" }); await processor.Process(exchange); await inner.Received(1).Process(exchange, Arg.Any()); } [Fact] public async Task Process_OnFailure_RemovesKeyForRetry() { var inner = Substitute.For(); inner.Process(Arg.Any(), Arg.Any()) .Returns(Task.FromException(new InvalidOperationException("fail"))); var repo = new InMemoryIdempotentRepository(); var processor = new IdempotentConsumerProcessor( inner, repo, e => "retry-key"); var exchange = new Exchange(new Message { Body = "test" }); var act = async () => await processor.Process(exchange); await act.Should().ThrowAsync(); // Outside a route the exchange's unit of work ends when the exchange is released; the failure it carries // decides the key's fate there. exchange.Exception = new InvalidOperationException("fail"); await exchange.DisposeAsync(); // The key should have been removed to allow retry (await repo.Contains("retry-key")).Should().BeFalse(); } [Fact] public async Task Process_OnFailure_RemoveThrows_PreservesOriginalException() { var inner = Substitute.For(); inner.Process(Arg.Any(), Arg.Any()) .Returns(Task.FromException(new InvalidOperationException("original"))); var repo = Substitute.For(); repo.Add(Arg.Any(), Arg.Any()).Returns(true); repo.Remove(Arg.Any(), Arg.Any()) .Returns(Task.FromException(new Exception("remove failed"))); var processor = new IdempotentConsumerProcessor(inner, repo, e => "k"); var exchange = new Exchange(new Message { Body = "x" }); // The processing failure must survive — a Remove that itself fails must not replace it. var ex = await processor.Invoking(p => p.Process(exchange)) .Should().ThrowAsync(); ex.Which.Message.Should().Be("original"); // The removal runs when the unit of work ends; its failure is logged, not thrown at whoever releases the exchange. exchange.Exception = ex.Which; await exchange.Invoking(e => e.DisposeAsync().AsTask()).Should().NotThrowAsync(); await repo.Received(1).Remove("k", Arg.Any()); } [Fact] public async Task Process_OnFailure_RepositoryInTheTransaction_DoesNotRemoveKey() { var inner = Substitute.For(); inner.Process(Arg.Any(), Arg.Any()) .Returns(Task.FromException(new InvalidOperationException("fail"))); var repo = Substitute.For(); repo.Add(Arg.Any(), Arg.Any()).Returns(true); repo.JoinsAmbientTransaction.Returns(true); var processor = new IdempotentConsumerProcessor(inner, repo, e => "k"); var exchange = new Exchange(new Message { Body = "x" }); var act = async () => { using var scope = new System.Transactions.TransactionScope( System.Transactions.TransactionScopeAsyncFlowOption.Enabled); await processor.Process(exchange); scope.Complete(); }; await act.Should().ThrowAsync(); exchange.Exception = new InvalidOperationException("fail"); await exchange.DisposeAsync(); // The key is part of the transaction: the rollback removed it. An explicit Remove afterwards could delete the // same key another node has claimed since, so it must NOT be called. await repo.DidNotReceive().Remove(Arg.Any(), Arg.Any()); } [Fact] public async Task Process_OnSuccess_ConfirmsKey() { var inner = Substitute.For(); var repo = new InMemoryIdempotentRepository(); var processor = new IdempotentConsumerProcessor( inner, repo, e => "confirm-key"); var exchange = new Exchange(new Message { Body = "test" }); await processor.Process(exchange); // Key should remain (confirmed) (await repo.Contains("confirm-key")).Should().BeTrue(); } [Fact] public async Task Process_MultipleDistinctKeys_AllProcessed() { var processedBodies = new List(); var inner = Substitute.For(); inner.Process(Arg.Any(), Arg.Any()) .Returns(ci => { processedBodies.Add(ci.Arg().In.Body); return Task.CompletedTask; }); var repo = new InMemoryIdempotentRepository(); var processor = new IdempotentConsumerProcessor( inner, repo, e => e.In.Body?.ToString()!); await processor.Process(new Exchange(new Message { Body = "a" })); await processor.Process(new Exchange(new Message { Body = "b" })); await processor.Process(new Exchange(new Message { Body = "c" })); processedBodies.Should().HaveCount(3); processedBodies.Should().ContainInOrder("a", "b", "c"); } [Fact] public void DuplicatePropertyKey_HasCorrectValue() { IdempotentConsumerProcessor.DuplicatePropertyKey.Should().Be("CamelDuplicateMessage"); } /// /// Scope-form IdempotentConsumer(..., body): body runs only for first-seen keys; /// subsequent route steps run for ALL exchanges including duplicates. /// [Fact] public async Task RouteDsl_IdempotentConsumerScope_BodyOnFirstSeen_TailAlways() { await using var context = new RouteContext(); var repo = new InMemoryIdempotentRepository(); var inBody = new List(); var afterBody = new List(); context.AddRoutes(r => { r.From("direct://ic-scope") .IdempotentConsumer(e => (string)e.In.Body!, repo, b => b .Process(e => inBody.Add((string)e.In.Body!))) .Process(e => afterBody.Add((string)e.In.Body!)); }); await context.Start(); var producer = context.GetEndpoint("direct://ic-scope").CreateProducer(); await producer.Start(); foreach (var k in new[] { "a", "b", "a", "c", "b" }) await producer.Process(new Exchange(new Message(k))); inBody.Should().Equal("a", "b", "c"); afterBody.Should().Equal("a", "b", "a", "c", "b"); } } Path: redb-route/tests/redb.Route.Tests/Processors/InflightTrackingProcessorTests.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/Processors/InflightTrackingProcessorTests.cs ---- using AwesomeAssertions; using NSubstitute; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Processors; namespace redb.Route.Tests.Processors; public class InflightTrackingProcessorTests { private readonly IInflightRepository _repo = Substitute.For(); private IProcessor MakeProcessor(IProcessor? inner = null) => new InflightTrackingProcessor(inner ?? new DelegateProcessor(_ => { }), _repo, "test-route", "kafka:orders"); [Fact] public async Task Process_RegistersBeforeInner_UnregistersAfter() { var callOrder = new List(); _repo.When(r => r.Register(Arg.Any())) .Do(_ => callOrder.Add("register")); _repo.When(r => r.Unregister(Arg.Any())) .Do(_ => callOrder.Add("unregister")); var inner = new DelegateProcessor(_ => callOrder.Add("inner")); var processor = new InflightTrackingProcessor(inner, _repo, "test-route", "kafka:orders"); await processor.Process(new Exchange(new Message("data"))); callOrder.Should().Equal("register", "inner", "unregister"); } [Fact] public async Task Process_UnregistersOnException() { var inner = new DelegateProcessor(_ => throw new InvalidOperationException("boom")); var processor = new InflightTrackingProcessor(inner, _repo, "test-route"); var act = () => processor.Process(new Exchange(new Message("data"))); await act.Should().ThrowAsync(); _repo.Received(1).Register(Arg.Any()); _repo.Received(1).Unregister(Arg.Any()); } [Fact] public async Task Process_RegistersCorrectFields() { InflightExchange? captured = null; _repo.When(r => r.Register(Arg.Any())) .Do(ci => captured = ci.Arg()); var exchange = new Exchange(new Message("data")); var processor = new InflightTrackingProcessor( new DelegateProcessor(_ => { }), _repo, "my-route", "kafka:orders"); await processor.Process(exchange); captured.Should().NotBeNull(); captured!.ExchangeId.Should().Be(exchange.ExchangeId); captured.RouteId.Should().Be("my-route"); captured.FromEndpoint.Should().Be("kafka:orders"); } [Fact] public async Task Process_UnregistersCorrectExchangeId() { string? unregisteredId = null; _repo.When(r => r.Unregister(Arg.Any())) .Do(ci => unregisteredId = ci.Arg()); var exchange = new Exchange(new Message("data")); var processor = MakeProcessor(); await processor.Process(exchange); unregisteredId.Should().Be(exchange.ExchangeId); } [Fact] public async Task Process_PropagatesCancellationToken() { using var cts = new CancellationTokenSource(); CancellationToken receivedToken = default; var inner = new DelegateProcessor((e, ct) => { receivedToken = ct; return Task.CompletedTask; }); var processor = new InflightTrackingProcessor(inner, _repo, "route"); await processor.Process(new Exchange(new Message("data")), cts.Token); receivedToken.Should().Be(cts.Token); } } Path: redb-route/tests/redb.Route.Tests/Processors/KeyedThrottleDynamicLimitTests.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/Processors/KeyedThrottleDynamicLimitTests.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Processors; using redb.Route.TestKit; namespace redb.Route.Tests.Processors; /// Keyed throttle with the limit read from the message: key and limit both come from the exchange. public class KeyedThrottleDynamicLimitTests { private static readonly TimeSpan Wait = TimeSpan.FromSeconds(2); private static readonly TimeSpan Window = TimeSpan.FromSeconds(10); private static async Task SendBurst(IRouteContext ctx, string uri, int goldCount, int stdCount) { for (var i = 0; i < goldCount; i++) await ctx.SendBodyAndHeader(uri, $"g{i}", "tier", "gold"); for (var i = 0; i < stdCount; i++) await ctx.SendBodyAndHeader(uri, $"s{i}", "tier", "std"); } [Fact] public async Task DynamicLimit_PerKey_GoldGetsFive_StdGetsTwo_InOneWindow() { await using var ctx = new RouteContext().AddRoutes(b => b .From("direct://kt") .Throttle(e => (string)e.In.Headers["tier"]!, e => Equals(e.In.Headers["tier"], "gold") ? 5 : 2, Window) .RejectOnOverflow() .To("mock://kt-out") .EndKeyedThrottle()); await ctx.Start(); await SendBurst(ctx, "direct://kt", goldCount: 6, stdCount: 6); var mock = ctx.Mock("mock://kt-out"); await mock.ExpectMessageCount(7).AssertIsSatisfiedAsync(Wait); mock.ReceivedExchanges.Count(e => Equals(e.In.Headers["tier"], "gold")).Should().Be(5); mock.ReceivedExchanges.Count(e => Equals(e.In.Headers["tier"], "std")).Should().Be(2); } [Fact] public async Task FixedLimit_CannotExpressPerKeyLimits_BothKeysGetTwo() { // The pre-existing int overload: same limit for every key — the asymmetry the dynamic form removes. await using var ctx = new RouteContext().AddRoutes(b => b .From("direct://kt-fixed") .Throttle(e => (string)e.In.Headers["tier"]!, 2, Window) .RejectOnOverflow() .To("mock://kt-fixed-out") .EndKeyedThrottle()); await ctx.Start(); await SendBurst(ctx, "direct://kt-fixed", goldCount: 6, stdCount: 6); await ctx.Mock("mock://kt-fixed-out").ExpectMessageCount(4).AssertIsSatisfiedAsync(Wait); } [Fact] public async Task StringForm_KeyAndLimitExpressions() { await using var ctx = new RouteContext().AddRoutes(b => b .From("direct://kt-expr") .Throttle("header.tier", "header.tier == 'gold' ? 5 : 2", Window) .RejectOnOverflow() .To("mock://kt-expr-out") .EndKeyedThrottle()); await ctx.Start(); await SendBurst(ctx, "direct://kt-expr", goldCount: 6, stdCount: 6); var mock = ctx.Mock("mock://kt-expr-out"); await mock.ExpectMessageCount(7).AssertIsSatisfiedAsync(Wait); mock.ReceivedExchanges.Count(e => Equals(e.In.Headers["tier"], "gold")).Should().Be(5); } [Fact] public async Task StringForm_MalformedLimitExpression_FailsAtDslTime() { var act = () => new RouteContext().AddRoutes(b => b .From("direct://kt-bad").Throttle("header.tier", "max(header.a, ", Window).EndKeyedThrottle()).Start(); await act.Should().ThrowAsync(); } [Fact] public async Task RejectedExchanges_Carry429_AndRetryAfter() { await using var ctx = new RouteContext().AddRoutes(b => b .From("direct://kt-429") .Throttle(e => "one", e => 1, Window).RejectOnOverflow().To("mock://kt-429-out").EndKeyedThrottle() .To("mock://kt-429-tail")); await ctx.Start(); using var template = new ProducerTemplate(ctx); template.Start(); var first = Exchange.Create(new Message("first"), null); var second = Exchange.Create(new Message("second"), null); await template.SendAsync("direct://kt-429", first); await template.SendAsync("direct://kt-429", second); ctx.Mock("mock://kt-429-out").ReceivedCount.Should().Be(1); ctx.Mock("mock://kt-429-tail").ReceivedCount.Should().Be(1, "a rejected exchange is stopped, it does not continue down the route"); second.IsStopped.Should().BeTrue(); // The pipeline hands Out over to In between steps, so the 429 reply is read from whichever holds it. var reply = second.Out ?? second.In; reply.Headers["redbHttp.ResponseCode"].Should().Be(429); reply.Headers["Retry-After"].Should().Be("10"); } [Fact] public async Task WaitMode_DynamicLimit_EventuallyPassesEverything() { await using var ctx = new RouteContext().AddRoutes(b => b .From("direct://kt-wait") .Throttle(e => (string)e.In.Headers["tier"]!, e => 2, TimeSpan.FromMilliseconds(150)) .To("mock://kt-wait-out") .EndKeyedThrottle()); await ctx.Start(); var sends = Enumerable.Range(0, 5).Select(i => ctx.SendBodyAndHeader("direct://kt-wait", i, "tier", "std")).ToArray(); await Task.WhenAll(sends); await ctx.Mock("mock://kt-wait-out").ExpectMessageCount(5).AssertIsSatisfiedAsync(Wait); } [Fact] public void Processor_EvictsIdleGates() { var next = new DelegateProcessor(_ => { }); using var throttle = new KeyedThrottleProcessor(next, e => (string)e.In.Body!, _ => 1, TimeSpan.FromMilliseconds(20)); throttle.Process(Exchange.Create(new Message("k1"), null)).GetAwaiter().GetResult(); throttle.ActiveKeyCount.Should().Be(1); Thread.Sleep(120); // > 2 × period and the slot is released after one period throttle.Process(Exchange.Create(new Message("k2"), null)).GetAwaiter().GetResult(); throttle.ActiveKeyCount.Should().Be(1, "k1 was idle for two periods and got evicted when k2 arrived"); } } Path: redb-route/tests/redb.Route.Tests/Processors/KeyedThrottleIntegrationTests.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/Processors/KeyedThrottleIntegrationTests.cs ---- using System.Diagnostics; using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Definitions; namespace redb.Route.Tests.Processors; /// /// Integration tests for Keyed Throttle using full route compilation and pipeline execution. /// [Trait("Category", "Integration")] public class KeyedThrottleIntegrationTests { private readonly RouteContext _context = new(); private static IExchange CreateExchange(object? body = null, string? key = null) { var ex = Exchange.Create(new Message(body), null); if (key != null) ex.In.Headers["ThrottleKey"] = key; return ex; } private static Func KeyFromHeader => e => e.In.Headers.TryGetValue("ThrottleKey", out var v) ? v?.ToString() ?? "" : ""; // ══════════════════════════════════════════════════════════════ // Basic compiled pipeline // ══════════════════════════════════════════════════════════════ [Fact] public async Task CompiledPipeline_SingleKey_PassesUnderLimit() { var def = new RouteDefinition(); def.From("direct://kt"); def.Throttle(KeyFromHeader, 5, TimeSpan.FromSeconds(5)) .Transform(e => $"ok:{e.In.Body}") .End(); var pipeline = def.CreateProcessor(_context); var ex = CreateExchange("hello", "A"); await pipeline.Process(ex); ex.In.Body.Should().Be("ok:hello"); } [Fact] public async Task CompiledPipeline_DifferentKeys_IndependentRates() { var def = new RouteDefinition(); def.From("direct://kt"); def.Throttle(KeyFromHeader, 2, TimeSpan.FromSeconds(10)) .Transform(e => $"ok:{e.In.Body}") .End(); var pipeline = def.CreateProcessor(_context); // 2 messages per key should pass immediately var a1 = CreateExchange("a1", "A"); var a2 = CreateExchange("a2", "A"); var b1 = CreateExchange("b1", "B"); var b2 = CreateExchange("b2", "B"); await pipeline.Process(a1); await pipeline.Process(b1); await pipeline.Process(a2); await pipeline.Process(b2); a1.In.Body.Should().Be("ok:a1"); a2.In.Body.Should().Be("ok:a2"); b1.In.Body.Should().Be("ok:b1"); b2.In.Body.Should().Be("ok:b2"); } [Fact] public async Task CompiledPipeline_SameKey_ExceedLimit_IsThrottled() { var def = new RouteDefinition(); def.From("direct://kt"); def.Throttle(KeyFromHeader, 2, TimeSpan.FromMilliseconds(500)) .Process(e => { }) .End(); var pipeline = def.CreateProcessor(_context); // Fill the bucket await pipeline.Process(CreateExchange(1, "X")); await pipeline.Process(CreateExchange(2, "X")); // 3rd message must wait ~500ms var sw = Stopwatch.StartNew(); await pipeline.Process(CreateExchange(3, "X")); sw.Stop(); sw.ElapsedMilliseconds.Should().BeGreaterThanOrEqualTo(400); } // ══════════════════════════════════════════════════════════════ // Preserves exchange properties // ══════════════════════════════════════════════════════════════ [Fact] public async Task CompiledPipeline_PreservesHeadersAndProperties() { var def = new RouteDefinition(); def.From("direct://kt"); def.Throttle(KeyFromHeader, 10) .Process(e => { }) .End(); var pipeline = def.CreateProcessor(_context); var ex = CreateExchange("body", "K"); ex.In.Headers["Custom"] = "value"; ex.Properties["Prop1"] = 42; await pipeline.Process(ex); ex.In.Headers["Custom"].Should().Be("value"); ex.In.Headers["ThrottleKey"].Should().Be("K"); ex.Properties["Prop1"].Should().Be(42); ex.In.Body.Should().Be("body"); } // ══════════════════════════════════════════════════════════════ // Chaining with transform // ══════════════════════════════════════════════════════════════ [Fact] public async Task CompiledPipeline_ChainingWithTransform() { var def = new RouteDefinition(); def.From("direct://kt") .SetHeader("Step", "before") .Throttle(KeyFromHeader, 10) .Transform(e => $"throttled:{e.In.Body}") .End(); var pipeline = def.CreateProcessor(_context); var ex = CreateExchange("data", "K"); await pipeline.Process(ex); // SetHeader runs before throttle (non-wrapping), transform is in the tail ex.In.Headers["Step"].Should().Be("before"); ex.In.Body.Should().Be("throttled:data"); } // ══════════════════════════════════════════════════════════════ // Default period (1 second) // ══════════════════════════════════════════════════════════════ [Fact] public async Task CompiledPipeline_DefaultPeriod_Works() { var def = new RouteDefinition(); def.From("direct://kt"); def.Throttle(KeyFromHeader, 100) .Process(e => { }) .End(); var pipeline = def.CreateProcessor(_context); // 100 messages under limit should pass fast var sw = Stopwatch.StartNew(); for (int i = 0; i < 100; i++) await pipeline.Process(CreateExchange(i, "K")); sw.Stop(); sw.ElapsedMilliseconds.Should().BeLessThan(2000); } // ══════════════════════════════════════════════════════════════ // Concurrent keys // ══════════════════════════════════════════════════════════════ [Fact] public async Task CompiledPipeline_ConcurrentKeys_AllProcessed() { var count = 0; var def = new RouteDefinition(); def.From("direct://kt"); def.Throttle(KeyFromHeader, 20, TimeSpan.FromSeconds(5)) .Process(e => Interlocked.Increment(ref count)) .End(); var pipeline = def.CreateProcessor(_context); var tasks = Enumerable.Range(0, 40) .Select(i => pipeline.Process(CreateExchange(i, $"Key{i % 4}"))) .ToArray(); await Task.WhenAll(tasks); count.Should().Be(40); } } Path: redb-route/tests/redb.Route.Tests/Processors/KeyedThrottleTests.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/Processors/KeyedThrottleTests.cs ---- using System.Diagnostics; using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Definitions; using redb.Route.Processors; namespace redb.Route.Tests.Processors; /// /// Unit tests for KeyedThrottleProcessor, DSL, and step creation. /// public class KeyedThrottleTests { private static IExchange CreateExchange(object? body = null, string? key = null) { var ex = Exchange.Create(new Message(body), null); if (key != null) ex.In.Headers["ThrottleKey"] = key; return ex; } private static Func KeyFromHeader => e => e.In.Headers.TryGetValue("ThrottleKey", out var v) ? v?.ToString() ?? "" : ""; // ══════════════════════════════════════════════════════════════ // Constructor validation // ══════════════════════════════════════════════════════════════ [Fact] public void Constructor_NullNext_Throws() { var act = () => new KeyedThrottleProcessor(null!, KeyFromHeader, 5); act.Should().Throw().WithParameterName("next"); } [Fact] public void Constructor_NullKeyExtractor_Throws() { var next = new DelegateProcessor(_ => { }); var act = () => new KeyedThrottleProcessor(next, null!, 5); act.Should().Throw().WithParameterName("keyExtractor"); } [Fact] public void Constructor_ZeroMax_Throws() { var next = new DelegateProcessor(_ => { }); var act = () => new KeyedThrottleProcessor(next, KeyFromHeader, 0); act.Should().Throw().WithParameterName("maxPerPeriod"); } [Fact] public void Constructor_NegativeMax_Throws() { var next = new DelegateProcessor(_ => { }); var act = () => new KeyedThrottleProcessor(next, KeyFromHeader, -1); act.Should().Throw().WithParameterName("maxPerPeriod"); } // ══════════════════════════════════════════════════════════════ // Processor behavior // ══════════════════════════════════════════════════════════════ [Fact] public async Task SingleMessage_PassesThrough() { var processed = false; var next = new DelegateProcessor(_ => processed = true); using var throttle = new KeyedThrottleProcessor(next, KeyFromHeader, 10); await throttle.Process(CreateExchange("hello", "A")); processed.Should().BeTrue(); } [Fact] public async Task SameKey_UnderLimit_AllPass() { var count = 0; var next = new DelegateProcessor(_ => Interlocked.Increment(ref count)); using var throttle = new KeyedThrottleProcessor(next, KeyFromHeader, 5, TimeSpan.FromSeconds(2)); for (int i = 0; i < 5; i++) await throttle.Process(CreateExchange(i, "A")); count.Should().Be(5); } [Fact] public async Task DifferentKeys_IndependentLimits() { var countA = 0; var countB = 0; var next = new DelegateProcessor(ex => { var key = ex.In.Headers["ThrottleKey"]?.ToString(); if (key == "A") Interlocked.Increment(ref countA); else Interlocked.Increment(ref countB); }); // 2 per period per key, long period so no slot release using var throttle = new KeyedThrottleProcessor(next, KeyFromHeader, 2, TimeSpan.FromSeconds(10)); // Key A: 2 should pass immediately await throttle.Process(CreateExchange(1, "A")); await throttle.Process(CreateExchange(2, "A")); // Key B: 2 should also pass immediately (independent bucket) await throttle.Process(CreateExchange(3, "B")); await throttle.Process(CreateExchange(4, "B")); countA.Should().Be(2); countB.Should().Be(2); } [Fact] public async Task SameKey_ExceedLimit_Throttles() { var count = 0; var next = new DelegateProcessor(_ => Interlocked.Increment(ref count)); using var throttle = new KeyedThrottleProcessor(next, KeyFromHeader, 2, TimeSpan.FromMilliseconds(500)); var sw = Stopwatch.StartNew(); // Send 2 — fills the bucket await throttle.Process(CreateExchange(1, "X")); await throttle.Process(CreateExchange(2, "X")); var fast = sw.ElapsedMilliseconds; // 3rd must wait for slot release (~500ms) await throttle.Process(CreateExchange(3, "X")); sw.Stop(); count.Should().Be(3); sw.ElapsedMilliseconds.Should().BeGreaterThanOrEqualTo(400); } [Fact] public async Task ExceedOnOneKey_OtherKeyStillFast() { var count = 0; var next = new DelegateProcessor(_ => Interlocked.Increment(ref count)); using var throttle = new KeyedThrottleProcessor(next, KeyFromHeader, 1, TimeSpan.FromSeconds(10)); // Exhaust key A await throttle.Process(CreateExchange(1, "A")); // Key B should still pass immediately var sw = Stopwatch.StartNew(); await throttle.Process(CreateExchange(2, "B")); sw.Stop(); count.Should().Be(2); sw.ElapsedMilliseconds.Should().BeLessThan(200); } [Fact] public async Task PreservesExchangeBody() { object? captured = null; var next = new DelegateProcessor(ex => captured = ex.In.Body); using var throttle = new KeyedThrottleProcessor(next, KeyFromHeader, 10); await throttle.Process(CreateExchange("payload", "K")); captured.Should().Be("payload"); } [Fact] public async Task NullKey_TreatedAsEmptyString() { var count = 0; var next = new DelegateProcessor(_ => Interlocked.Increment(ref count)); using var throttle = new KeyedThrottleProcessor(next, _ => null!, 10); await throttle.Process(CreateExchange("a")); await throttle.Process(CreateExchange("b")); count.Should().Be(2); } [Fact] public async Task Cancellation_ThrowsOperationCanceled() { var next = new DelegateProcessor(_ => { }); using var throttle = new KeyedThrottleProcessor(next, KeyFromHeader, 1, TimeSpan.FromSeconds(10)); // Exhaust the single slot for key "Z" await throttle.Process(CreateExchange(1, "Z")); using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(50)); var act = () => throttle.Process(CreateExchange(2, "Z"), cts.Token); await act.Should().ThrowAsync(); } [Fact] public async Task ConcurrentAccess_ThreadSafe() { var count = 0; var next = new DelegateProcessor(_ => Interlocked.Increment(ref count)); using var throttle = new KeyedThrottleProcessor(next, KeyFromHeader, 50, TimeSpan.FromSeconds(5)); var tasks = Enumerable.Range(0, 50) .Select(i => throttle.Process(CreateExchange(i, "K"))) .ToArray(); await Task.WhenAll(tasks); count.Should().Be(50); } [Fact] public async Task ConcurrentAccess_MultipleKeys_ThreadSafe() { var count = 0; var next = new DelegateProcessor(_ => Interlocked.Increment(ref count)); using var throttle = new KeyedThrottleProcessor(next, KeyFromHeader, 20, TimeSpan.FromSeconds(5)); var tasks = Enumerable.Range(0, 60) .Select(i => throttle.Process(CreateExchange(i, $"Key{i % 3}"))) .ToArray(); await Task.WhenAll(tasks); count.Should().Be(60); } [Fact] public void Dispose_Idempotent() { var next = new DelegateProcessor(_ => { }); var throttle = new KeyedThrottleProcessor(next, KeyFromHeader, 10); throttle.Dispose(); var act = () => throttle.Dispose(); act.Should().NotThrow(); } // ══════════════════════════════════════════════════════════════ // DSL — step recording // ══════════════════════════════════════════════════════════════ [Fact] public void DSL_Throttle_Keyed_RecordsStep() { var def = new RouteDefinition(); Func key = e => "k"; def.Throttle(key, 10, TimeSpan.FromSeconds(2)); var node = def.Outputs.Should().ContainSingle().Which.Should().BeOfType().Subject; node.KeyExtractor.Should().BeSameAs(key); node.MaxPerPeriod.Should().Be(10); node.Period.Should().Be(TimeSpan.FromSeconds(2)); } [Fact] public void DSL_Throttle_Keyed_DefaultPeriod() { var def = new RouteDefinition(); Func key = e => "k"; def.Throttle(key, 5); var node = def.Outputs.Should().ContainSingle().Which.Should().BeOfType().Subject; node.Period.Should().BeNull(); } [Fact] public void DSL_Throttle_Keyed_NullKeyExtractor_Throws() { var def = new RouteDefinition(); var act = () => def.Throttle(null!, 5); act.Should().Throw().WithParameterName("keyExtractor"); } [Fact] public void DSL_Throttle_Keyed_ZeroMax_Throws() { var def = new RouteDefinition(); var act = () => def.Throttle(e => "k", 0); act.Should().Throw().WithParameterName("maxPerPeriod"); } [Fact] public void DSL_Throttle_Keyed_Chaining() { var def = new RouteDefinition(); var scope = def.Throttle(e => "k", 10); scope.To("direct:out"); var result = scope.EndKeyedThrottle(); result.Should().BeSameAs(def); def.Outputs.Should().ContainSingle().Which.Should().BeOfType() .Which.Outputs.Should().ContainSingle().Which.Should().BeOfType(); } } Path: redb-route/tests/redb.Route.Tests/Processors/LoadBalancerIntegrationTests.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/Processors/LoadBalancerIntegrationTests.cs ---- using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Components; using redb.Route.Core; using redb.Route.Processors; using redb.Route.Processors.LoadBalancer; namespace redb.Route.Tests.Processors; /// /// Integration tests for using real DirectComponent endpoints. /// Tests the full pipeline: strategy selection → ToProcessor → DirectEndpoint → DirectProducer → consumer. /// [Trait("Category", "Integration")] public class LoadBalancerIntegrationTests : IAsyncLifetime { private readonly RouteContext _context = new(); private readonly ConcurrentBag<(string Endpoint, object? Body)> _received = []; private readonly List _consumers = []; /// /// Registers a consumer on a direct endpoint that captures received exchanges. /// private async Task RegisterConsumer(string name) { var endpoint = (DirectEndpoint)_context.GetEndpoint($"direct:{name}"); var processor = new DelegateProcessor((exchange, _) => { _received.Add((name, exchange.In.Body)); return Task.CompletedTask; }); var consumer = endpoint.CreateConsumer(processor); await consumer.Start(); _consumers.Add(consumer); } // ══════════════════════════════════════════════════════════════ // RoundRobin — full pipeline // ══════════════════════════════════════════════════════════════ [Fact] public async Task RoundRobin_FullPipeline_DistributesEvenly() { var endpoints = new[] { "direct:lb-rr-a", "direct:lb-rr-b", "direct:lb-rr-c" }; foreach (var ep in endpoints) await RegisterConsumer(ep.Replace("direct:", "")); var lb = new LoadBalancerProcessor(_context, endpoints, new RoundRobinStrategy()); for (var i = 0; i < 9; i++) await lb.Process(new Exchange(new Message($"msg-{i}"))); _received.Count.Should().Be(9); _received.Count(r => r.Endpoint == "lb-rr-a").Should().Be(3); _received.Count(r => r.Endpoint == "lb-rr-b").Should().Be(3); _received.Count(r => r.Endpoint == "lb-rr-c").Should().Be(3); } // ══════════════════════════════════════════════════════════════ // Random — full pipeline // ══════════════════════════════════════════════════════════════ [Fact] public async Task Random_FullPipeline_AllEndpointsReceive() { var endpoints = new[] { "direct:lb-rand-a", "direct:lb-rand-b", "direct:lb-rand-c" }; foreach (var ep in endpoints) await RegisterConsumer(ep.Replace("direct:", "")); var lb = new LoadBalancerProcessor(_context, endpoints, new RandomStrategy()); for (var i = 0; i < 300; i++) await lb.Process(new Exchange(new Message($"msg-{i}"))); _received.Count.Should().Be(300); // All three endpoints should have received at least some messages _received.Select(r => r.Endpoint).Distinct().Count().Should().Be(3); } // ══════════════════════════════════════════════════════════════ // Failover — full pipeline with real failures // ══════════════════════════════════════════════════════════════ [Fact] public async Task Failover_FullPipeline_RetriesOnFailure() { // Register consumer on endpoint B only — A will throw (no consumer registered) var endpoints = new[] { "direct:lb-fo-a", "direct:lb-fo-b" }; await RegisterConsumer("lb-fo-b"); var strategy = new FailoverStrategy(maxFailures: 1); var lb = new LoadBalancerProcessor(_context, endpoints, strategy); // First exchange should fail on A, retry on B var exchange = new Exchange(new Message("failover-test")); await lb.Process(exchange); _received.Count.Should().Be(1); _received.Single().Endpoint.Should().Be("lb-fo-b"); } [Fact] public async Task Failover_FullPipeline_AllFailed_Throws() { // No consumers registered — all endpoints will fail var endpoints = new[] { "direct:lb-fo-fail-a", "direct:lb-fo-fail-b" }; var strategy = new FailoverStrategy(maxFailures: 1); var lb = new LoadBalancerProcessor(_context, endpoints, strategy); var exchange = new Exchange(new Message("all-fail")); var act = () => lb.Process(exchange); await act.Should().ThrowAsync(); } // ══════════════════════════════════════════════════════════════ // Sticky — full pipeline // ══════════════════════════════════════════════════════════════ [Fact] public async Task Sticky_FullPipeline_SameKeySameEndpoint() { var endpoints = new[] { "direct:lb-sticky-a", "direct:lb-sticky-b" }; foreach (var ep in endpoints) await RegisterConsumer(ep.Replace("direct:", "")); var strategy = new StickyStrategy(e => e.In.GetHeader("tenantId")); var lb = new LoadBalancerProcessor(_context, endpoints, strategy); // Send 10 exchanges with tenantId = "ABC" for (var i = 0; i < 10; i++) { var exchange = new Exchange(new Message($"sticky-{i}")); exchange.In.Headers["tenantId"] = "ABC"; await lb.Process(exchange); } _received.Count.Should().Be(10); // All should go to the same endpoint _received.Select(r => r.Endpoint).Distinct().Count().Should().Be(1); } // ══════════════════════════════════════════════════════════════ // Weighted — full pipeline // ══════════════════════════════════════════════════════════════ [Fact] public async Task Weighted_FullPipeline_RespectsWeights() { var endpoints = new[] { "direct:lb-wt-heavy", "direct:lb-wt-light" }; foreach (var ep in endpoints) await RegisterConsumer(ep.Replace("direct:", "")); var strategy = new WeightedStrategy([("direct:lb-wt-heavy", 3), ("direct:lb-wt-light", 1)]); var lb = new LoadBalancerProcessor(_context, endpoints, strategy); for (var i = 0; i < 400; i++) await lb.Process(new Exchange(new Message($"weighted-{i}"))); _received.Count.Should().Be(400); _received.Count(r => r.Endpoint == "lb-wt-heavy").Should().Be(300); _received.Count(r => r.Endpoint == "lb-wt-light").Should().Be(100); } // ══════════════════════════════════════════════════════════════ // Concurrent access — thread safety under load // ══════════════════════════════════════════════════════════════ [Fact] public async Task RoundRobin_Concurrent_NoDataLoss() { var endpoints = new[] { "direct:lb-conc-a", "direct:lb-conc-b", "direct:lb-conc-c" }; foreach (var ep in endpoints) await RegisterConsumer(ep.Replace("direct:", "")); var lb = new LoadBalancerProcessor(_context, endpoints, new RoundRobinStrategy()); const int total = 300; var tasks = Enumerable.Range(0, total) .Select(i => lb.Process(new Exchange(new Message($"concurrent-{i}")))) .ToArray(); await Task.WhenAll(tasks); _received.Count.Should().Be(total); } // ══════════════════════════════════════════════════════════════ // Body passthrough — data integrity // ══════════════════════════════════════════════════════════════ [Fact] public async Task LoadBalancer_PreservesExchangeBody() { await RegisterConsumer("lb-body-a"); var lb = new LoadBalancerProcessor( _context, ["direct:lb-body-a"], new RoundRobinStrategy()); var payload = new { OrderId = 42, Product = "Widget" }; await lb.Process(new Exchange(new Message(payload))); _received.Count.Should().Be(1); _received.Single().Body.Should().BeEquivalentTo(payload); } // ══════════════════════════════════════════════════════════════ // Cleanup // ══════════════════════════════════════════════════════════════ public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { foreach (var consumer in _consumers) await consumer.Stop(); await _context.DisposeAsync(); } } Path: redb-route/tests/redb.Route.Tests/Processors/LoadBalancerTests.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/Processors/LoadBalancerTests.cs ---- using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Definitions; using redb.Route.Processors.LoadBalancer; namespace redb.Route.Tests.Processors; /// /// Unit tests for Load Balancer strategies and processor. /// public class LoadBalancerTests { private static readonly string[] ThreeEndpoints = ["http://a:8080", "http://b:8080", "http://c:8080"]; // ══════════════════════════════════════════════════════════════ // RoundRobinStrategy // ══════════════════════════════════════════════════════════════ [Fact] public void RoundRobin_CyclesEvenly() { var strategy = new RoundRobinStrategy(); var exchange = CreateExchange(); var results = new List(); for (var i = 0; i < 9; i++) results.Add(strategy.Select(exchange, ThreeEndpoints)); results.Should().BeEquivalentTo([ "http://a:8080", "http://b:8080", "http://c:8080", "http://a:8080", "http://b:8080", "http://c:8080", "http://a:8080", "http://b:8080", "http://c:8080" ]); } [Fact] public void RoundRobin_SingleEndpoint_AlwaysReturnsSame() { var strategy = new RoundRobinStrategy(); var exchange = CreateExchange(); var single = new[] { "http://only:8080" }; for (var i = 0; i < 5; i++) strategy.Select(exchange, single).Should().Be("http://only:8080"); } [Fact] public void RoundRobin_EmptyEndpoints_Throws() { var strategy = new RoundRobinStrategy(); var exchange = CreateExchange(); var act = () => strategy.Select(exchange, Array.Empty()); act.Should().Throw(); } [Fact] public void RoundRobin_ThreadSafety() { var strategy = new RoundRobinStrategy(); var exchange = CreateExchange(); var counts = new ConcurrentDictionary(); foreach (var ep in ThreeEndpoints) counts[ep] = 0; const int iterations = 3000; Parallel.For(0, iterations, _ => { var selected = strategy.Select(exchange, ThreeEndpoints); counts.AddOrUpdate(selected, 1, (_, old) => old + 1); }); // With round-robin, each endpoint should get exactly 1000 picks foreach (var ep in ThreeEndpoints) counts[ep].Should().Be(1000); } // ══════════════════════════════════════════════════════════════ // RandomStrategy // ══════════════════════════════════════════════════════════════ [Fact] public void Random_DistributesAcrossEndpoints() { var strategy = new RandomStrategy(); var exchange = CreateExchange(); var hits = new HashSet(); // With 1000 iterations and 3 endpoints, extremely unlikely to miss any for (var i = 0; i < 1000; i++) hits.Add(strategy.Select(exchange, ThreeEndpoints)); hits.Should().BeEquivalentTo(ThreeEndpoints); } [Fact] public void Random_SingleEndpoint_AlwaysReturnsSame() { var strategy = new RandomStrategy(); var exchange = CreateExchange(); var single = new[] { "http://only:8080" }; for (var i = 0; i < 10; i++) strategy.Select(exchange, single).Should().Be("http://only:8080"); } [Fact] public void Random_EmptyEndpoints_Throws() { var strategy = new RandomStrategy(); var exchange = CreateExchange(); var act = () => strategy.Select(exchange, Array.Empty()); act.Should().Throw(); } // ══════════════════════════════════════════════════════════════ // FailoverStrategy // ══════════════════════════════════════════════════════════════ [Fact] public void Failover_SelectsFirstHealthy() { var strategy = new FailoverStrategy(maxFailures: 2); var exchange = CreateExchange(); strategy.Select(exchange, ThreeEndpoints).Should().Be("http://a:8080"); } [Fact] public void Failover_SkipsFailedEndpoints() { var strategy = new FailoverStrategy(maxFailures: 2); var exchange = CreateExchange(); // Fail endpoint A twice (reaches maxFailures) strategy.ReportFailure("http://a:8080", new Exception("down")); strategy.ReportFailure("http://a:8080", new Exception("down")); strategy.Select(exchange, ThreeEndpoints).Should().Be("http://b:8080"); } [Fact] public void Failover_BelowMaxFailures_StillSelects() { var strategy = new FailoverStrategy(maxFailures: 3); var exchange = CreateExchange(); // Only 1 failure, maxFailures is 3 — should still select A strategy.ReportFailure("http://a:8080", new Exception("flaky")); strategy.Select(exchange, ThreeEndpoints).Should().Be("http://a:8080"); } [Fact] public void Failover_AllFailed_ReturnFirst() { var strategy = new FailoverStrategy(maxFailures: 1); var exchange = CreateExchange(); foreach (var ep in ThreeEndpoints) strategy.ReportFailure(ep, new Exception("all down")); // Falls back to first endpoint strategy.Select(exchange, ThreeEndpoints).Should().Be("http://a:8080"); } [Fact] public void Failover_RecoveryAfterTimeout() { // Use very short recovery timeout (already expired by definition) var strategy = new FailoverStrategy(maxFailures: 1, recoveryTimeout: TimeSpan.Zero); var exchange = CreateExchange(); strategy.ReportFailure("http://a:8080", new Exception("down")); // Recovery timeout of zero + any elapsed time → should probe A again strategy.Select(exchange, ThreeEndpoints).Should().Be("http://a:8080"); } [Fact] public void Failover_SuccessResetsFailureCount() { var strategy = new FailoverStrategy(maxFailures: 2); var exchange = CreateExchange(); strategy.ReportFailure("http://a:8080", new Exception()); strategy.ReportFailure("http://a:8080", new Exception()); // A is now considered failed strategy.ReportSuccess("http://a:8080"); // A should be healthy again strategy.Select(exchange, ThreeEndpoints).Should().Be("http://a:8080"); } [Fact] public void Failover_EmptyEndpoints_Throws() { var strategy = new FailoverStrategy(); var exchange = CreateExchange(); var act = () => strategy.Select(exchange, Array.Empty()); act.Should().Throw(); } [Fact] public void Failover_InvalidMaxFailures_Throws() { var act = () => new FailoverStrategy(maxFailures: 0); act.Should().Throw(); } // ══════════════════════════════════════════════════════════════ // WeightedStrategy // ══════════════════════════════════════════════════════════════ [Fact] public void Weighted_RespectsWeightProportions() { var strategy = new WeightedStrategy([("http://heavy:8080", 3), ("http://light:8080", 1)]); var exchange = CreateExchange(); var counts = new Dictionary { ["http://heavy:8080"] = 0, ["http://light:8080"] = 0 }; for (var i = 0; i < 400; i++) counts[strategy.Select(exchange, ["http://heavy:8080", "http://light:8080"])]++; // 3:1 ratio over 400 iterations = heavy: 300, light: 100 counts["http://heavy:8080"].Should().Be(300); counts["http://light:8080"].Should().Be(100); } [Fact] public void Weighted_SingleWeight_AlwaysSame() { var strategy = new WeightedStrategy([("http://only:8080", 5)]); var exchange = CreateExchange(); for (var i = 0; i < 10; i++) strategy.Select(exchange, ["http://only:8080"]).Should().Be("http://only:8080"); } [Fact] public void Weighted_EmptyEndpoints_Throws() { var act = () => new WeightedStrategy([]); act.Should().Throw(); } [Fact] public void Weighted_ZeroWeight_Throws() { var act = () => new WeightedStrategy([("http://a:8080", 0)]); act.Should().Throw(); } [Fact] public void Weighted_NegativeWeight_Throws() { var act = () => new WeightedStrategy([("http://a:8080", -1)]); act.Should().Throw(); } // ══════════════════════════════════════════════════════════════ // StickyStrategy // ══════════════════════════════════════════════════════════════ [Fact] public void Sticky_SameKey_SameEndpoint() { var strategy = new StickyStrategy(e => e.In.GetHeader("tenantId")); var exchange1 = CreateExchange(headers: new() { ["tenantId"] = "tenant-A" }); var exchange2 = CreateExchange(headers: new() { ["tenantId"] = "tenant-A" }); var ep1 = strategy.Select(exchange1, ThreeEndpoints); var ep2 = strategy.Select(exchange2, ThreeEndpoints); ep1.Should().Be(ep2); } [Fact] public void Sticky_DifferentKeys_CanSelectDifferentEndpoints() { var strategy = new StickyStrategy(e => e.In.GetHeader("tenantId")); var hits = new HashSet(); // Generate enough keys to hit different endpoints for (var i = 0; i < 100; i++) { var exchange = CreateExchange(headers: new() { ["tenantId"] = $"tenant-{i}" }); hits.Add(strategy.Select(exchange, ThreeEndpoints)); } // Should hit at least 2 different endpoints (extremely likely with 100 keys and 3 endpoints) hits.Count.Should().BeGreaterThanOrEqualTo(2); } [Fact] public void Sticky_NullKey_FallsBackToRoundRobin() { var strategy = new StickyStrategy(_ => null); var exchange = CreateExchange(); // Should not throw — falls back to round-robin var selected = strategy.Select(exchange, ThreeEndpoints); selected.Should().BeOneOf(ThreeEndpoints); } [Fact] public void Sticky_EmptyKey_FallsBackToRoundRobin() { var strategy = new StickyStrategy(_ => ""); var exchange = CreateExchange(); var selected = strategy.Select(exchange, ThreeEndpoints); selected.Should().BeOneOf(ThreeEndpoints); } [Fact] public void Sticky_EmptyEndpoints_Throws() { var strategy = new StickyStrategy(_ => "key"); var exchange = CreateExchange(); var act = () => strategy.Select(exchange, Array.Empty()); act.Should().Throw(); } [Fact] public void Sticky_NullExtractor_Throws() { var act = () => new StickyStrategy(null!); act.Should().Throw(); } [Fact] public void Failover_NegativeRecoveryTimeout_Throws() { var act = () => new FailoverStrategy(maxFailures: 3, recoveryTimeout: TimeSpan.FromSeconds(-1)); act.Should().Throw(); } // ══════════════════════════════════════════════════════════════ // ILoadBalancerStrategy default methods // ══════════════════════════════════════════════════════════════ [Fact] public void DefaultInterface_ReportMethods_AreNoOp() { // RoundRobin doesn't override Report methods — verify default no-ops work ILoadBalancerStrategy strategy = new RoundRobinStrategy(); // Should not throw strategy.ReportFailure("http://a:8080", new Exception("test")); strategy.ReportSuccess("http://a:8080"); } // ══════════════════════════════════════════════════════════════ // DSL integration // ══════════════════════════════════════════════════════════════ [Fact] public void DSL_LoadBalance_AddsStep() { var def = new RouteDefinition(); var strategy = new RoundRobinStrategy(); def.LoadBalance(strategy, "http://a:8080", "http://b:8080"); var lbDef = def.Outputs.Should().ContainSingle().Which.Should().BeOfType().Subject; lbDef.Strategy.Should().BeSameAs(strategy); lbDef.Endpoints.Should().BeEquivalentTo(["http://a:8080", "http://b:8080"]); } [Fact] public void DSL_LoadBalance_NullStrategy_Throws() { var def = new RouteDefinition(); var act = () => def.LoadBalance(null!, "http://a:8080"); act.Should().Throw(); } [Fact] public void DSL_LoadBalance_NoUris_Throws() { var def = new RouteDefinition(); var act = () => def.LoadBalance(new RoundRobinStrategy()); act.Should().Throw(); } // ══════════════════════════════════════════════════════════════ // Helpers // ══════════════════════════════════════════════════════════════ private static IExchange CreateExchange(object? body = null, Dictionary? headers = null) { var msg = new Message { Body = body ?? "test" }; if (headers != null) { foreach (var (k, v) in headers) msg.Headers[k] = v; } return new Exchange(msg); } } Path: redb-route/tests/redb.Route.Tests/Processors/LogProcessorTests.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/Processors/LogProcessorTests.cs ---- using AwesomeAssertions; using Microsoft.Extensions.Logging; using NSubstitute; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Processors; namespace redb.Route.Tests.Processors; /// Tests for . public class LogProcessorTests { /// Static message is logged. [Fact] public async Task Process_StaticMessage_Logged() { var logger = Substitute.For(); var processor = new LogProcessor(logger, "hello route"); await processor.Process(new Exchange()); logger.Received(1).Log( LogLevel.Information, Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any>()); } /// Dynamic message receives the exchange. [Fact] public async Task Process_DynamicMessage_UsesExchange() { var logger = Substitute.For(); var processor = new LogProcessor(logger, ex => $"body={ex.In.Body}"); await processor.Process(new Exchange(new Message("test"))); logger.Received(1).Log( LogLevel.Information, Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any>()); } /// Custom log level is used. [Fact] public async Task Process_CustomLevel_Used() { var logger = Substitute.For(); var processor = new LogProcessor(logger, "warn!", LogLevel.Warning); await processor.Process(new Exchange()); logger.Received(1).Log( LogLevel.Warning, Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any>()); } /// Null logger throws. [Fact] public void Constructor_NullLogger_Throws() { var act = () => new LogProcessor(null!, "msg"); act.Should().Throw(); } /// Null message func throws. [Fact] public void Constructor_NullMessageFunc_Throws() { var logger = Substitute.For(); var act = () => new LogProcessor(logger, (Func)null!); act.Should().Throw(); } } Path: redb-route/tests/redb.Route.Tests/Processors/LoopProcessorTests.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/Processors/LoopProcessorTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Processors; namespace redb.Route.Tests.Processors; /// Tests for . public class LoopProcessorTests { /// Count-based loop executes N times. [Fact] public async Task Process_CountBased_ExecutesNTimes() { var count = 0; var body = new DelegateProcessor(_ => count++); var loop = new LoopProcessor(body, 5); await loop.Process(new Exchange()); count.Should().Be(5); } /// Count zero executes zero times. [Fact] public async Task Process_CountZero_NoExecution() { var count = 0; var body = new DelegateProcessor(_ => count++); var loop = new LoopProcessor(body, 0); await loop.Process(new Exchange()); count.Should().Be(0); } /// Predicate-based loop stops when false. [Fact] public async Task Process_PredicateBased_StopsWhenFalse() { var iterations = 0; var body = new DelegateProcessor(ex => { iterations++; var current = (int)(ex.In.Body ?? 0); ex.In.Body = current + 1; }); var loop = new LoopProcessor(body, ex => (int)(ex.In.Body ?? 0) < 3); var exchange = new Exchange(new Message(0)); await loop.Process(exchange); iterations.Should().Be(3); exchange.In.Body.Should().Be(3); } /// Exchange.Stop() breaks the loop. [Fact] public async Task Process_ExchangeStopped_BreaksLoop() { var count = 0; var body = new DelegateProcessor(ex => { count++; if (count >= 2) ex.Stop(); }); var loop = new LoopProcessor(body, 100); await loop.Process(new Exchange()); count.Should().Be(2); } /// CancellationToken is respected. [Fact] public async Task Process_CancellationRespected() { using var cts = new CancellationTokenSource(); var count = 0; var body = new DelegateProcessor((ex, ct) => { count++; if (count >= 3) cts.Cancel(); return Task.CompletedTask; }); var loop = new LoopProcessor(body, 1000); var act = () => loop.Process(new Exchange(), cts.Token); await act.Should().ThrowAsync(); count.Should().BeGreaterThanOrEqualTo(3); } /// Negative maxIterations throws. [Fact] public void Constructor_NegativeCount_Throws() { var act = () => new LoopProcessor(new DelegateProcessor(_ => { }), -1); act.Should().Throw(); } // ── Copy Mode ── /// Copy mode clones exchange each iteration — mutations don't accumulate. [Fact] public async Task Process_CopyMode_CountBased_IsolatesIterations() { var bodies = new List(); var body = new DelegateProcessor(ex => { var val = (int)(ex.In.Body ?? 0); bodies.Add(val); ex.In.Body = val + 100; // mutate — should NOT carry to next iteration }); var loop = new LoopProcessor(body, 3, copy: true); var exchange = new Exchange(new Message(1)); await loop.Process(exchange); // Each iteration should see original body = 1 bodies.Should().AllBeEquivalentTo(1); // Final exchange body = last iteration result (1 + 100) ((int)exchange.In.Body!).Should().Be(101); } /// Copy mode with predicate loop. [Fact] public async Task Process_CopyMode_PredicateBased_IsolatesIterations() { var iteration = 0; var body = new DelegateProcessor(ex => { iteration++; ex.In.Body = iteration; // mutate }); // Predicate checks original exchange body (always 0 < 3), // but iteration counter grows externally var loop = new LoopProcessor(body, ex => iteration < 3, copy: true); var exchange = new Exchange(new Message(0)); await loop.Process(exchange); iteration.Should().Be(3); // Last iteration wrote 3 to copy → merged back ((int)exchange.In.Body!).Should().Be(3); } /// Non-copy mode accumulates mutations across iterations. [Fact] public async Task Process_NoCopy_MutationsAccumulate() { var bodies = new List(); var body = new DelegateProcessor(ex => { var val = (int)(ex.In.Body ?? 0); bodies.Add(val); ex.In.Body = val + 1; }); var loop = new LoopProcessor(body, 3, copy: false); var exchange = new Exchange(new Message(0)); await loop.Process(exchange); bodies.Should().BeEquivalentTo(new[] { 0, 1, 2 }); ((int)exchange.In.Body!).Should().Be(3); } /// Each iteration carries its index, and a counted loop its size, as Camel's loop properties. [Theory] [InlineData(false)] [InlineData(true)] public async Task Process_CountBased_PublishesLoopIndexAndSize(bool copy) { var seen = new List<(int Index, int Size)>(); var body = new DelegateProcessor(ex => seen.Add( (ex.GetProperty(ExchangePropertyKeys.LoopIndex), ex.GetProperty(ExchangePropertyKeys.LoopSize)))); await new LoopProcessor(body, 3, copy).Process(new Exchange(new Message("x"))); seen.Should().Equal((0, 3), (1, 3), (2, 3)); } /// A while loop carries its index and no size: the count is not known in advance. [Fact] public async Task Process_PredicateBased_PublishesLoopIndexOnly() { var seen = new List<(int Index, bool HasSize)>(); var body = new DelegateProcessor(ex => { seen.Add((ex.GetProperty(ExchangePropertyKeys.LoopIndex), ex.Properties.ContainsKey(ExchangePropertyKeys.LoopSize))); ex.In.Body = (int)ex.In.Body! + 1; }); await new LoopProcessor(body, ex => (int)ex.In.Body! < 2).Process(new Exchange(new Message(0))); seen.Should().Equal((0, false), (1, false)); } } Path: redb-route/tests/redb.Route.Tests/Processors/MessageHistoryTests.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/Processors/MessageHistoryTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Configuration; using redb.Route.Core; namespace redb.Route.Tests.Processors; /// /// Tests for the Message History EIP: per-node recording, enablement (global + route override), /// ordering, on-throw capture, and formatting. /// public class MessageHistoryTests { private static async Task RunAsync(RouteContext context, string fromUri, IExchange exchange) { await context.Start(); var producer = context.GetEndpoint(fromUri).CreateProducer(); await producer.Start(); await producer.Process(exchange); return exchange; } [Fact] public async Task MessageHistory_RouteEnabled_RecordsEachNodeInOrder() { await using var context = new RouteContext(); context.AddRoutes(r => r.From("direct://mh-order").MessageHistory() .Process(_ => { }) .Process(_ => { })); var exchange = await RunAsync(context, "direct://mh-order", new Exchange(new Message("x"))); var entries = MessageHistory.GetEntries(exchange); entries.Should().HaveCount(2); entries[0].NodeId.Should().Be("processAction1"); entries[1].NodeId.Should().Be("processAction2"); entries.Should().OnlyContain(e => e.Label == "processAction" && e.ElapsedMs >= 0 && e.RouteId.Length > 0); } [Fact] public async Task MessageHistory_DisabledByDefault_RecordsNothing() { await using var context = new RouteContext(); context.AddRoutes(r => r.From("direct://mh-off").Process(_ => { })); var exchange = await RunAsync(context, "direct://mh-off", new Exchange(new Message("x"))); MessageHistory.GetEntries(exchange).Should().BeEmpty(); } [Fact] public async Task MessageHistory_GlobalOption_Enables() { await using var context = new RouteContext(options: new RouteEngineOptions { EnableMessageHistory = true }); context.AddRoutes(r => r.From("direct://mh-global").Process(_ => { })); var exchange = await RunAsync(context, "direct://mh-global", new Exchange(new Message("x"))); MessageHistory.GetEntries(exchange).Should().ContainSingle(); } [Fact] public async Task MessageHistory_RouteOverride_DisablesWhenGlobalOn() { await using var context = new RouteContext(options: new RouteEngineOptions { EnableMessageHistory = true }); context.AddRoutes(r => r.From("direct://mh-override").MessageHistory(false).Process(_ => { })); var exchange = await RunAsync(context, "direct://mh-override", new Exchange(new Message("x"))); MessageHistory.GetEntries(exchange).Should().BeEmpty(); } [Fact] public async Task MessageHistory_RecordsEntry_EvenWhenNodeThrows() { await using var context = new RouteContext(); context.AddRoutes(r => r.From("direct://mh-throw").MessageHistory() .Process(_ => throw new InvalidOperationException("boom"))); await context.Start(); var producer = context.GetEndpoint("direct://mh-throw").CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("x")); // The throwing node still records its history entry (recorded in a finally). try { await producer.Process(exchange); } catch (InvalidOperationException) { /* expected */ } var entries = MessageHistory.GetEntries(exchange); entries.Should().ContainSingle().Which.Label.Should().Be("processAction"); } [Fact] public async Task MessageHistory_Format_ProducesTable() { await using var context = new RouteContext(); context.AddRoutes(r => r.From("direct://mh-fmt").MessageHistory().Process(_ => { })); var exchange = await RunAsync(context, "direct://mh-fmt", new Exchange(new Message("x"))); var dump = MessageHistory.Format(exchange); dump.Should().Contain("Message History"); dump.Should().Contain("processAction"); } [Fact] public async Task MessageHistory_Format_EmptyWhenNoHistory() { MessageHistory.Format(new Exchange(new Message("x"))).Should().BeEmpty(); } } Path: redb-route/tests/redb.Route.Tests/Processors/MulticastProcessorTests.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/Processors/MulticastProcessorTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Processors; namespace redb.Route.Tests.Processors; /// Tests for . public class MulticastProcessorTests { /// Parallel processing sends clones to all targets. [Fact] public async Task Process_Parallel_AllTargetsReceiveClones() { var bodies = new System.Collections.Concurrent.ConcurrentBag(); var multicast = new MulticastProcessor(parallelProcessing: true) .AddTarget(new DelegateProcessor(ex => bodies.Add(ex.In.Body))) .AddTarget(new DelegateProcessor(ex => bodies.Add(ex.In.Body))); await multicast.Process(new Exchange(new Message("data"))); bodies.Should().HaveCount(2); bodies.Should().OnlyContain(b => (string)b! == "data"); } /// Sequential processing preserves order. [Fact] public async Task Process_Sequential_PreservesOrder() { var order = new List(); var multicast = new MulticastProcessor(parallelProcessing: false) .AddTarget(new DelegateProcessor(_ => order.Add(1))) .AddTarget(new DelegateProcessor(_ => order.Add(2))); await multicast.Process(new Exchange()); order.Should().Equal(1, 2); } /// Each target gets an independent clone — mutations don't leak. [Fact] public async Task Process_Clones_AreIndependent() { IExchange? clone1 = null; IExchange? clone2 = null; var multicast = new MulticastProcessor(parallelProcessing: false) .AddTarget(new DelegateProcessor(ex => { clone1 = ex; ex.In.Body = "modified-1"; })) .AddTarget(new DelegateProcessor(ex => { clone2 = ex; })); var original = new Exchange(new Message("original")); await multicast.Process(original); clone1!.In.Body.Should().Be("modified-1"); clone2!.In.Body.Should().Be("original"); // Not affected by clone1 original.In.Body.Should().Be("original"); // Original unchanged } /// Aggregation strategy is called pair-wise for each clone result. [Fact] public async Task Process_WithAggregation_MergesResults() { var multicast = new MulticastProcessor( parallelProcessing: false, aggregationStrategy: (aggregated, current) => { aggregated.In.Body = (int)aggregated.In.Body! + (int)current.In.Body!; return aggregated; }) .AddTarget(new DelegateProcessor(ex => ex.In.Body = 10)) .AddTarget(new DelegateProcessor(ex => ex.In.Body = 20)); var exchange = new Exchange(new Message(0)); await multicast.Process(exchange); exchange.In.Body.Should().Be(30); } /// Empty multicast does nothing. [Fact] public async Task Process_NoTargets_DoesNothing() { var multicast = new MulticastProcessor(); await multicast.Process(new Exchange()); // No exception = success } /// Targets property returns all added processors. [Fact] public void Targets_ReturnsAll() { var multicast = new MulticastProcessor() .AddTarget(new DelegateProcessor(_ => { })) .AddTarget(new DelegateProcessor(_ => { })); multicast.Targets.Should().HaveCount(2); } // ── Parallel Error Handling ── /// Single parallel failure: exchange.Exception is the single exception. [Fact] public async Task ProcessParallel_SingleFailure_SetsExchangeException() { var multicast = new MulticastProcessor(parallelProcessing: true, stopOnException: false) .AddTarget(new DelegateProcessor(_ => { })) .AddTarget(new DelegateProcessor((_, _) => throw new InvalidOperationException("boom"))); var exchange = new Exchange(new Message("data")); await multicast.Process(exchange); exchange.Exception.Should().BeOfType(); exchange.Exception!.Message.Should().Be("boom"); } /// Multiple parallel failures: exchange.Exception is AggregateException. [Fact] public async Task ProcessParallel_MultipleFailures_SetsAggregateException() { var multicast = new MulticastProcessor(parallelProcessing: true, stopOnException: false) .AddTarget(new DelegateProcessor((_, _) => throw new InvalidOperationException("err1"))) .AddTarget(new DelegateProcessor((_, _) => throw new ArgumentException("err2"))) .AddTarget(new DelegateProcessor(_ => { })); var exchange = new Exchange(new Message("data")); await multicast.Process(exchange); exchange.Exception.Should().BeOfType(); var agg = (AggregateException)exchange.Exception!; agg.InnerExceptions.Should().HaveCount(2); agg.InnerExceptions.Should().Contain(e => e is InvalidOperationException); agg.InnerExceptions.Should().Contain(e => e is ArgumentException); } /// stopOnException=true rethrows the first exception. [Fact] public async Task ProcessParallel_StopOnException_Rethrows() { var multicast = new MulticastProcessor(parallelProcessing: true, stopOnException: true) .AddTarget(new DelegateProcessor((_, _) => throw new InvalidOperationException("stop"))) .AddTarget(new DelegateProcessor(_ => { })); var exchange = new Exchange(new Message("data")); var act = async () => await multicast.Process(exchange); await act.Should().ThrowAsync().WithMessage("stop"); } // ── Sequential Error Handling ── /// Sequential failure with stopOnException sets exchange.Exception and rethrows. [Fact] public async Task ProcessSequential_StopOnException_SetsExceptionAndThrows() { var count = 0; var multicast = new MulticastProcessor(parallelProcessing: false, stopOnException: true) .AddTarget(new DelegateProcessor(_ => count++)) .AddTarget(new DelegateProcessor((_, _) => throw new InvalidOperationException("seq-fail"))) .AddTarget(new DelegateProcessor(_ => count++)); var exchange = new Exchange(new Message("data")); var act = async () => await multicast.Process(exchange); await act.Should().ThrowAsync().WithMessage("seq-fail"); count.Should().Be(1); // Third target was skipped } /// Sequential without stopOnException continues and stores exception. [Fact] public async Task ProcessSequential_NoStop_ContinuesAfterFailure() { var count = 0; var multicast = new MulticastProcessor(parallelProcessing: false, stopOnException: false) .AddTarget(new DelegateProcessor(_ => count++)) .AddTarget(new DelegateProcessor((_, _) => throw new InvalidOperationException("e1"))) .AddTarget(new DelegateProcessor(_ => count++)); var exchange = new Exchange(new Message("data")); await multicast.Process(exchange); count.Should().Be(2); // All non-failing targets executed } /// Each branch carries its index, whether it is the last, and the parent's id, as Camel's multicast. [Theory] [InlineData(false)] [InlineData(true)] public async Task Process_PublishesMulticastIndexCompleteAndCorrelationId(bool parallel) { var seen = new System.Collections.Concurrent.ConcurrentBag<(int Index, bool Complete, string? CorrelationId)>(); void Capture(IExchange ex) => seen.Add((ex.GetProperty(ExchangePropertyKeys.MulticastIndex), ex.GetProperty(ExchangePropertyKeys.MulticastComplete), ex.GetProperty(ExchangePropertyKeys.CorrelationId))); var multicast = new MulticastProcessor(parallelProcessing: parallel) .AddTarget(new DelegateProcessor(Capture)) .AddTarget(new DelegateProcessor(Capture)) .AddTarget(new DelegateProcessor(Capture)); var parent = new Exchange(new Message("data")); await multicast.Process(parent); seen.OrderBy(s => s.Index).Should().Equal( (0, false, parent.ExchangeId), (1, false, parent.ExchangeId), (2, true, parent.ExchangeId)); } } Path: redb-route/tests/redb.Route.Tests/Processors/NormalizerIntegrationTests.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/Processors/NormalizerIntegrationTests.cs ---- using System; using System.Collections.Generic; using System.Globalization; using System.Threading.Tasks; using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Definitions; namespace redb.Route.Tests.Processors; /// /// Integration tests for Normalizer using full route compilation and pipeline execution. /// [Trait("Category", "Integration")] public class NormalizerIntegrationTests { private readonly RouteContext _context = new(); private static IExchange CreateExchange(object? body = null, IDictionary? headers = null) { var msg = new Message(body); if (headers is not null) { foreach (var kv in headers) msg.Headers[kv.Key] = kv.Value; } return Exchange.Create(msg, null); } // ══════════════════════════════════════════════════════════════ // Basic predicate routing // ══════════════════════════════════════════════════════════════ [Fact] public async Task When_MatchingPredicate_AppliesTransform() { var def = new RouteDefinition(); def.From("direct://normalize"); def.Normalize(n => n .When(e => e.In.Body is string, e => ((string)e.In.Body!).ToUpperInvariant()) .When(e => e.In.Body is int, e => ((int)e.In.Body!) * 10)); var pipeline = def.CreateProcessor(_context); var exchange = CreateExchange("hello"); await pipeline.Process(exchange); exchange.In.Body.Should().Be("HELLO"); } [Fact] public async Task When_SecondPredicate_MatchesCorrectBranch() { var def = new RouteDefinition(); def.From("direct://normalize"); def.Normalize(n => n .When(e => e.In.Body is string, e => "was-string") .When(e => e.In.Body is int, e => "was-int")); var pipeline = def.CreateProcessor(_context); var exchange = CreateExchange(42); await pipeline.Process(exchange); exchange.In.Body.Should().Be("was-int"); } [Fact] public async Task When_NoMatch_BodyUnchanged() { var def = new RouteDefinition(); def.From("direct://normalize"); def.Normalize(n => n .When(e => e.In.Body is string, e => "was-string")); var pipeline = def.CreateProcessor(_context); var exchange = CreateExchange(42); await pipeline.Process(exchange); exchange.In.Body.Should().Be(42); } // ══════════════════════════════════════════════════════════════ // Otherwise fallback // ══════════════════════════════════════════════════════════════ [Fact] public async Task Otherwise_AppliedWhenNoPredicateMatches() { var def = new RouteDefinition(); def.From("direct://normalize"); def.Normalize(n => n .When(e => e.In.Body is string, e => "was-string") .Otherwise(e => "unknown-format")); var pipeline = def.CreateProcessor(_context); var exchange = CreateExchange(new object()); await pipeline.Process(exchange); exchange.In.Body.Should().Be("unknown-format"); } [Fact] public async Task Otherwise_NotApplied_WhenPredicateMatches() { var def = new RouteDefinition(); def.From("direct://normalize"); def.Normalize(n => n .When(e => e.In.Body is string, e => "was-string") .Otherwise(e => "fallback")); var pipeline = def.CreateProcessor(_context); var exchange = CreateExchange("test"); await pipeline.Process(exchange); exchange.In.Body.Should().Be("was-string"); } // ══════════════════════════════════════════════════════════════ // ContentType-based routing // ══════════════════════════════════════════════════════════════ [Fact] public async Task WhenContentType_MatchesJsonHeader() { var def = new RouteDefinition(); def.From("direct://normalize"); def.Normalize(n => n .WhenContentType("application/json", e => $"json:{e.In.Body}") .WhenContentType("application/xml", e => $"xml:{e.In.Body}")); var pipeline = def.CreateProcessor(_context); var exchange = CreateExchange("data", new Dictionary { ["ContentType"] = "application/json" }); await pipeline.Process(exchange); exchange.In.Body.Should().Be("json:data"); } [Fact] public async Task WhenContentType_CaseInsensitive() { var def = new RouteDefinition(); def.From("direct://normalize"); def.Normalize(n => n .WhenContentType("application/xml", e => "xml-normalized")); var pipeline = def.CreateProcessor(_context); var exchange = CreateExchange("data", new Dictionary { ["ContentType"] = "APPLICATION/XML" }); await pipeline.Process(exchange); exchange.In.Body.Should().Be("xml-normalized"); } // ══════════════════════════════════════════════════════════════ // Mixed clauses // ══════════════════════════════════════════════════════════════ [Fact] public async Task MixedClauses_PredicateAndContentType() { var def = new RouteDefinition(); def.From("direct://normalize"); def.Normalize(n => n .When(e => e.In.Body is int, e => string.Format(CultureInfo.InvariantCulture, "int:{0}", e.In.Body)) .WhenContentType("text/csv", e => string.Format(CultureInfo.InvariantCulture, "csv:{0}", e.In.Body)) .Otherwise(e => string.Format(CultureInfo.InvariantCulture, "other:{0}", e.In.Body))); var pipeline = def.CreateProcessor(_context); // int body → predicate branch var e1 = CreateExchange(100); await pipeline.Process(e1); e1.In.Body.Should().Be("int:100"); // text/csv → content-type branch var e2 = CreateExchange("a,b,c", new Dictionary { ["ContentType"] = "text/csv" }); await pipeline.Process(e2); e2.In.Body.Should().Be("csv:a,b,c"); // no match → otherwise var e3 = CreateExchange(3.14); await pipeline.Process(e3); e3.In.Body.Should().Be("other:3.14"); } // ══════════════════════════════════════════════════════════════ // Pipeline chaining // ══════════════════════════════════════════════════════════════ [Fact] public async Task Normalize_ChainsWithSubsequentSteps() { var def = new RouteDefinition(); def.From("direct://normalize"); def.Normalize(n => n .When(e => e.In.Body is string, e => ((string)e.In.Body!).ToUpperInvariant())); def.SetHeader("Normalized", "true"); var pipeline = def.CreateProcessor(_context); var exchange = CreateExchange("hello"); await pipeline.Process(exchange); exchange.In.Body.Should().Be("HELLO"); exchange.In.Headers["Normalized"].Should().Be("true"); } [Fact] public async Task Normalize_PreservesProperties() { var def = new RouteDefinition(); def.From("direct://normalize"); def.Normalize(n => n .When(e => true, e => "normalized")); var pipeline = def.CreateProcessor(_context); var exchange = CreateExchange("raw"); exchange.Properties["traceId"] = "abc-123"; await pipeline.Process(exchange); exchange.In.Body.Should().Be("normalized"); exchange.Properties["traceId"].Should().Be("abc-123"); } } Path: redb-route/tests/redb.Route.Tests/Processors/NormalizerTests.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/Processors/NormalizerTests.cs ---- using System; using System.Collections.Generic; using System.Linq; using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Definitions; namespace redb.Route.Tests.Processors; /// /// Unit tests for Normalizer DSL, builder validation, and step generation. /// public class NormalizerTests { // ══════════════════════════════════════════════════════════════ // DSL — step recording // ══════════════════════════════════════════════════════════════ [Fact] public void DSL_AddsNormalizerStep() { var def = new RouteDefinition(); def.Normalize(n => n .When(e => e.In.Body is string, e => ((string)e.In.Body!).ToUpperInvariant())); def.Outputs.Should().ContainSingle().Which.Should().BeOfType(); } [Fact] public void DSL_NullConfigure_Throws() { var def = new RouteDefinition(); var act = () => def.Normalize(null!); act.Should().Throw(); } [Fact] public void DSL_NoWhenClauses_Throws() { var def = new RouteDefinition(); def.From("direct://test"); var act = () => def.Normalize(n => { }); act.Should().Throw() .WithMessage("*at least one When*"); } // ══════════════════════════════════════════════════════════════ // Builder — When clause validation // ══════════════════════════════════════════════════════════════ [Fact] public void When_NullPredicate_Throws() { var builder = new NormalizerDefinition(); var act = () => builder.When(null!, e => e.In.Body); act.Should().Throw(); } [Fact] public void When_NullTransform_Throws() { var builder = new NormalizerDefinition(); var act = () => builder.When(e => true, null!); act.Should().Throw(); } [Fact] public void WhenContentType_NullContentType_Throws() { var builder = new NormalizerDefinition(); var act = () => builder.WhenContentType(null!, e => e.In.Body); act.Should().Throw(); } [Fact] public void WhenContentType_NullTransform_Throws() { var builder = new NormalizerDefinition(); var act = () => builder.WhenContentType("application/json", null!); act.Should().Throw(); } [Fact] public void Otherwise_NullTransform_Throws() { var builder = new NormalizerDefinition(); var act = () => builder.Otherwise(null!); act.Should().Throw(); } // ══════════════════════════════════════════════════════════════ // Builder — chaining // ══════════════════════════════════════════════════════════════ [Fact] public void Builder_Chaining_ReturnsSameInstance() { INormalizerDefinition builder = new NormalizerDefinition(); var result = builder .When(e => true, e => "a") .WhenContentType("text/plain", e => "b") .Otherwise(e => "c"); result.Should().BeSameAs(builder); } [Fact] public void DSL_Chaining_ReturnsRouteDefinition() { var def = new RouteDefinition(); def.From("direct://test"); var result = def.Normalize(n => n.When(e => true, e => "ok")); result.Should().BeSameAs(def); } } Path: redb-route/tests/redb.Route.Tests/Processors/OnExceptionCallbackProcessorTests.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/Processors/OnExceptionCallbackProcessorTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Tests.Processors; /// /// OnRedelivery, OnExceptionOccurred and OnPrepareFailure take a processor beside the delegate, as /// Apache Camel's do: the markup form of a route can only name a bean from the registry, and a bean is an /// . Both places a handler can be declared — in the route and on the builder — pass them on. /// public class OnExceptionCallbackProcessorTests { private sealed class Counting(List calls, string name) : IProcessor { public Task Process(IExchange exchange, CancellationToken ct = default) { calls.Add(name); return Task.CompletedTask; } } private static async Task Start(RouteContext context, string uri) { await context.Start(); var producer = context.GetEndpoint(uri).CreateProducer(); await producer.Start(); return producer; } [Fact] public async Task A_route_level_handler_calls_all_three_processors() { var calls = new List(); await using var context = new RouteContext(); context.AddRoutes(r => r .From("direct://cb-route") .OnException() .MaximumRedeliveries(2) .RedeliveryDelay(TimeSpan.FromMilliseconds(1)) .Handled() .OnExceptionOccurred(new Counting(calls, "occurred")) .OnRedelivery(new Counting(calls, "redelivery")) .OnPrepareFailure(new Counting(calls, "prepare")) .End() .Process(_ => throw new InvalidOperationException("boom"))); var producer = await Start(context, "direct://cb-route"); await producer.Process(new Exchange(new Message("x"))); calls.Should().Equal( "occurred", "redelivery", // first failure, then the first retry "occurred", "redelivery", // second failure, then the second retry "occurred", "prepare"); // third failure: retries exhausted, the handler is about to run } [Fact] public async Task A_builder_level_handler_calls_all_three_processors() { var calls = new List(); await using var context = new RouteContext(); context.AddRoutes(b => { b.OnException() .MaximumRedeliveries(1) .RedeliveryDelay(TimeSpan.FromMilliseconds(1)) .Handled() .OnExceptionOccurred(new Counting(calls, "occurred")) .OnRedelivery(new Counting(calls, "redelivery")) .OnPrepareFailure(new Counting(calls, "prepare")); b.From("direct://cb-builder") .Process(_ => throw new InvalidOperationException("boom")); }); var producer = await Start(context, "direct://cb-builder"); await producer.Process(new Exchange(new Message("x"))); calls.Should().Equal("occurred", "redelivery", "occurred", "prepare"); } [Fact] public async Task The_delegate_form_still_runs_beside_the_processor_form() { var calls = new List(); await using var context = new RouteContext(); context.AddRoutes(r => r .From("direct://cb-both") .OnException() .Handled() .OnExceptionOccurred(_ => calls.Add("delegate")) .OnExceptionOccurred(new Counting(calls, "processor")) .End() .Process(_ => throw new InvalidOperationException("boom"))); var producer = await Start(context, "direct://cb-both"); await producer.Process(new Exchange(new Message("x"))); calls.Should().Equal("delegate", "processor"); } } Path: redb-route/tests/redb.Route.Tests/Processors/OnExceptionContinuedTests.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/Processors/OnExceptionContinuedTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Tests.Processors; /// /// OnException ... Continued() is Apache Camel's continued(true): the failure is suppressed and routing /// picks up at the step after the one that failed, where Handled() ends the route. Camel gets it for free — its /// error handler wraps every step, so the pipeline simply moves on; here the handler wraps the route, so every pipeline /// the failure unwound through remembers where it stopped and the handler replays the rest. /// public class OnExceptionContinuedTests { private static async Task Start(RouteContext context, string uri) { await context.Start(); var producer = context.GetEndpoint(uri).CreateProducer(); await producer.Start(); return producer; } [Fact] public async Task Continued_picks_the_route_up_after_the_step_that_failed() { var steps = new List(); await using var context = new RouteContext(); context.AddRoutes(r => r .From("direct://continued-plain") .OnException() .Continued() .Process(_ => steps.Add("handler")) .End() .Process(_ => steps.Add("before")) .Process(_ => throw new InvalidOperationException("boom")) .Process(_ => steps.Add("after"))); var producer = await Start(context, "direct://continued-plain"); var exchange = new Exchange(new Message("x")); await producer.Process(exchange); steps.Should().Equal("before", "handler", "after"); exchange.Exception.Should().BeNull("a continued failure is suppressed, as a handled one is"); exchange.EndedInFailure().Should().BeFalse(); } [Fact] public async Task Handled_ends_the_route_at_the_step_that_failed() { var steps = new List(); await using var context = new RouteContext(); context.AddRoutes(r => r .From("direct://handled-plain") .OnException() .Handled() .Process(_ => steps.Add("handler")) .End() .Process(_ => throw new InvalidOperationException("boom")) .Process(_ => steps.Add("after"))); var producer = await Start(context, "direct://handled-plain"); await producer.Process(new Exchange(new Message("x"))); steps.Should().Equal("handler"); } [Fact] public async Task Continued_picks_up_inside_the_scope_that_failed_and_then_outside_it() { var steps = new List(); await using var context = new RouteContext(); context.AddRoutes(r => r .From("direct://continued-nested") .OnException() .Continued() .End() .Filter(_ => true, b => b .Process(_ => throw new InvalidOperationException("boom")) .Process(_ => steps.Add("rest of the scope"))) .Process(_ => steps.Add("after the scope"))); var producer = await Start(context, "direct://continued-nested"); await producer.Process(new Exchange(new Message("x"))); steps.Should().Equal("rest of the scope", "after the scope"); } [Fact] public async Task Continued_does_not_replay_a_block_whose_transaction_rolled_back() { var steps = new List(); await using var context = new RouteContext(); context.AddRoutes(r => r .From("direct://continued-tx") .OnException() .Continued() .End() .Transacted() .Process(_ => steps.Add("work")) .Process(_ => throw new InvalidOperationException("boom")) .Process(_ => steps.Add("rest of the block")) .End() .Process(_ => steps.Add("after the block"))); var producer = await Start(context, "direct://continued-tx"); await producer.Process(new Exchange(new Message("x"))); steps.Should().Equal("work", "after the block"); } [Fact] public async Task A_builder_level_handler_resumes_the_route_too() { var steps = new List(); await using var context = new RouteContext(); context.AddRoutes(b => { b.OnException() .Continued() .Process(_ => steps.Add("handler")); b.From("direct://continued-builder") .Process(_ => throw new InvalidOperationException("boom")) .Process(_ => steps.Add("after")); }); var producer = await Start(context, "direct://continued-builder"); await producer.Process(new Exchange(new Message("x"))); // A handler declared on the builder wraps the route from the outside; the route's own pipeline still recorded // where it stopped, so the resume works from there too. steps.Should().Equal("handler", "after"); } [Fact] public async Task A_failure_in_the_resumed_steps_goes_through_the_handlers_again() { var steps = new List(); await using var context = new RouteContext(); context.AddRoutes(r => r .From("direct://continued-twice") .OnException() .Continued() .Process(_ => steps.Add("handler")) .End() .Process(_ => throw new InvalidOperationException("first")) .Process(_ => throw new InvalidOperationException("second")) .Process(_ => steps.Add("last"))); var producer = await Start(context, "direct://continued-twice"); await producer.Process(new Exchange(new Message("x"))); steps.Should().Equal("handler", "handler", "last"); } } Path: redb-route/tests/redb.Route.Tests/Processors/OnExceptionProcessorTests.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/Processors/OnExceptionProcessorTests.cs ---- using AwesomeAssertions; using Microsoft.Extensions.Logging; using NSubstitute; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Definitions; using redb.Route.Processors; namespace redb.Route.Tests.Processors; /// Tests for . public class OnExceptionProcessorTests { /// Body executes normally when no exception. [Fact] public async Task Process_NoException_BodyExecutes() { var executed = false; var processor = new OnExceptionProcessor( new DelegateProcessor(_ => executed = true)); await processor.Process(new Exchange()); executed.Should().BeTrue(); } /// Matching handler is invoked on exception. [Fact] public async Task Process_MatchingHandler_Invoked() { var handled = false; var processor = new OnExceptionProcessor( new DelegateProcessor(_ => throw new InvalidOperationException("boom"))) .Handle(new DelegateProcessor(ex => { handled = true; ex.Exception.Should().BeOfType(); })); var exchange = new Exchange(); await processor.Process(exchange); handled.Should().BeTrue(); // handled:false (default) — the handler ran but the failure is NOT suppressed (Camel handled(false)), // so the consumer (which checks Exception != null && !ExceptionHandled) still sees the failure. exchange.ExceptionHandled.Should().BeFalse(); exchange.Exception.Should().NotBeNull(); } /// No matching handler — exception rethrows. [Fact] public async Task Process_NoMatchingHandler_Rethrows() { var processor = new OnExceptionProcessor( new DelegateProcessor(_ => throw new InvalidOperationException())) .Handle(new DelegateProcessor(_ => { })); var act = () => processor.Process(new Exchange()); await act.Should().ThrowAsync(); } /// Most-specific handler wins regardless of declaration order (Camel: nearest supertype). [Fact] public async Task Process_MostSpecificHandler_WinsRegardlessOfOrder() { string? picked = null; var processor = new OnExceptionProcessor( new DelegateProcessor(_ => throw new InvalidOperationException("boom"))) // General handler declared FIRST, specific one SECOND — specificity must win, not order. .Handle(new DelegateProcessor(_ => picked = "general"), handled: true) .Handle(new DelegateProcessor(_ => picked = "specific"), handled: true); await processor.Process(new Exchange()); picked.Should().Be("specific", "the most-derived matching handler must win even when declared after the general one"); } /// Redelivery retries before invoking handler. [Fact] public async Task Process_Redelivery_RetriesBeforeHandler() { var attempts = 0; var body = new DelegateProcessor(_ => { attempts++; throw new InvalidOperationException($"attempt {attempts}"); }); var handled = false; var processor = new OnExceptionProcessor(body, Substitute.For()) .Handle( new DelegateProcessor(_ => handled = true), maxRedeliveries: 2); await processor.Process(new Exchange()); attempts.Should().Be(3); // 1 original + 2 redeliveries handled.Should().BeTrue(); } /// A genuine cancellation is never caught — the caller's token is what makes it one. [Fact] public async Task Process_CallerCancellation_NeverCaught() { using var cts = new CancellationTokenSource(); cts.Cancel(); var processor = new OnExceptionProcessor( new DelegateProcessor(_ => throw new OperationCanceledException())) .Handle(new DelegateProcessor(_ => { })); var act = () => processor.Process(new Exchange(), cts.Token); await act.Should().ThrowAsync(); } /// A downstream timeout (an OperationCanceledException with our token still live) is named a /// TimeoutException and reaches the handler. [Fact] public async Task Process_Timeout_HandledAsTimeoutException() { var handled = false; var processor = new OnExceptionProcessor( new DelegateProcessor(_ => throw new TaskCanceledException("downstream deadline"))) .Handle(new DelegateProcessor(_ => handled = true), handled: true); var exchange = new Exchange(); await processor.Process(exchange); handled.Should().BeTrue(); exchange.ExceptionHandled.Should().BeTrue(); } /// Handlers property returns registered handlers. [Fact] public void Handlers_ReturnsRegistered() { var processor = new OnExceptionProcessor(new DelegateProcessor(_ => { })) .Handle(new DelegateProcessor(_ => { })) .Handle(new DelegateProcessor(_ => { })); processor.Handlers.Should().HaveCount(2); } // ── Handled flag ── [Fact] public async Task Handled_ClearsExceptionOnExchange() { var processor = new OnExceptionProcessor( new DelegateProcessor(_ => throw new InvalidOperationException("boom"))) .Handle(new DelegateProcessor(_ => { }), handled: true); var exchange = new Exchange(); await processor.Process(exchange); exchange.ExceptionHandled.Should().BeTrue(); exchange.Exception.Should().BeNull("Handled flag should clear the exception"); } [Fact] public async Task Handled_False_ExceptionRemainsOnExchange() { var processor = new OnExceptionProcessor( new DelegateProcessor(_ => throw new InvalidOperationException("boom"))) .Handle(new DelegateProcessor(_ => { }), handled: false); var exchange = new Exchange(); await processor.Process(exchange); exchange.ExceptionHandled.Should().BeFalse("Handled=false must not suppress the failure (Camel handled(false))"); exchange.Exception.Should().NotBeNull("Handled=false should keep exception on exchange"); } // ── Continued flag ── [Fact] public async Task Continued_SetsExceptionHandled() { var processor = new OnExceptionProcessor( new DelegateProcessor(_ => throw new InvalidOperationException("boom"))) .Handle(new DelegateProcessor(_ => { }), continued: true); var exchange = new Exchange(); await processor.Process(exchange); exchange.ExceptionHandled.Should().BeTrue(); exchange.Exception.Should().BeNull("Continued suppresses the exception and resumes routing"); } // ── OnWhen predicate ── [Fact] public async Task OnWhen_True_HandlerFires() { var handled = false; var processor = new OnExceptionProcessor( new DelegateProcessor(_ => throw new InvalidOperationException("boom"))) .Handle(new DelegateProcessor(_ => handled = true), onWhenPredicate: ex => ex.Exception?.Message == "boom"); await processor.Process(new Exchange()); handled.Should().BeTrue(); } [Fact] public async Task OnWhen_False_HandlerSkipped_ExceptionRethrown() { var processor = new OnExceptionProcessor( new DelegateProcessor(_ => throw new InvalidOperationException("boom"))) .Handle(new DelegateProcessor(_ => { }), onWhenPredicate: _ => false); var act = () => processor.Process(new Exchange()); await act.Should().ThrowAsync(); } // ── OnExceptionOccurred callback ── [Fact] public async Task OnExceptionOccurred_CalledOnEachException() { var callbackCount = 0; var attempts = 0; var processor = new OnExceptionProcessor( new DelegateProcessor(_ => { attempts++; throw new InvalidOperationException(); })) .Handle(new DelegateProcessor(_ => { }), maxRedeliveries: 2, onExceptionOccurred: _ => callbackCount++); await processor.Process(new Exchange()); callbackCount.Should().Be(3, "callback fires on each exception (1 original + 2 retries)"); } // ── RetryAttemptedLogLevel / RetriesExhaustedLogLevel ── [Fact] public async Task CustomLogLevels_AreRespected() { var attempts = 0; var body = new DelegateProcessor(_ => { attempts++; throw new InvalidOperationException($"attempt {attempts}"); }); // This test verifies the handler can be created with custom log levels without error var processor = new OnExceptionProcessor(body) .Handle( new DelegateProcessor(_ => { }), maxRedeliveries: 1, retryAttemptedLogLevel: LogLevel.Debug, retriesExhaustedLogLevel: LogLevel.Critical); var exchange = new Exchange(); await processor.Process(exchange); attempts.Should().Be(2); // 1 original + 1 retry // handler is handled:false — after retries are exhausted the failure is not suppressed. exchange.ExceptionHandled.Should().BeFalse(); } // ── DSL integration: fluent chain scope ── [Fact] public async Task DslScope_Handled_ClearsException() { var context = new RouteContext(); object? captured = null; context.AddRoutes(r => { r.From("direct://oe-handled") .OnException() .Handled() .Log("Handled!") .End() .Process(_ => throw new InvalidOperationException("test")) .Process(e => captured = "should-not-reach"); }); await context.Start(); try { var producer = context.GetEndpoint("direct://oe-handled").CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("data")); await producer.Process(exchange); exchange.ExceptionHandled.Should().BeTrue(); exchange.Exception.Should().BeNull(); } finally { await context.Stop(); } } [Fact] public async Task DslScope_OnWhen_FiltersHandler() { var fallbackReached = false; var context = new RouteContext(); context.AddRoutes(r => { r.From("direct://oe-onwhen") .OnException() .OnWhen(e => e.Exception?.Message == "expected") .Handled() .Process(_ => fallbackReached = true) .End() .Process(_ => throw new InvalidOperationException("expected")); }); await context.Start(); try { var producer = context.GetEndpoint("direct://oe-onwhen").CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("data")); await producer.Process(exchange); fallbackReached.Should().BeTrue(); exchange.ExceptionHandled.Should().BeTrue(); } finally { await context.Stop(); } } [Fact] public async Task DslScope_OnExceptionOccurred_CallbackInvoked() { var callbackCount = 0; var context = new RouteContext(); context.AddRoutes(r => { r.From("direct://oe-callback") .OnException() .Handled() .MaximumRedeliveries(1) .RedeliveryDelay(TimeSpan.FromMilliseconds(1)) .OnExceptionOccurred(_ => callbackCount++) .End() .Process(_ => throw new InvalidOperationException("test")); }); await context.Start(); try { var producer = context.GetEndpoint("direct://oe-callback").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("data"))); callbackCount.Should().Be(2, "callback fires on original + 1 retry"); } finally { await context.Stop(); } } [Fact] public async Task DslScope_RetryLogLevels_Configurable() { var context = new RouteContext(); context.AddRoutes(r => { r.From("direct://oe-loglevels") .OnException() .Handled() .MaximumRedeliveries(1) .RedeliveryDelay(TimeSpan.FromMilliseconds(1)) .RetryAttemptedLogLevel(LogLevel.Debug) .RetriesExhaustedLogLevel(LogLevel.Critical) .End() .Process(_ => throw new InvalidOperationException("test")); }); await context.Start(); try { var producer = context.GetEndpoint("direct://oe-loglevels").CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("data")); await producer.Process(exchange); // Simply verifies that custom log levels don't break anything exchange.ExceptionHandled.Should().BeTrue(); } finally { await context.Stop(); } } [Fact] public void DslScope_HandledOutsideScope_Throws() { var def = new RouteDefinition(); var act = () => def.Handled(); act.Should().Throw() .WithMessage("*OnException*"); } [Fact] public void DslScope_ContinuedOutsideScope_Throws() { var def = new RouteDefinition(); var act = () => def.Continued(); act.Should().Throw() .WithMessage("*OnException*"); } [Fact] public void DslScope_OnWhenOutsideScope_Throws() { var def = new RouteDefinition(); var act = () => def.OnWhen(_ => true); act.Should().Throw() .WithMessage("*OnException*"); } // ── B3: RetryWhile predicate ── [Fact] public async Task RetryWhile_ContinuesWhileTrue() { var attempts = 0; var body = new DelegateProcessor(_ => { attempts++; throw new InvalidOperationException($"attempt {attempts}"); }); var processor = new OnExceptionProcessor(body, Substitute.For()) .Handle( new DelegateProcessor(_ => { }), handled: true, retryWhile: ex => attempts < 4, // retry while attempts < 4 redeliveryDelay: TimeSpan.FromMilliseconds(1)); await processor.Process(new Exchange()); attempts.Should().Be(4, "RetryWhile should keep retrying until predicate returns false"); } [Fact] public async Task RetryWhile_OverridesMaxRedeliveries() { var attempts = 0; var body = new DelegateProcessor(_ => { attempts++; throw new InvalidOperationException(); }); // MaxRedeliveries=1 but RetryWhile says keep going until 5 var processor = new OnExceptionProcessor(body, Substitute.For()) .Handle( new DelegateProcessor(_ => { }), handled: true, maxRedeliveries: 1, retryWhile: _ => attempts < 5, redeliveryDelay: TimeSpan.FromMilliseconds(1)); await processor.Process(new Exchange()); attempts.Should().Be(5, "RetryWhile takes priority over MaxRedeliveries"); } // ── B4: OnRedelivery callback ── [Fact] public async Task OnRedelivery_CalledBeforeEachRetry() { var redeliveryCalls = 0; var attempts = 0; var body = new DelegateProcessor(_ => { attempts++; throw new InvalidOperationException(); }); var processor = new OnExceptionProcessor(body, Substitute.For()) .Handle( new DelegateProcessor(_ => { }), handled: true, maxRedeliveries: 3, redeliveryDelay: TimeSpan.FromMilliseconds(1), onRedelivery: _ => redeliveryCalls++); await processor.Process(new Exchange()); redeliveryCalls.Should().Be(3, "OnRedelivery fires before each of the 3 retries"); } // ── B5: OnPrepareFailure callback ── [Fact] public async Task OnPrepareFailure_CalledBeforeHandler() { var prepareCalled = false; var body = new DelegateProcessor(_ => throw new InvalidOperationException()); var processor = new OnExceptionProcessor(body) .Handle( new DelegateProcessor(_ => { }), handled: true, onPrepareFailure: ex => { prepareCalled = true; ex.In.Headers["PreparedForFailure"] = true; }); var exchange = new Exchange(); await processor.Process(exchange); prepareCalled.Should().BeTrue(); exchange.In.Headers.Should().ContainKey("PreparedForFailure"); } // ── B6: UseOriginalMessage / UseOriginalBody ── [Fact] public async Task UseOriginalBody_RestoresBodyBeforeHandler() { var body = new DelegateProcessor(ex => { ex.In.Body = "mutated"; throw new InvalidOperationException(); }); object? handlerBody = null; var processor = new OnExceptionProcessor(body) .Handle( new DelegateProcessor(ex => handlerBody = ex.In.Body), handled: true, useOriginalBody: true); var exchange = new Exchange(new Message("original")); await processor.Process(exchange); handlerBody.Should().Be("original", "UseOriginalBody should restore body before handler"); } [Fact] public async Task UseOriginalMessage_RestoresBodyAndHeaders() { var body = new DelegateProcessor(ex => { ex.In.Body = "mutated"; ex.In.Headers["NewHeader"] = "added"; throw new InvalidOperationException(); }); object? handlerBody = null; bool? hasNewHeader = null; var processor = new OnExceptionProcessor(body) .Handle( new DelegateProcessor(ex => { handlerBody = ex.In.Body; hasNewHeader = ex.In.Headers.ContainsKey("NewHeader"); }), handled: true, useOriginalMessage: true); var exchange = new Exchange(new Message("original")); exchange.In.Headers["OriginalHeader"] = "kept"; await processor.Process(exchange); handlerBody.Should().Be("original"); hasNewHeader.Should().BeFalse("UseOriginalMessage should restore original headers, removing added ones"); } // ── B7: AllowRedeliveryWhileStopping ── [Fact] public async Task AllowRedeliveryWhileStopping_False_StopsRetryOnCancellation() { var attempts = 0; var cts = new CancellationTokenSource(); var body = new DelegateProcessor(_ => { attempts++; if (attempts == 1) cts.Cancel(); // cancel after first attempt throw new InvalidOperationException(); }); var handlerCalled = false; var processor = new OnExceptionProcessor(body, Substitute.For()) .Handle( new DelegateProcessor(_ => handlerCalled = true), handled: true, maxRedeliveries: 5, redeliveryDelay: TimeSpan.FromMilliseconds(1), allowRedeliveryWhileStopping: false); // The cts.Cancel() triggers OperationCanceledException in Task.Delay // But since AllowRedeliveryWhileStopping=false, shouldRetry becomes false, // so it goes to exhaustion path (handler should fire) await processor.Process(new Exchange(), cts.Token); attempts.Should().Be(1, "should stop retrying after cancellation"); handlerCalled.Should().BeTrue("handler fires after retries are refused"); } // ── B8: LogStackTrace / LogExhausted ── [Fact] public async Task LogExhausted_False_SuppressesExhaustionLog() { var logger = Substitute.For(); var body = new DelegateProcessor(_ => throw new InvalidOperationException()); var processor = new OnExceptionProcessor(body, logger) .Handle( new DelegateProcessor(_ => { }), handled: true, maxRedeliveries: 1, redeliveryDelay: TimeSpan.FromMilliseconds(1), logExhausted: false); await processor.Process(new Exchange()); // Logger should NOT receive an Error-level "Retries exhausted" message // (it may still receive Warning-level retry attempt messages) logger.ReceivedCalls() .Where(c => c.GetMethodInfo().Name == "Log") .SelectMany(c => c.GetArguments()) .OfType() .Should().NotContain(LogLevel.Error); } // ── LogHandled / LogContinued (Camel's logHandled / logContinued) ── /// The argument list of every Log call a substitute logger received. private static IReadOnlyList Logged(ILogger logger) => [.. logger.ReceivedCalls() .Where(c => c.GetMethodInfo().Name == "Log") .Select(c => c.GetArguments())]; /// The argument list of every Error-level Log call. private static IReadOnlyList LoggedErrors(ILogger logger) => [.. Logged(logger).Where(a => a[0] is LogLevel.Error)]; /// The exception each Error-level call handed to the logger (the fourth argument of ILogger.Log). private static IReadOnlyList LoggedErrorsWithStack(ILogger logger) => [.. LoggedErrors(logger).Select(a => a[3] as Exception)]; [Fact] public async Task HandledFailure_NotLogged_ByDefault() { var logger = Substitute.For(); var body = new DelegateProcessor(_ => throw new InvalidOperationException("handled")); var processor = new OnExceptionProcessor(body, logger) .Handle(new DelegateProcessor(_ => { }), handled: true); var exchange = new Exchange(); await processor.Process(exchange); exchange.ExceptionHandled.Should().BeTrue(); LoggedErrors(logger).Should().BeEmpty( "the handler answered the exchange: an Error entry with the stack is noise (Camel's logHandled=false)"); } [Fact] public async Task HandledFailure_Logged_WhenLogHandled() { var logger = Substitute.For(); var failure = new InvalidOperationException("handled and logged"); var body = new DelegateProcessor(_ => throw failure); var processor = new OnExceptionProcessor(body, logger) .Handle(new DelegateProcessor(_ => { }), handled: true, logHandled: true); await processor.Process(new Exchange()); LoggedErrorsWithStack(logger).Should().Contain(failure, "LogHandled(true) asks for the entry"); } [Fact] public async Task ContinuedFailure_NotLogged_ByDefault() { var logger = Substitute.For(); var body = new DelegateProcessor(_ => throw new InvalidOperationException("continued")); var processor = new OnExceptionProcessor(body, logger) .Handle(new DelegateProcessor(_ => { }), continued: true); var exchange = new Exchange(); await processor.Process(exchange); exchange.ExceptionHandled.Should().BeTrue(); LoggedErrors(logger).Should().BeEmpty( "Camel's logContinued=false keeps a continued failure out of the log"); } [Fact] public async Task ContinuedFailure_Logged_WhenLogContinued() { var logger = Substitute.For(); var failure = new InvalidOperationException("continued and logged"); var body = new DelegateProcessor(_ => throw failure); var processor = new OnExceptionProcessor(body, logger) .Handle(new DelegateProcessor(_ => { }), continued: true, logContinued: true); await processor.Process(new Exchange()); LoggedErrorsWithStack(logger).Should().Contain(failure, "LogContinued(true) asks for the entry"); } [Fact] public async Task HandledFailure_OnRollbackOnlyExchange_IsLogged() { var logger = Substitute.For(); var failure = new InvalidOperationException("the work was rolled back"); var body = new DelegateProcessor(ex => { ex.MarkRollbackOnly(); throw failure; }); var processor = new OnExceptionProcessor(body, logger) .Handle(new DelegateProcessor(_ => { }), handled: true); await processor.Process(new Exchange()); LoggedErrorsWithStack(logger).Should().Contain(failure, "a rollback-only exchange lost its work, so the entry is worth having even though the handler answered"); } [Fact] public async Task UnhandledFailure_StillLogged() { var logger = Substitute.For(); var failure = new InvalidOperationException("nobody handled this"); var body = new DelegateProcessor(_ => throw failure); var processor = new OnExceptionProcessor(body, logger) .Handle(new DelegateProcessor(_ => { })); await processor.Process(new Exchange()); LoggedErrorsWithStack(logger).Should().Contain(failure, "an unhandled failure is logged exactly as before"); } // ── B10: Exchange redelivery headers ── [Fact] public async Task RedeliveryHeaders_SetDuringRetries() { var headers = new Dictionary(); var attempts = 0; var body = new DelegateProcessor(ex => { attempts++; if (attempts <= 2) throw new InvalidOperationException(); }); var processor = new OnExceptionProcessor(body, Substitute.For()) .Handle( new DelegateProcessor(ex => { // Capture headers at handler time (after exhaustion) foreach (var h in ex.In.Headers) headers[h.Key] = h.Value; }), handled: true, maxRedeliveries: 1, redeliveryDelay: TimeSpan.FromMilliseconds(1)); var exchange = new Exchange(); await processor.Process(exchange); exchange.In.Headers.Should().ContainKey("CamelRedelivered"); exchange.In.Headers.Should().ContainKey("CamelRedeliveryExhausted"); exchange.In.Headers["CamelRedeliveryExhausted"].Should().Be(true); } [Fact] public async Task RedeliveryHeaders_NotSetWhenNoRetries() { var body = new DelegateProcessor(_ => throw new InvalidOperationException()); var processor = new OnExceptionProcessor(body) .Handle( new DelegateProcessor(_ => { }), handled: true, maxRedeliveries: 0); var exchange = new Exchange(); await processor.Process(exchange); // CamelRedelivered is set but is false (no actual redelivery happened) exchange.In.Headers["CamelRedelivered"].Should().Be(false); } // ── DSL integration for new features ── [Fact] public async Task Dsl_RetryWhile_WorksInFluent() { var attempts = 0; var context = new RouteContext(); context.AddRoutes(r => { r.From("direct://oe-retrywhile") .OnException() .Handled() .RetryWhile(_ => attempts < 3) .RedeliveryDelay(TimeSpan.FromMilliseconds(1)) .End() .Process(_ => { attempts++; throw new InvalidOperationException(); }); }); await context.Start(); try { var producer = context.GetEndpoint("direct://oe-retrywhile").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("data"))); attempts.Should().Be(3); } finally { await context.Stop(); } } [Fact] public async Task Dsl_UseOriginalBody_WorksInFluent() { object? handlerBody = null; var context = new RouteContext(); context.AddRoutes(r => { r.From("direct://oe-origbody") .OnException() .Handled() .UseOriginalBody() .Process(ex => handlerBody = ex.In.Body) .End() .Process(ex => { ex.In.Body = "mutated"; throw new InvalidOperationException(); }); }); await context.Start(); try { var producer = context.GetEndpoint("direct://oe-origbody").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("original"))); handlerBody.Should().Be("original"); } finally { await context.Stop(); } } [Fact] public async Task Dsl_OnRedelivery_WorksInFluent() { var redeliveryCount = 0; var context = new RouteContext(); context.AddRoutes(r => { r.From("direct://oe-onredeliver") .OnException() .Handled() .MaximumRedeliveries(2) .RedeliveryDelay(TimeSpan.FromMilliseconds(1)) .OnRedelivery(_ => redeliveryCount++) .End() .Process(_ => throw new InvalidOperationException()); }); await context.Start(); try { var producer = context.GetEndpoint("direct://oe-onredeliver").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("data"))); redeliveryCount.Should().Be(2); } finally { await context.Stop(); } } [Fact] public async Task Dsl_OnPrepareFailure_WorksInFluent() { var prepared = false; var context = new RouteContext(); context.AddRoutes(r => { r.From("direct://oe-prepfail") .OnException() .Handled() .OnPrepareFailure(_ => prepared = true) .End() .Process(_ => throw new InvalidOperationException()); }); await context.Start(); try { var producer = context.GetEndpoint("direct://oe-prepfail").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("data"))); prepared.Should().BeTrue(); } finally { await context.Stop(); } } } Path: redb-route/tests/redb.Route.Tests/Processors/OwnedPropertiesMergeBackTests.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/Processors/OwnedPropertiesMergeBackTests.cs ---- using AwesomeAssertions; using Microsoft.Extensions.DependencyInjection; using redb.Route.Abstractions; using redb.Route.Components; using redb.Route.Core; using redb.Route.Processors; namespace redb.Route.Tests.Processors; /// /// The exchange's own bookkeeping — a cached named DI scope (__redb_scope:*) or a registered resource /// (__redb_resource:*) — belongs to the exchange that created it. A branch that caches a scope on its clone /// must not hand that scope to the original through the aggregation merge-back: the clone releases it right after, /// and the original would keep a disposed scope under the same key (ObjectDisposedException on the next use). /// public class OwnedPropertiesMergeBackTests { private const string ScopeKey = "__redb_scope:audit"; private sealed class TrackingScope : IServiceScope, IAsyncDisposable { public int DisposeCount; public IServiceProvider ServiceProvider => null!; public void Dispose() => Interlocked.Increment(ref DisposeCount); public ValueTask DisposeAsync() { Interlocked.Increment(ref DisposeCount); return ValueTask.CompletedTask; } } [Fact] public async Task Multicast_BranchScope_StaysWithTheClone() { var scope = new TrackingScope(); var multicast = new MulticastProcessor(parallelProcessing: false, aggregationStrategy: (_, latest) => latest) .AddTarget(new DelegateProcessor(ex => ex.Properties[ScopeKey] = scope)); var original = new Exchange(new Message("m")); await multicast.Process(original); original.Properties.Should().NotContainKey(ScopeKey, "the clone owns the scope it cached and has released it"); scope.DisposeCount.Should().Be(1, "released once, with the clone"); } [Fact] public async Task Loop_IterationScope_StaysWithTheIterationCopy() { var scope = new TrackingScope(); var loop = new LoopProcessor(new DelegateProcessor(ex => ex.Properties[ScopeKey] = scope), 1, copy: true); var original = new Exchange(new Message("m")); await loop.Process(original); original.Properties.Should().NotContainKey(ScopeKey, "the iteration copy owns the scope it cached and has released it"); scope.DisposeCount.Should().Be(1, "released once, with the iteration copy"); } [Fact] public async Task Splitter_PartScope_StaysWithThePart() { var scope = new TrackingScope(); var splitter = new SplitterProcessor( ex => (IEnumerable)ex.In.Body!, new DelegateProcessor(ex => ex.Properties[ScopeKey] = scope), aggregationStrategy: (_, part) => part); var original = new Exchange(new Message(new List { "a" })); await splitter.Process(original); original.Properties.Should().NotContainKey(ScopeKey, "the part owns the scope it cached and has released it"); scope.DisposeCount.Should().Be(1, "released once, with the part"); } [Fact] public async Task ScatterGather_RecipientScope_StaysWithTheClone() { var scope = new TrackingScope(); var context = new RouteContext(); var consumers = new List(); foreach (var name in new[] { "direct:owned-sg-a", "direct:owned-sg-b" }) { var consumer = ((DirectEndpoint)context.GetEndpoint(name)).CreateConsumer(new DelegateProcessor(ex => ex.In.Headers["seen"] = true)); await consumer.Start(); consumers.Add(consumer); } try { // A recipient runs on a child exchange (its scopes stay there); the aggregation strategy runs on the // scatter clone itself and may touch redb — that scope must not reach the original either. var sg = new ScatterGatherProcessor(context, ["direct:owned-sg-a", "direct:owned-sg-b"], (_, latest) => { latest.Properties[ScopeKey] = scope; return latest; }); var original = new Exchange(new Message("m")); await sg.Process(original); original.Properties.Should().NotContainKey(ScopeKey, "the recipient clone owns the scope it cached and has released it"); scope.DisposeCount.Should().Be(1, "released once, with the recipient clone"); } finally { foreach (var consumer in consumers) await consumer.Stop(); await context.DisposeAsync(); } } } Path: redb-route/tests/redb.Route.Tests/Processors/ParallelFanOutTransactionTests.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/Processors/ParallelFanOutTransactionTests.cs ---- using System.Collections.Concurrent; using System.Transactions; using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Transactions; namespace redb.Route.Tests.Processors; /// /// A parallel scatter-gather or recipient list inside .Transacted() follows the rule of every parallel fan-out /// ( for Multicast and Split): each branch runs under a dependent clone /// of the route's transaction, never the transaction itself, and a branch that fails rolls the whole block back, in /// best-effort mode too, so the deferred sends of the other branches never go out. /// public sealed class ParallelFanOutTransactionTests { private sealed record Seen(Transaction? Transaction, string Kind); /// /// Runs a transacted direct:in whose fan-out sends to two direct:branch routes held in flight together. /// private static async Task<(Transaction? Parent, Seen[] Branches)> RunConcurrent( Func fanOut) { await using var ctx = new RouteContext("fanout-tx-" + Guid.NewGuid().ToString("N")); var seen = new ConcurrentQueue(); Transaction? parent = null; using var bothIn = new CountdownEvent(2); ctx.AddRoutes(r => { fanOut(r.From("direct:in").Transacted().Process(_ => parent = Transaction.Current)).EndTransaction(); r.From("direct:branch").Process(async (_, ct) => { var current = Transaction.Current; seen.Enqueue(new Seen(current, current?.GetType().Name ?? "(none)")); bothIn.Signal(); // Both branches are inside their step at once: the fan-out really runs them in parallel. await Task.Run(() => bothIn.Wait(TimeSpan.FromSeconds(10)), ct); }); }); await ctx.Start(); using var producer = new ProducerTemplate(ctx); producer.Start(); await producer.SendAsync("direct:in", "x"); return (parent, seen.ToArray()); } private static void EachBranchUnderADependentClone(Transaction? parent, Seen[] branches) { parent.Should().NotBeNull(); branches.Should().HaveCount(2); branches.Should().OnlyContain(b => b.Kind == nameof(DependentTransaction), "concurrent branches never share one Transaction.Current"); branches.Should().OnlyContain(b => !ReferenceEquals(b.Transaction, parent)); } [Fact] public async Task Parallel_scatter_gather_branches_run_under_dependent_clones() { var (parent, branches) = await RunConcurrent(r => r.ScatterGather(sg => sg .Recipients("direct:branch", "direct:branch") .AggregationStrategy((a, b) => b) .ParallelProcessing())); EachBranchUnderADependentClone(parent, branches); } [Fact] public async Task Parallel_recipient_list_branches_run_under_dependent_clones() { var (parent, branches) = await RunConcurrent(r => r.RecipientList(_ => ["direct:branch", "direct:branch"], parallelProcessing: true)); EachBranchUnderADependentClone(parent, branches); } /// /// A transacted direct:in fanning out in best-effort mode to direct:ok, which defers a send to the block, /// and direct:fail, which throws. Returns whether the deferred send went out, the outcome of the route's /// transaction and what the caller saw. /// private static async Task<(bool Sent, TransactionStatus? Outcome, Exception? Failure)> RunWithAFailedBranch( Func fanOut) { await using var ctx = new RouteContext("fanout-tx-" + Guid.NewGuid().ToString("N")); var sent = false; TransactionStatus? outcome = null; ctx.AddRoutes(r => { fanOut(r.From("direct:in").Transacted().Process(_ => Transaction.Current!.TransactionCompleted += (_, e) => outcome = e.Transaction!.TransactionInformation.Status)) .EndTransaction(); r.From("direct:ok").Process(ex => TransactedActions.RegisterSend(ex, "ok-send", _ => { sent = true; return Task.CompletedTask; }, "test")); r.From("direct:fail").Process(_ => throw new InvalidOperationException("branch failed")); }); await ctx.Start(); using var producer = new ProducerTemplate(ctx); producer.Start(); Exception? failure = null; try { await producer.SendAsync("direct:in", "x"); } catch (Exception ex) { failure = ex; } return (sent, outcome, failure); } [Fact] public async Task A_failed_scatter_gather_branch_rolls_the_block_back_in_best_effort_mode() { var (sent, outcome, failure) = await RunWithAFailedBranch(r => r.ScatterGather(sg => sg .Recipients("direct:ok", "direct:fail") .AggregationStrategy((a, b) => b) .ParallelProcessing() .StopOnException(false))); sent.Should().BeFalse("the deferred send of the branch that succeeded is dropped with the block"); outcome.Should().Be(TransactionStatus.Aborted); failure.Should().NotBeNull("the block could not commit"); } [Fact] public async Task A_sequential_fan_out_in_best_effort_mode_still_commits_after_a_failed_branch() { // UPGRADING's way back to the old outcome: sequential branches run on the route's transaction and are not isolated. var (sgSent, sgOutcome, sgFailure) = await RunWithAFailedBranch(r => r.ScatterGather(sg => sg .Recipients("direct:ok", "direct:fail") .AggregationStrategy((a, b) => b) .ParallelProcessing(false) .StopOnException(false))); var (rlSent, rlOutcome, rlFailure) = await RunWithAFailedBranch(r => r.RecipientList(_ => ["direct:ok", "direct:fail"], parallelProcessing: false, stopOnException: false)); (sgSent, sgOutcome, sgFailure).Should().Be((true, TransactionStatus.Committed, (Exception?)null)); (rlSent, rlOutcome, rlFailure).Should().Be((true, TransactionStatus.Committed, (Exception?)null)); } [Fact] public async Task A_failed_recipient_list_branch_rolls_the_block_back_in_best_effort_mode() { var (sent, outcome, failure) = await RunWithAFailedBranch(r => r.RecipientList(_ => ["direct:ok", "direct:fail"], parallelProcessing: true, stopOnException: false)); sent.Should().BeFalse("the deferred send of the branch that succeeded is dropped with the block"); outcome.Should().Be(TransactionStatus.Aborted); failure.Should().NotBeNull("the block could not commit"); } } Path: redb-route/tests/redb.Route.Tests/Processors/ParallelTransactionIsolationTests.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/Processors/ParallelTransactionIsolationTests.cs ---- using System.Collections.Concurrent; using System.Transactions; using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Processors; namespace redb.Route.Tests.Processors; /// /// Verifies that parallel Splitter / Multicast branches run under a private /// clone of the ambient transaction instead of sharing one /// across threads (which System.Transactions forbids). /// public class ParallelTransactionIsolationTests { [Fact] public async Task Multicast_Parallel_InsideTransaction_EachBranchUnderDependentClone() { var kinds = new ConcurrentBag(); var multicast = new MulticastProcessor(parallelProcessing: true) .AddTarget(new DelegateProcessor(_ => kinds.Add(TxKind()))) .AddTarget(new DelegateProcessor(_ => kinds.Add(TxKind()))) .AddTarget(new DelegateProcessor(_ => kinds.Add(TxKind()))); using (var scope = new TransactionScope( TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Enabled)) { await multicast.Process(new Exchange(new Message("data"))); scope.Complete(); // must not throw / block — all dependents already signalled Complete() } kinds.Should().HaveCount(3); kinds.Should().OnlyContain(k => k == nameof(DependentTransaction)); } [Fact] public async Task Splitter_Parallel_InsideTransaction_EachBranchUnderDependentClone() { var kinds = new ConcurrentBag(); var splitter = new SplitterProcessor( ex => (IEnumerable)ex.In.Body!, new DelegateProcessor(_ => kinds.Add(TxKind())), parallelProcessing: true, stopOnException: false); using (var scope = new TransactionScope( TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Enabled)) { await splitter.Process(new Exchange(new Message(new object[] { "a", "b", "c", "d" }))); scope.Complete(); } kinds.Should().HaveCount(4); kinds.Should().OnlyContain(k => k == nameof(DependentTransaction)); } [Fact] public async Task Multicast_Parallel_NoAmbientTransaction_IsPassthrough() { var sawTransaction = new ConcurrentBag(); var multicast = new MulticastProcessor(parallelProcessing: true) .AddTarget(new DelegateProcessor(_ => sawTransaction.Add(Transaction.Current != null))) .AddTarget(new DelegateProcessor(_ => sawTransaction.Add(Transaction.Current != null))); await multicast.Process(new Exchange(new Message("data"))); sawTransaction.Should().HaveCount(2); sawTransaction.Should().OnlyContain(seen => seen == false); // no scope created when no ambient TX } private static string TxKind() => Transaction.Current?.GetType().Name ?? "(none)"; } Path: redb-route/tests/redb.Route.Tests/Processors/PipelineProcessorTests.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/Processors/PipelineProcessorTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Processors; namespace redb.Route.Tests.Processors; /// Tests for . public class PipelineProcessorTests { /// Processors execute in order. [Fact] public async Task Process_ExecutesInOrder() { var order = new List(); var pipeline = new PipelineProcessor(); pipeline.Add(new DelegateProcessor(_ => order.Add(1))); pipeline.Add(new DelegateProcessor(_ => order.Add(2))); pipeline.Add(new DelegateProcessor(_ => order.Add(3))); await pipeline.Process(new Exchange()); order.Should().Equal(1, 2, 3); } /// Empty pipeline completes without error. [Fact] public async Task Process_EmptyPipeline_Succeeds() { var pipeline = new PipelineProcessor(); var exchange = new Exchange(); await pipeline.Process(exchange); exchange.IsStopped.Should().BeFalse(); } /// Stops when exchange.Stop() is called. [Fact] public async Task Process_StoppedExchange_BreaksEarly() { var order = new List(); var pipeline = new PipelineProcessor(); pipeline.Add(new DelegateProcessor(ex => { order.Add(1); ex.Stop(); })); pipeline.Add(new DelegateProcessor(_ => order.Add(2))); await pipeline.Process(new Exchange()); order.Should().Equal(1); } /// Respects CancellationToken — throws on cancellation. [Fact] public async Task Process_CancellationRequested_Throws() { var pipeline = new PipelineProcessor(); pipeline.Add(new DelegateProcessor(_ => { })); using var cts = new CancellationTokenSource(); cts.Cancel(); var act = () => pipeline.Process(new Exchange(), cts.Token); await act.Should().ThrowAsync(); } /// AddRange adds multiple processors at once. [Fact] public async Task AddRange_AddsMultiple() { var order = new List(); var pipeline = new PipelineProcessor(); pipeline.AddRange([ new DelegateProcessor(_ => order.Add(1)), new DelegateProcessor(_ => order.Add(2)) ]); await pipeline.Process(new Exchange()); order.Should().Equal(1, 2); pipeline.Processors.Should().HaveCount(2); } /// Exception in a processor propagates. [Fact] public async Task Process_ExceptionPropagates() { var pipeline = new PipelineProcessor(); pipeline.Add(new DelegateProcessor(_ => throw new InvalidOperationException("boom"))); pipeline.Add(new DelegateProcessor(_ => { })); var act = () => pipeline.Process(new Exchange()); await act.Should().ThrowAsync().WithMessage("boom"); } /// Out→In merge copies ContentType. [Fact] public async Task Process_OutToInMerge_CopiesContentType() { var pipeline = new PipelineProcessor(); pipeline.Add(new DelegateProcessor(ex => { var outMsg = new Message("response") { ContentType = "application/xml" }; outMsg.Headers["extra"] = "val"; ex.Out = outMsg; })); // Second processor sees merged In pipeline.Add(new DelegateProcessor(ex => { ex.In.Body.Should().Be("response"); ex.In.ContentType.Should().Be("application/xml"); ex.In.Headers["extra"].Should().Be("val"); ex.HasOut.Should().BeFalse(); })); var exchange = new Exchange(new Message("original") { ContentType = "text/plain" }); await pipeline.Process(exchange); exchange.In.ContentType.Should().Be("application/xml"); } /// Out→In merge keeps In's ContentType when the Out message carries none. [Fact] public async Task Process_OutToInMerge_KeepsContentTypeWhenOutHasNone() { var pipeline = new PipelineProcessor(); pipeline.Add(new DelegateProcessor(ex => ex.Out = new Message("response"))); pipeline.Add(new DelegateProcessor(ex => { ex.In.Body.Should().Be("response"); ex.In.ContentType.Should().Be("text/plain"); })); var exchange = new Exchange(new Message("original") { ContentType = "text/plain" }); await pipeline.Process(exchange); exchange.In.ContentType.Should().Be("text/plain"); } } Path: redb-route/tests/redb.Route.Tests/Processors/RecipientListProcessorTests.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/Processors/RecipientListProcessorTests.cs ---- using AwesomeAssertions; using NSubstitute; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Processors; namespace redb.Route.Tests.Processors; /// Tests for . public class RecipientListProcessorTests { private static (IRouteContext context, Dictionary> received) SetupContext( params string[] uris) { var received = new Dictionary>(); var context = Substitute.For(); foreach (var uri in uris) { received[uri] = []; var capturedUri = uri; var producer = Substitute.For(); producer.When(p => p.Process(Arg.Any(), Arg.Any())) .Do(ci => received[capturedUri].Add(ci.Arg())); var endpoint = Substitute.For(); endpoint.CreateProducer().Returns(producer); context.GetEndpoint(uri).Returns(endpoint); } return (context, received); } [Fact] public async Task Process_Sequential_RoutesToAllRecipients() { var (context, received) = SetupContext("seda://a", "seda://b", "seda://c"); var processor = new RecipientListProcessor( context, _ => new[] { "seda://a", "seda://b", "seda://c" }); await processor.Process(new Exchange(new Message("data"))); received["seda://a"].Should().HaveCount(1); received["seda://b"].Should().HaveCount(1); received["seda://c"].Should().HaveCount(1); } [Fact] public async Task Process_SendsClones_NotOriginal() { var capturedExchanges = new List(); var producer = Substitute.For(); producer.When(p => p.Process(Arg.Any(), Arg.Any())) .Do(ci => capturedExchanges.Add(ci.Arg())); var endpoint = Substitute.For(); endpoint.CreateProducer().Returns(producer); var context = Substitute.For(); context.GetEndpoint("seda://a").Returns(endpoint); var processor = new RecipientListProcessor( context, _ => new[] { "seda://a" }); var original = new Exchange(new Message("original")); await processor.Process(original); capturedExchanges.Should().HaveCount(1); capturedExchanges[0].Should().NotBeSameAs(original); capturedExchanges[0].In.Body.Should().Be("original"); } [Fact] public async Task Process_DynamicUris_ResolvedAtRuntime() { var (context, received) = SetupContext("seda://x", "seda://y"); var processor = new RecipientListProcessor( context, ex => { var header = (string)ex.In.Headers["targets"]!; return header.Split(','); }); var exchange = new Exchange(new Message("data")); exchange.In.Headers["targets"] = "seda://x,seda://y"; await processor.Process(exchange); received["seda://x"].Should().HaveCount(1); received["seda://y"].Should().HaveCount(1); } [Fact] public async Task Process_EmptyList_DoesNothing() { var context = Substitute.For(); var processor = new RecipientListProcessor( context, _ => Enumerable.Empty()); await processor.Process(new Exchange()); // No exception, no calls context.DidNotReceive().GetEndpoint(Arg.Any()); } [Fact] public async Task Process_WithAggregation_MergesResults() { var producer = Substitute.For(); producer.When(p => p.Process(Arg.Any(), Arg.Any())) .Do(ci => { var ex = ci.Arg(); ex.In.Body = (int)ex.In.Body! * 10; }); var endpoint = Substitute.For(); endpoint.CreateProducer().Returns(producer); var context = Substitute.For(); context.GetEndpoint(Arg.Any()).Returns(endpoint); var processor = new RecipientListProcessor( context, _ => new[] { "seda://a", "seda://b" }, aggregationStrategy: (a, b) => { a.In.Body = (int)a.In.Body! + (int)b.In.Body!; return a; }); var exchange = new Exchange(new Message(1)); await processor.Process(exchange); // Each clone gets body=1, producer multiplies by 10 → 10 + 10 = 20 exchange.In.Body.Should().Be(20); } [Fact] public async Task Process_Parallel_AllRecipientsReceive() { var (context, received) = SetupContext("seda://a", "seda://b"); var processor = new RecipientListProcessor( context, _ => new[] { "seda://a", "seda://b" }, parallelProcessing: true); await processor.Process(new Exchange(new Message("parallel"))); received["seda://a"].Should().HaveCount(1); received["seda://b"].Should().HaveCount(1); } [Fact] public async Task Process_Parallel_WithAggregation() { var producer = Substitute.For(); producer.When(p => p.Process(Arg.Any(), Arg.Any())) .Do(ci => ci.Arg().In.Body = 5); var endpoint = Substitute.For(); endpoint.CreateProducer().Returns(producer); var context = Substitute.For(); context.GetEndpoint(Arg.Any()).Returns(endpoint); var processor = new RecipientListProcessor( context, _ => new[] { "seda://a", "seda://b", "seda://c" }, parallelProcessing: true, aggregationStrategy: (a, b) => { a.In.Body = (int)a.In.Body! + (int)b.In.Body!; return a; }); var exchange = new Exchange(new Message(0)); await processor.Process(exchange); exchange.In.Body.Should().Be(15); // 5+5+5 } [Fact] public async Task Process_StopOnException_Sequential_Propagates() { var producer = Substitute.For(); producer.When(p => p.Process(Arg.Any(), Arg.Any())) .Do(_ => throw new InvalidOperationException("fail")); var endpoint = Substitute.For(); endpoint.CreateProducer().Returns(producer); var context = Substitute.For(); context.GetEndpoint(Arg.Any()).Returns(endpoint); var processor = new RecipientListProcessor( context, _ => new[] { "seda://a", "seda://b" }, stopOnException: true); var act = () => processor.Process(new Exchange()); await act.Should().ThrowAsync(); } [Fact] public void Constructor_NullContext_Throws() { var act = () => new RecipientListProcessor(null!, _ => new[] { "a" }); act.Should().Throw().WithParameterName("context"); } [Fact] public void Constructor_NullFactory_Throws() { var act = () => new RecipientListProcessor(Substitute.For(), null!); act.Should().Throw().WithParameterName("recipientListFactory"); } /// Each copy carries the recipient it goes to, as Camel's CamelRecipientListEndpoint. [Theory] [InlineData(false)] [InlineData(true)] public async Task Process_PublishesRecipientListEndpoint(bool parallel) { var (context, received) = SetupContext("seda://a", "seda://b"); var processor = new RecipientListProcessor(context, _ => new[] { "seda://a", "seda://b" }, parallelProcessing: parallel); await processor.Process(new Exchange(new Message("data"))); received["seda://a"].Single().GetProperty(ExchangePropertyKeys.RecipientListEndpoint).Should().Be("seda://a"); received["seda://b"].Single().GetProperty(ExchangePropertyKeys.RecipientListEndpoint).Should().Be("seda://b"); } }