Path: redb-route/tests/redb.Route.Tests.Xml/CatalogContributionsTests.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Xml/CatalogContributionsTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Xml; namespace redb.Route.Tests.Xml; /// A body type for the unmarshal/ofType tests. public class CatalogOrder { public string? Id { get; set; } public int Amount { get; set; } } /// /// Catalog batch: the rest of the element set — leaves, scopes, branch /// children and the schema errors the format promises. Behavioral spot-checks plus one /// anti-drift document that exercises every element at once. /// public class CatalogContributionsTests : 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 void Load(string xml, string? sourceName = null) => _context.AddXmlRoutesFromContent(xml, sourceName ?? ""); // ── behavior ───────────────────────────────────────────────────────────── [Fact] public async Task SetHeaders_MixesConstantsAndExpressions() { Load("""
"""); var producer = await StartAndProducer("direct://cat-sh-in"); var exchange = new Exchange(new Message("x")); await producer.Process(exchange); exchange.In.Headers["fixed"].Should().Be("A"); exchange.In.Headers["derived"].Should().Be("x-tail"); } [Fact] public async Task SetProperties_MixesConstantsAndExpressions_InOrder() { Load(""" """); var producer = await StartAndProducer("direct://cat-sp-in"); var exchange = new Exchange(new Message("x")); await producer.Process(exchange); exchange.Properties["fixed"].Should().Be("A"); exchange.Properties["derived"].Should().Be("x-tail"); exchange.Properties["chained"].Should().Be("A+"); } [Fact] public void SetProperties_AcceptsOnlyPropertyChildren() { var foreignChild = () => Load("""
"""); foreignChild.Should().Throw().WithMessage("* accepts only children*"); } [Fact] public async Task TryCatch_CatchHandles_FinallyAlwaysRuns() { Load(""" """); var producer = await StartAndProducer("direct://cat-tc-in"); var exchange = new Exchange(new Message("x")); await producer.Process(exchange); // Engine semantics: a matched catch marks the exception handled; the record stays. exchange.ExceptionHandled.Should().BeTrue(); exchange.In.Headers["caught"].Should().Be("yes"); exchange.In.Headers["final"].Should().Be("yes"); } [Fact] public async Task Loop_Count_RepeatsTheBody() { var hits = 0; _context.AddRoutes(r => r.From("direct://cat-loop-out").Process(_ => hits++)); Load(""" """); var producer = await StartAndProducer("direct://cat-loop-in"); await producer.Process(new Exchange(new Message("x"))); hits.Should().Be(3); } [Fact] public async Task Aggregate_CompletionSize_WithNamedStrategy_Merges() { object? merged = null; _context.AddRoutes(r => r.From("direct://cat-agg-out").Process(e => merged = e.In.Body)); Load(""" """); var producer = await StartAndProducer("direct://cat-agg-in"); await producer.Process(Msg("a", ("group", "g"))); await producer.Process(Msg("b", ("group", "g"))); merged.Should().Be("a+b"); } [Fact] public async Task Multicast_DeliversToEveryBranchStep() { // Multicast runs its branches in parallel by default — the sink must be thread-safe. var seen = new System.Collections.Concurrent.ConcurrentBag(); _context.AddRoutes(r => { r.From("direct://cat-mc-1").Process(_ => seen.Add("one")); r.From("direct://cat-mc-2").Process(_ => seen.Add("two")); }); Load(""" """); var producer = await StartAndProducer("direct://cat-mc-in"); await producer.Process(new Exchange(new Message("x"))); seen.Should().BeEquivalentTo("one", "two"); } [Fact] public async Task Split_TokenizeLines_SplitsTheBody() { var parts = new List(); _context.AddRoutes(r => r.From("direct://cat-split-out").Process(e => parts.Add(e.In.Body))); Load(""" """); var producer = await StartAndProducer("direct://cat-split-in"); await producer.Process(new Exchange(new Message("a;b;;c"))); parts.Should().Equal("a", "b", "c"); } [Fact] public async Task ClaimCheck_SetAndGet_RestoresTheBody() { Load(""" """); var producer = await StartAndProducer("direct://cat-claim-in"); var exchange = Msg("payload", ("ticket", "t-1")); await producer.Process(exchange); exchange.In.Body.Should().Be("payload"); } [Fact] public async Task MarshalUnmarshal_JsonRoundtrip_ByRegisteredFormat() { Load($$""" """); var producer = await StartAndProducer("direct://cat-json-in"); var exchange = new Exchange(new Message(new CatalogOrder { Id = "o-1", Amount = 7 })); await producer.Process(exchange); var order = exchange.In.Body.Should().BeOfType().Subject; order.Id.Should().Be("o-1"); order.Amount.Should().Be(7); } [Fact] public async Task OnException_RouteLevel_HandlesTheFailure() { Load(""" """); var producer = await StartAndProducer("direct://cat-onexc-in"); var exchange = new Exchange(new Message("x")); await producer.Process(exchange); exchange.Exception.Should().BeNull(); exchange.In.Headers["rescued"].Should().Be("yes"); } [Fact] public async Task Enrich_NamedStrategy_PutsTheResourceIntoAHeader() { _context.AddRoutes(r => r.From("direct://cat-enrich-src").SetBody("resource-data")); Load(""" """); var producer = await StartAndProducer("direct://cat-enrich-in"); var exchange = new Exchange(new Message("original")); await producer.Process(exchange); exchange.In.Body.Should().Be("original"); exchange.In.Headers["extra"].Should().Be("resource-data"); } [Fact] public async Task RecipientList_SendsToEveryListedEndpoint() { var seen = new List(); _context.AddRoutes(r => { r.From("direct://cat-rl-a").Process(_ => seen.Add("a")); r.From("direct://cat-rl-b").Process(_ => seen.Add("b")); }); Load(""" """); var producer = await StartAndProducer("direct://cat-rl-in"); await producer.Process(Msg("x", ("targets", "direct://cat-rl-a;direct://cat-rl-b"))); seen.Should().BeEquivalentTo("a", "b"); } [Fact] public async Task OfType_IsATypedSection_ConvertingNotGuarding() { // OfType converts the body to the target type; an incompatible body is a // conversion failure on the exchange, never a silent skip. var hits = 0; _context.AddRoutes(r => r.From("direct://cat-oftype-out").Process(_ => hits++)); Load($$""" """); var producer = await StartAndProducer("direct://cat-oftype-in"); var typed = new Exchange(new Message(new CatalogOrder())); await producer.Process(typed); var incompatible = new Exchange(new Message("just a string")); var act = () => producer.Process(incompatible); await act.Should().ThrowAsync("an incompatible body is a conversion failure"); hits.Should().Be(1); typed.In.Headers["after"].Should().Be("yes", "siblings after stay on the parent route"); } [Fact] public async Task Normalize_ByConditionAndOtherwise_TransformsTheBody() { Load(""" """); var producer = await StartAndProducer("direct://cat-norm-in"); var wrapped = Msg("w", ("kind", "wrapped")); await producer.Process(wrapped); var plain = Msg("p", ("kind", "plain")); await producer.Process(plain); wrapped.In.Body.Should().Be("unwrapped:w"); plain.In.Body.Should().Be("passthrough:p"); } [Fact] public async Task LoadBalance_RoundRobin_AlternatesEndpoints() { var seen = new List(); _context.AddRoutes(r => { r.From("direct://cat-lb-1").Process(_ => seen.Add("one")); r.From("direct://cat-lb-2").Process(_ => seen.Add("two")); }); Load(""" """); var producer = await StartAndProducer("direct://cat-lb-in"); await producer.Process(new Exchange(new Message("1"))); await producer.Process(new Exchange(new Message("2"))); seen.Should().BeEquivalentTo("one", "two"); } [Fact] public async Task Saga_RegistryProcessorSteps_CompensateOnFailure() { var log = new List(); _context.AddToRegistry("step1", new ProbeProcessor("one", log)); _context.AddToRegistry("undo1", new ProbeProcessor("undo-one", log)); _context.AddToRegistry("boom", new ProbeProcessor("boom", log, fail: true)); _context.AddXmlRoutesFromContent(""" """); var producer = await StartAndProducer("direct://cat-saga-in"); var act = () => producer.Process(new Exchange(new Message("x"))); await act.Should().ThrowAsync("the failing step surfaces after compensation"); log.Should().Equal("one", "boom", "undo-one"); } private sealed class ProbeProcessor(string mark, List log, bool fail = false) : IProcessor { public Task Process(IExchange exchange, CancellationToken ct = default) { log.Add(mark); return fail ? Task.FromException(new InvalidOperationException(mark)) : Task.CompletedTask; } } // ── schema errors ──────────────────────────────────────────────────────── [Fact] public void Aggregate_WithoutStrategy_IsASchemaError() { var act = () => Load(""" """, "bad-agg.xml"); act.Should().Throw().WithMessage("*bad-agg.xml(4,*strategy*"); } [Fact] public void UnknownAggregationStrategy_ReportsThePosition() { var act = () => Load(""" """, "bad-strategy.xml"); act.Should().Throw().WithMessage("*bad-strategy.xml(4,*nosuchstrategy*"); } [Fact] public void Loop_WithTwoSources_IsASchemaError() { var act = () => Load(""" """); act.Should().Throw().WithMessage("*exactly one of count, expr or while*"); } [Fact] public void Xslt_FileAndContentTogether_IsASchemaError() { var act = () => Load(""" ]]> """); act.Should().Throw().WithMessage("*either the file attribute or inline*not both*"); } [Fact] public async Task ValidateXsd_FileWithANamespacedSchema_WithoutTargetNamespace_TakesTheSchemasNamespace() { // Row 50: without targetNamespace= the schema's own target namespace is taken. var dir = Path.Combine(Path.GetTempPath(), "redb-xsd-ns-" + Guid.NewGuid().ToString("N")[..8]); Directory.CreateDirectory(dir); try { var xsd = Path.Combine(dir, "person.xsd"); File.WriteAllText(xsd, """ """); Load($""" """); var producer = await StartAndProducer("direct://cat-xsd-ns-in"); var exchange = new Exchange(new Message("""Ann""")); await producer.Process(exchange); exchange.Exception.Should().BeNull(); } finally { Directory.Delete(dir, recursive: true); } } [Fact] public void WeightedLoadBalance_MissingWeight_IsASchemaError() { var act = () => Load(""" """); act.Should().Throw().WithMessage("*weight on every *"); } [Fact] public void BadTransactionPolicy_ReportsTheKnownNames() { var act = () => Load(""" """); act.Should().Throw() .WithMessage("*not a transaction policy (default, requiresNew, suppress, mandatory)*"); } [Fact] public void FormatOptionsOnMarshal_RequireTheTypeForm() { var act = () => Load(""" """); act.Should().Throw().WithMessage("*need the type= form*"); } [Fact] public void RichLog_TextAndChildrenTogether_IsASchemaError() { var act = () => Load(""" some text
"""); act.Should().Throw().WithMessage("*either message text or child elements*"); } [Fact] public void MessageHistory_ReachesTheRouteDefinition() { // The route-level flag of the C# DSL has a markup form: a leaf step, like . // Found missing while spelling the SerialNumbers demo in XML (2026-09-17). Load(""" step """); var builder = _context.RouteBuilders.Single(); if (!builder.IsBuilt) builder.InternalBuild(_context); builder.Definitions.OfType().Single() .GetMessageHistory().Should().BeTrue(" is the markup form of .MessageHistory()"); } [Fact] public void Tracing_ReachesTheRouteDefinition() { // The route-level attribute, the markup form of .Tracing(false): a // service route stays out of the trace without switching the whole context's telemetry off. Load(""" step """); var builder = _context.RouteBuilders.Single(); if (!builder.IsBuilt) builder.InternalBuild(_context); builder.Definitions.OfType().Single() .GetTracing().Should().BeFalse(" is the markup form of .Tracing(false)"); } [Fact] public async Task MessageHistory_TrailIsReadableFromAnExpression() { // The trail the engine records is a value like any other: the markup reads it through the // messageHistory() function of the expression language, so a route can log it or branch on // it without a processor. The seam is what this test pins - the function lives in the engine. Load(""" step """); var producer = await StartAndProducer("direct://cat-hist-fn-in"); var exchange = new Exchange(new Message("x")); await producer.Process(exchange); exchange.In.Headers["trail"].Should().BeOfType() .Which.Should().NotBeEmpty("the recorded trail renders as text"); Convert.ToInt32(exchange.In.Headers["steps"]).Should().BeGreaterThan(0); } // ── anti-drift: the whole catalog in one document ──────────────────────── [Fact] public async Task TheWholeCatalog_LoadsAndStarts_InOneDocument() { _context.AddToRegistry("cat-repo", new Processors.InMemoryIdempotentRepository()); Load($$"""
plain rich
"""); await _context.Start(); _context.Routes.Select(r => r.RouteId).Should() .Contain(["cat-all-leaves", "cat-all-scopes", "cat-all-sinks", "cat-all-4-sink"]); } 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; } }