Bundle: redb-route / tests/redb.Route.Tests.Xml (tests.redb.Route.Tests.Xml.txt), 66 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.Xml/AttachmentElementsTests.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.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/AttachmentElementsTests.cs ---- using System.Text; using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Xml; namespace redb.Route.Tests.Xml; /// /// <addAttachment>, <removeAttachment> and <removeAttachments>: a markup route /// builds a message with files without code, from an expression, the body or a file. /// public class AttachmentElementsTests : IAsyncLifetime { private readonly RouteContext _context = new(); public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() => await _context.DisposeAsync(); private async Task Run(string steps, string body = "the body") { _context.AddXmlRoutesFromContent($""" {steps} """, "attachments.xml"); await _context.Start(); var producer = _context.GetEndpoint("direct://att-in").CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message(body)); await producer.Process(exchange); return exchange; } private static string Text(Attachment a) => Encoding.UTF8.GetString(a.Content.ReadAllBytes()); [Fact] public async Task The_three_sources_add_attachments_and_remove_takes_them_off() { var path = Path.Combine(Path.GetTempPath(), $"xml-att-{Guid.NewGuid():N}.txt"); await File.WriteAllTextAsync(path, "file text"); try { var exchange = await Run($""" """); var attachments = exchange.In.Attachments; attachments.Select(a => a.Name).Should().Equal("note", "copy.bin", Path.GetFileName(path), "by-header"); Text(attachments[0]).Should().Be("anna"); attachments[0].FileName.Should().Be("anna.txt"); Text(attachments[1]).Should().Be("the body"); attachments[1].ContentType.Should().Be("application/pdf"); Text(attachments[2]).Should().Be("file text"); Text(attachments[3]).Should().Be("file text"); } finally { File.Delete(path); } } [Fact] public async Task RemoveAttachments_clears_them() { var exchange = await Run(""" """); exchange.In.Attachments.Should().BeEmpty(); } [Fact] public async Task Two_sources_on_one_element_are_a_markup_error() { var act = () => Run(""""""); await act.Should().ThrowAsync().WithMessage("*attachments.xml(*exactly one of 'expr', 'fromBody', 'file' or 'fileExpr'*"); } [Fact] public void Generated_code_names_the_optional_arguments_so_the_overload_is_never_ambiguous() { var document = System.Xml.Linq.XDocument.Parse(""" """); var code = XmlCodeGenerator.Generate(document, "AttachmentsGenerated", "Tests.Generated"); code.Should().Contain("AddAttachment(\"note\", Expr(\"${header.n}\"), contentType: \"text/plain\")"); code.Should().Contain("AddAttachmentFromBody(\"body\", fileName: Expr(\"${header.f}\"))"); code.Should().Contain("AddAttachmentFromFile(Expr(\"${header.p}\"), name: \"doc\")"); code.Should().Contain("RemoveAttachments()"); } [Theory] [InlineData("", 2)] [InlineData(" maxParts=\"1\"", -1)] public async Task A_MIME_multipart_format_declared_in_context_xml_reads_a_form_with_its_options(string options, int expectedFiles) { var type = "redb.Route.DataFormats.Mime.MimeMultipartDataFormat, redb.Route.DataFormats.Mime"; new XmlContextLoader(_context).Load(System.Xml.Linq.XDocument.Parse( $"""""", System.Xml.Linq.LoadOptions.SetLineInfo), "context.xml"); _context.AddXmlRoutesFromContent(""" """, "form.xml"); await _context.Start(); var producer = _context.GetEndpoint("direct://form-in").CreateProducer(); await producer.Start(); var body = Encoding.UTF8.GetBytes( "--b\r\nContent-Disposition: form-data; name=\"f\"; filename=\"a.txt\"\r\n\r\nA\r\n" + "--b\r\nContent-Disposition: form-data; name=\"f\"; filename=\"b.txt\"\r\n\r\nB\r\n--b--\r\n"); var exchange = new Exchange(new Message(body) { ContentType = "multipart/form-data; boundary=b" }); var act = () => producer.Process(exchange); if (expectedFiles < 0) { await act.Should().ThrowAsync().WithMessage("*MaxParts*", "the attribute reached the options"); return; } await act(); exchange.In.Attachments.Select(a => a.Name).Should().Equal("a.txt", "b.txt"); } [Fact] public async Task An_attachment_without_a_name_is_a_markup_error() { var act = () => Run(""""""); await act.Should().ThrowAsync().WithMessage("*requires the 'name' attribute*"); } } Path: redb-route/tests/redb.Route.Tests.Xml/BeanStepXmlTests.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.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/BeanStepXmlTests.cs ---- using System.Xml.Linq; using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Definitions; using redb.Route.Xml; namespace redb.Route.Tests.Xml; /// /// The step <bean ref|beanType method/> (amended 2026-11-05): the structured endpoint child of /// <to> without the wrapper. It normalizes through the same path into the same bean: endpoint; /// the name bean keeps its other two places (the declaration under <routes>/<context> /// and the endpoint child of <to>) exactly as before. /// public class BeanStepXmlTests : IAsyncLifetime { private readonly RouteContext _context = new(); public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { await _context.DisposeAsync(); GC.SuppressFinalize(this); } private static string Greeter => $"{typeof(XmlGreeter).FullName}, {typeof(XmlGreeter).Assembly.GetName().Name}"; private string? StepUri(string stepXml, out List errors) { var ctx = new XmlParseContext(_context, ElementRegistry.CreateDefault(), "probe.xml"); var uri = StructuredEndpoint.ResolveBeanStep(XElement.Parse(stepXml, LoadOptions.SetLineInfo), ctx); errors = [.. ctx.Errors]; return uri; } private async Task StartAndProducer(string fromUri) { await _context.Start(); var producer = _context.GetEndpoint(fromUri).CreateProducer(); await producer.Start(); return producer; } private static string CodeOf(string xml) => XmlCodeGenerator.Generate(XDocument.Parse(xml), "Beans", "Tests.Generated", sourceName: ""); // ── normalization ──────────────────────────────────────────────────────── [Theory] [InlineData("""""", "bean://#greeter?method=Greet")] [InlineData("""""", "bean://#greeter?method=Greet")] [InlineData("""""", "bean://#greeter")] [InlineData("""""", "bean://Acme.Pricing, Acme?method=Gross(${header.qty})&Prefix=x")] [InlineData("""""", "bean://#greeter?method=Greet")] public void Step_NormalizesIntoTheBeanUri(string step, string expected) { StepUri(step, out var errors).Should().Be(expected); errors.Should().BeEmpty(); } [Fact] public void Step_AndTheToChild_MeetAtOneEndpointKey() { var step = StepUri("""""", out _)!; var ctx = new XmlParseContext(_context, ElementRegistry.CreateDefault(), "probe.xml"); var child = StructuredEndpoint.Resolve( XElement.Parse(""""""), ctx, out _)!; EndpointUriParser.Parse(step).NormalizedKey.Should().Be(EndpointUriParser.Parse(child).NormalizedKey); EndpointUriParser.Parse(step).NormalizedKey .Should().Be(EndpointUriParser.Parse("bean:#greeter?method=Greet").NormalizedKey); } [Theory] [InlineData("""""", "exactly one of ref=")] [InlineData("""""", "exactly one of ref=")] [InlineData("""""", "not path=")] [InlineData("""""", "is a declaration")] [InlineData("""""", "attributes only")] [InlineData("""""", "contains '?'")] public void Step_Malformed_IsAPositionedError(string step, string message) { StepUri(step, out var errors).Should().BeNull(); errors.Should().ContainSingle().Which.Should().Contain(message); } // ── the three places of ─────────────────────────────────────────── [Fact] public async Task AllThreePlaces_ParseAndRun_InOneDocument() { _context.AddXmlRoutesFromContent($$""" """); var producer = await StartAndProducer("direct://xml-bean-step"); var exchange = new Exchange(new Message("bob")); exchange.In.Headers["go"] = "yes"; await producer.Process(exchange); exchange.In.Headers["first"].Should().Be("decl:bob"); exchange.In.Body.Should().Be("decl:decl:decl:bob", "the step, the bean: URI and the step in a scope each called it"); } [Fact] public async Task BeanTypeStep_CreatesTheInstance_WithItsProperties() { _context.AddXmlRoutesFromContent($$""" """); var producer = await StartAndProducer("direct://xml-bean-type-step"); var exchange = new Exchange(new Message("ann")); await producer.Process(exchange); exchange.In.Body.Should().Be("typed:ann"); } [Fact] public void StepAtTheRoutesLevel_IsReadAsADeclaration_AndRefused() { // At the container level a is a declaration: the step attributes do not make it a step. var act = () => _context.AddXmlRoutesFromContent(""" """); act.Should().Throw().WithMessage("*is a step: it belongs inside a *"); } [Fact] public void DeclarationInsideARoute_IsRefused_PointingToTheContainerLevel() { var act = () => _context.AddXmlRoutesFromContent($$""" """); act.Should().Throw().WithMessage("*is a declaration* or *"); } // ── schema ─────────────────────────────────────────────────────────────── private static string ThreePlaces => $$""" """; [Fact] public void CatalogSchema_TakesAllThreePlaces() { var catalog = ComponentCatalog.Build([new Components.Bean.BeanComponent()]); XmlRouteSchema.Validate(XDocument.Parse(ThreePlaces, LoadOptions.SetLineInfo), ElementRegistry.CreateDefault(), catalog) .Should().BeEmpty(); } [Fact] public void CoreSchema_TakesAllThreePlaces() { XmlRouteSchema.Validate(XDocument.Parse(ThreePlaces, LoadOptions.SetLineInfo), ElementRegistry.CreateDefault()) .Should().BeEmpty(); } [Fact] public void Schema_TakesTheStep_AndKeepsTheDeclaration() { var problems = XmlRouteSchema.Validate(XDocument.Parse($$""" """, LoadOptions.SetLineInfo), ElementRegistry.CreateDefault()); problems.Should().BeEmpty(); } [Fact] public void Schema_RefusesADeclarationChildOnTheStep() { var problems = XmlRouteSchema.Validate(XDocument.Parse(""" """, LoadOptions.SetLineInfo), ElementRegistry.CreateDefault()); problems.Should().NotBeEmpty("the step takes attributes only; belongs to a declaration"); } // ── code generation ────────────────────────────────────────────────────── [Fact] public void Print_IsTheBeanSugar_OrTheUriWhenTheStepSetsProperties() { var code = CodeOf($$""" """); code.Should().Contain(".Bean(\"#greeter\", \"Greet\")"); code.Should().Contain(".Bean(\"#greeter\")"); code.Should().Contain($".To(\"bean://{Greeter}?method=Greet&Prefix=x\")"); } [Fact] public void Print_ProducesTheSameUri_TheLoaderBuilds() { const string xml = """ """; _context.AddXmlRoutesFromContent(xml); var builder = _context.RouteBuilders.Single(); if (!builder.IsBuilt) builder.InternalBuild(_context); var loaded = builder.Definitions.Single().Outputs.OfType().Single().Uri; EndpointUriParser.Parse(loaded).NormalizedKey .Should().Be(EndpointUriParser.Parse(Components.Bean.BeanComponent.UriFor("#greeter", "Greet")).NormalizedKey); CodeOf(xml).Should().Contain(".Bean(\"#greeter\", \"Greet\")"); } } Path: redb-route/tests/redb.Route.Tests.Xml/CacheKeyGateTests.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.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/CacheKeyGateTests.cs ---- using AwesomeAssertions; using redb.Route.Cache; using redb.Route.Xml.Packaging; namespace redb.Route.Tests.Xml; /// /// The gate reads <cache key> by the cache key rule (AttributeSpec.ConstantKey): a constant with a dash, /// a slash or a colon passes as the key it is, an expression over a root is compiled, and broken arithmetic over a root /// is the engine's error. /// public sealed class CacheKeyGateTests : IDisposable { private readonly string _root = Path.Combine(Path.GetTempPath(), "redb-xml-cachekey-" + Guid.NewGuid().ToString("N")); public CacheKeyGateTests() => Directory.CreateDirectory(_root); public void Dispose() => Directory.Delete(_root, recursive: true); private PackageResult Check(string key) { var dir = RouteProjectScaffold.Create(_root, "Ck" + Guid.NewGuid().ToString("N")[..6]); File.WriteAllText(Path.Combine(dir, "routes", "main.route.xml"), $""" """); return RoutePackage.Check(dir, "p", "1.0.0", extensions: [new CacheXmlContribution()]); } [Theory] [InlineData("orders-all")] [InlineData("reports/daily")] [InlineData("b:c")] [InlineData("header.customerId")] [InlineData("${header.k}-x")] public void AKeyTheEngineReads_Passes(string key) { var result = Check(key); result.Errors.Should().BeEmpty(); result.Warnings.Should().NotContain(w => w.Message.Contains("key=")); } [Fact] public void BrokenArithmeticOverARoot_IsTheEnginesError() { Check("header.a+b").Errors.Should().Contain(e => e.Message.StartsWith("key= ", StringComparison.Ordinal) && e.Message.Contains("'b' at position 10 is not a value")); } } Path: redb-route/tests/redb.Route.Tests.Xml/CatalogAndSynonymTests.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.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/CatalogAndSynonymTests.cs ---- using System.Xml.Linq; using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Diagnostics; using redb.Route.Xml; namespace redb.Route.Tests.Xml; /// Fast/Safe processing mode of the test connector. public enum CatMode { Fast, Safe } /// The options of the test connector — an ordinary . public sealed class CatEndpointOptions : EndpointOptions { public string? GroupId { get; set; } public int Retries { get; set; } = 3; [Sensitive] public string? Password { get; set; } public CatMode Mode { get; set; } = CatMode.Fast; public TimeSpan Timeout { get; set; } = TimeSpan.FromSeconds(5); public override void Validate() { } } /// /// The test connector of the anti-copy-paste criterion: Options, a Scheme, and ONE line of /// §7.2 metadata — and it must appear in the structured form, the catalog and the generated /// XSD without a single line of XML-specific code. /// public sealed class CatComponent : ComponentBase { public override string Scheme => "cat"; public override string? StructuredPathSynonym => "queue"; public override IEndpoint CreateEndpoint(EndpointUri uri) => throw new NotSupportedException("registration-only test connector"); } /// A connector whose path is a text (the sql shape). public sealed class SqlishComponent : ComponentBase { public override string Scheme => "sqlish"; public override bool PathIsText => true; public override IEndpoint CreateEndpoint(EndpointUri uri) => throw new NotSupportedException("registration-only test connector"); } /// Options for the dog family — named after the BASE component. public sealed class DogEndpointOptions : EndpointOptions { public bool Secure { get; set; } public override void Validate() { } } /// The base of the Https shape. public class DogComponent : ComponentBase { public override string Scheme => "dog"; public override IEndpoint CreateEndpoint(EndpointUri uri) => throw new NotSupportedException("registration-only test connector"); } /// /// The Https shape: a DERIVED component (HttpsComponent : HttpComponent) with no options /// class of its own — it must inherit the base's options in the catalog. /// public sealed class DogsComponent : DogComponent { public override string Scheme => "dogs"; } /// /// Component catalog metadata: the component catalog is reflection over what a connector /// already has, the path synonym is read FROM the component, and the catalog-aware XSD makes /// the structured endpoint children strict and enum-hinted. /// public class CatalogAndSynonymTests : IAsyncLifetime { private readonly RouteContext _context = new(); public CatalogAndSynonymTests() { _context.AddComponent(new CatComponent()); _context.AddComponent(new SqlishComponent()); } public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { await _context.DisposeAsync(); GC.SuppressFinalize(this); } private static IReadOnlyList Catalog() => ComponentCatalog.Build([new CatComponent(), new SqlishComponent()]); // ── the catalog is reflection, not a hand-kept list ────────────────────── [Fact] public void DerivedComponent_InheritsTheBaseOptions_TheHttpsShape() { // The live catalog run over the worker caught this: HttpsComponent : HttpComponent // has no HttpsEndpointOptions — the naming walk must climb the base chain. var catalog = ComponentCatalog.Build([new DogsComponent()]); var dogs = catalog.Single(c => c.Scheme == "dogs"); dogs.OptionsType.Should().Be(typeof(DogEndpointOptions).FullName); dogs.Options.Should().Contain(o => o.Name == "Secure"); } [Fact] public void Catalog_DescribesTheConnector_FromItsOwnCode() { var cat = Catalog().Single(c => c.Scheme == "cat"); cat.PathSynonym.Should().Be("queue"); cat.PathIsText.Should().BeFalse(); cat.OptionsType.Should().Be(typeof(CatEndpointOptions).FullName); cat.Package.Should().Be(typeof(CatComponent).Assembly.GetName().Name); var options = cat.Options.ToDictionary(o => o.Name); options["Retries"].Should().BeEquivalentTo(new CatalogOption("Retries", "int", "3", false, null, Role: null, ConnectionParameter: false, ConnectionFactoryReference: false)); options["Password"].Sensitive.Should().BeTrue("the [Sensitive] mark must reach the property panel"); options["Mode"].Type.Should().Be("enum"); options["Mode"].EnumValues.Should().Equal("Fast", "Safe"); options["Mode"].Default.Should().Be("Fast"); options["Timeout"].Type.Should().Be("duration"); options["Timeout"].Default.Should().Be("00:00:05"); } [Fact] public void CatalogJson_IsCamelCased_AndMarksSecrets() { var json = ComponentCatalog.ToJson(Catalog()); json.Should().Contain("\"scheme\": \"cat\"") .And.Contain("\"pathSynonym\": \"queue\"") .And.Contain("\"sensitive\": true"); } // ── the synonym comes from the component, not from a list ──────────────── [Fact] public void StructuredForm_UsesTheComponentsPathSynonym() { _context.AddXmlRoutesFromContent(""" """); var text = RouteDescriber.Describe(Examples.ExampleHarness.Definitions(_context)); text.Should().Contain("to uri=cat://orders?retries=5", "queue= is the component's declared synonym for the path part"); } [Fact] public void SynonymAndPath_Together_IsASchemaError() { var act = () => _context.AddXmlRoutesFromContent(""" """); act.Should().Throw().WithMessage("*carries its path more than once*"); } [Fact] public async Task PathIsText_TakesThePathFromContent_AndRefusesTheAttribute() { _context.AddXmlRoutesFromContent(""" """); RouteDescriber.Describe(Examples.ExampleHarness.Definitions(_context)) .Should().Contain("to uri=sqlish://SELECT 1"); await using var other = new RouteContext(); other.AddComponent(new SqlishComponent()); var act = () => other.AddXmlRoutesFromContent(""" """); act.Should().Throw() .WithMessage("*path of is a text*element content*"); } // ── the catalog-aware XSD: strict scheme elements with typed options ───── [Fact] public void CatalogAwareXsd_ValidatesTheKnownScheme_AndRejectsTheUnknown() { var registry = ElementRegistry.CreateDefault(); var catalog = Catalog(); XmlRouteSchema.Validate(XDocument.Parse(""" """, LoadOptions.SetLineInfo), registry, catalog) .Should().BeEmpty(); XmlRouteSchema.Validate(XDocument.Parse(""" """, LoadOptions.SetLineInfo), registry, catalog) .Should().NotBeEmpty("a scheme outside the catalog is not a valid endpoint child"); } [Fact] public void CatalogAwareXsd_EnforcesEnumOptions() { var problems = XmlRouteSchema.Validate(XDocument.Parse(""" """, LoadOptions.SetLineInfo), ElementRegistry.CreateDefault(), Catalog()); problems.Should().Contain(p => p.Message.Contains("Sideways"), "enum options become xs:enumeration — the editor offers Fast/Safe"); } } 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; } } Path: redb-route/tests/redb.Route.Tests.Xml/CatalogEnumOptionsTests.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.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/CatalogEnumOptionsTests.cs ---- using System.Security.Authentication; using System.Xml.Linq; using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Xml; namespace redb.Route.Tests.Xml; /// An acknowledgement mode, spelled lowercase in the engine's own messages. public enum ProbeAckMode { Manual, Auto, } /// A connector with a pick-one enum option and a [Flags] one. public sealed class ProbeTlsComponent : ComponentBase { public override string Scheme => "probetls"; public override IEndpoint CreateEndpoint(EndpointUri uri) => throw new NotSupportedException("catalog-only test component"); } /// A pick-one enum whose list is long enough to lose the case-insensitive union. public enum ProbeFileExist { Override, Append, Fail, Ignore, } /// The options binds. public sealed class ProbeTlsEndpointOptions : EndpointOptions { public ProbeAckMode AckMode { get; set; } public ProbeFileExist FileExist { get; set; } public SslProtocols SslProtocols { get; set; } public override void Validate() { } } /// Options two components share — the mail connector's shape (imap, pop3, smtp). public sealed class ProbeSharedOptions : EndpointOptions { public bool TrustAllCertificates { get; set; } public override void Validate() { } } /// A component whose options class is named after neither it nor its assembly's only one. public sealed class ProbeInboxComponent : ComponentBase { public override string Scheme => "probeinbox"; public override IEndpoint CreateEndpoint(EndpointUri uri) => throw new NotSupportedException("catalog-only test component"); } /// The endpoint that declares the shared options as its type argument. public sealed class ProbeInboxEndpoint(EndpointUri uri, IComponent component, ProbeSharedOptions options) : EndpointBase(uri, component, options) { public override IProducer CreateProducer() => throw new NotSupportedException(); public override IConsumer CreateConsumer(IProcessor processor) => throw new NotSupportedException(); } /// /// Enum options in the editor schema read the way the engine reads them: the option converter /// parses member names in any case, and a [Flags] enum takes several members joined by commas. /// The schema used to take exact C# names only (ackMode="manual", the engine's own /// spelling, was an error) and one flags member at most (sslProtocols="Tls12,Tls13" was one). /// A LONG pick-one list is the one exception, and it is deliberate: the case-insensitive form costs /// the editor's language server its memory, so above the threshold the schema lists the member names /// and nothing more (see XmlRouteSchema.EnumOptionType). /// public sealed class CatalogEnumOptionsTests { private static readonly IReadOnlyList Catalog = ComponentCatalog.Build([new ProbeTlsComponent()]); private static IReadOnlyList<(int Line, int Column, string Message)> Validate(string attributes) => XmlRouteSchema.Validate(XDocument.Parse($""" """, LoadOptions.SetLineInfo), ElementRegistry.CreateDefault(), Catalog); [Fact] public void Catalog_TellsAFlagsEnum_FromAPickOneEnum() { var options = Catalog.Single().Options; options.Single(o => o.Name == "AckMode").Type.Should().Be("enum"); options.Single(o => o.Name == "SslProtocols").Type.Should().Be("flags"); } [Fact] public void Catalog_FindsSharedOptions_ThroughTheEndpointsTypeArgument() { // imap, pop3 and smtp share MailEndpointOptions: neither naming nor "the assembly's only // options class" finds it, so their catalog entries had no options at all. var inbox = ComponentCatalog.Build([new ProbeInboxComponent()]).Single(); inbox.OptionsType.Should().Be(typeof(ProbeSharedOptions).FullName); inbox.Options.Should().Contain(o => o.Name == "TrustAllCertificates"); } [Theory] [InlineData("ackMode=\"manual\"")] [InlineData("ackMode=\"Manual\"")] [InlineData("ackMode=\"AUTO\"")] [InlineData("sslProtocols=\"Tls12,Tls13\"")] [InlineData("sslProtocols=\"tls12, Tls13\"")] public void Schema_TakesWhatTheEngineTakes(string attributes) => Validate(attributes).Should().BeEmpty(); [Theory] [InlineData("ackMode=\"sometimes\"")] [InlineData("sslProtocols=\"Tls99\"")] [InlineData("sslProtocols=\"Tls12,\"")] public void Schema_RefusesWhatTheEngineRefuses(string attributes) => Validate(attributes).Should().NotBeEmpty(); [Fact] public void Schema_LongPickOneList_TakesTheNamesTheCatalogLists_AndNoOtherCase() { // The one deliberate exception (see the class comment): the case-insensitive union for the // catalog's 43 long pick-one lists is what took the editor's language server past its memory // on the first completion (2026-10-08). The engine goes on parsing any case, the editor asks // for the spelling the catalog carries. Validate("fileExist=\"Append\"").Should().BeEmpty(); Validate("fileExist=\"append\"").Should().NotBeEmpty(); } } Path: redb-route/tests/redb.Route.Tests.Xml/CatalogReferenceTests.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.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/CatalogReferenceTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Components; using redb.Route.Core; using redb.Route.Xml; namespace redb.Route.Tests.Xml; /// A connector whose options name registry objects in every way an option can. public sealed class ProbeRefComponent : ComponentBase { public override string Scheme => "proberef"; public override IEndpoint CreateEndpoint(EndpointUri uri) => throw new NotSupportedException("catalog-only test component"); } /// The options of . public sealed class ProbeRefEndpointOptions : EndpointOptions { [ConnectionFactoryReference(typeof(ProbeRefFactory))] public string? ConnectionFactory { get; set; } [RegistryReference(typeof(IHeaderFilterStrategy))] public string? HeaderFilterStrategy { get; set; } [RegistryReference] public string? Anything { get; set; } public string? Queue { get; set; } public override void Validate() { } } /// The factory type expects. public sealed class ProbeRefFactory; /// /// Row 7: an option that names a registry object carries , the expected type as /// Full.Name, Assembly or object; every other option has none, and the JSON writes the member only when it /// is set. The option's type stays what it was. /// public sealed class CatalogReferenceTests { private static readonly IReadOnlyList Options = ComponentCatalog.Build([new ProbeRefComponent()]).Single().Options; private static CatalogOption Option(string name) => Options.Single(o => o.Name == name); private static string T() => $"{typeof(TType).FullName}, {typeof(TType).Assembly.GetName().Name}"; [Fact] public void ATypedMark_IsTheExpectedType() { Option("HeaderFilterStrategy").Reference.Should().Be(T()); Option("HeaderFilterStrategy").Type.Should().Be("string"); } [Fact] public void AnUntypedMark_IsObject() { Option("Anything").Reference.Should().Be("object"); } [Fact] public void TheConnectionFactoryReference_IsARegistryReferenceToo_AndKeepsItsFlag() { Option("ConnectionFactory").Reference.Should().Be(T()); Option("ConnectionFactory").ConnectionFactoryReference.Should().BeTrue(); } [Fact] public void AnUnmarkedOption_HasNoReference() { Option("Queue").Reference.Should().BeNull(); } [Fact] public void TheJson_WritesReferenceOnlyWhereItIsSet() { var json = ComponentCatalog.ToJson(ComponentCatalog.Build([new ProbeRefComponent()])); json.Should().Contain($"\"reference\": \"{T()}\"").And.Contain("\"reference\": \"object\""); System.Text.RegularExpressions.Regex.Matches(json, "\"reference\"").Count.Should().Be(3); } [Fact] public void TheCoreVmEndpoint_MarksItsHeaderFilterStrategy() { var vm = ComponentCatalog.Build([new VmComponent()]).Single(); vm.Options.Single(o => o.Name == "HeaderFilterStrategy").Reference.Should().Be(T()); vm.Options.Where(o => o.Name != "HeaderFilterStrategy").Should().OnlyContain(o => o.Reference == null); } } Path: redb-route/tests/redb.Route.Tests.Xml/Characterization/TemplateCharacterizationTests.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.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/Characterization/TemplateCharacterizationTests.cs ---- using System.Globalization; using System.Net; using System.Reflection; using System.Runtime.CompilerServices; using System.Text; using System.Text.Json; using System.Text.RegularExpressions; using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Expressions; using redb.Route.Predicates; using redb.Route.Xml.Packaging; namespace redb.Route.Tests.Xml.Characterization; /// /// Characterization of every place that finds ${...} in a string, recorded before the shared template scanner /// and the bean function change any of them (stage 2 of the bean parity work, step a). The corpus is every template /// written in the redb.Route tree: docs, examples, demos, sources and tests. For each one the snapshot holds what the /// engine does with it today: /// /// the hole spans of the template compiler, of 's template test and of /// ' expression test (, the one reader that may change when the /// scanner replaces the three patterns); /// the single-placeholder reading, the rendered text, the typed value, the condition result, whether an /// endpoint option binds it as dynamic, and the pack gate's comparison warning. /// /// The snapshot file must not change while the scanner and the grammar change. Values that depend on the clock, on /// random numbers or on the environment are recorded by their kind only. /// Re-record (only on purpose, and only with the reviewer's agreement): REDB_RECORD_CHARACTERIZATION=1 re-records the /// committed templates; =extract rebuilds the corpus from the sources. /// public sealed class TemplateCharacterizationTests { private const string SnapshotName = "template-characterization.jsonl"; private static string Here([CallerFilePath] string file = "") => Path.GetDirectoryName(file)!; /// The redb.Route tree root: two levels above the test project directory, in the monorepo and the mirror. private static string RouteTreeRoot() => Path.GetFullPath(Path.Combine(Here(), "..", "..", "..")); [Fact] public void EveryTemplateOfTheRouteTree_BehavesAsRecorded() { var snapshot = Path.Combine(Here(), SnapshotName); // "1" re-records the committed templates (the corpus stays fixed while the engine changes); "extract" builds the // corpus again from the Route tree, which also picks up and drops templates as the sources change. var record = Environment.GetEnvironmentVariable("REDB_RECORD_CHARACTERIZATION"); if (record is "1" or "extract") { List corpus = record == "extract" || !File.Exists(snapshot) ? ExtractCorpus(RouteTreeRoot()) : [.. File.ReadAllLines(snapshot).Where(l => l.Length > 0) .Select(l => JsonSerializer.Deserialize(l, Json)!.Template)]; // A one-time, reviewed addition to the corpus: one expression per line of the named file. if (Environment.GetEnvironmentVariable("REDB_CHARACTERIZATION_ADD") is { Length: > 0 } additions) corpus = [.. new SortedSet(corpus.Concat(File.ReadAllLines(additions).Where(l => l.Length > 0)), StringComparer.Ordinal)]; File.WriteAllText(snapshot, string.Join("\n", corpus.Select(t => Serialize(Characterize(t)))) + "\n", new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)); } File.Exists(snapshot).Should().BeTrue($"the snapshot {SnapshotName} is committed beside this test"); var recorded = File.ReadAllLines(snapshot).Where(l => l.Length > 0).ToList(); recorded.Count.Should().BeGreaterThan(500, "the corpus is every template of the Route tree"); var mismatches = new List(); foreach (var line in recorded) { var template = JsonSerializer.Deserialize(line, Json)!.Template; var now = Serialize(Characterize(template)); if (now != line) mismatches.Add($"recorded: {line}{Environment.NewLine}now: {now}"); } mismatches.Should().BeEmpty($"{mismatches.Count} of {recorded.Count} templates behave differently:{Environment.NewLine}" + string.Join(Environment.NewLine, mismatches.Take(20))); } [Fact] public void TheSnapshot_IsSortedAndFreeOfDuplicates() { var templates = File.ReadAllLines(Path.Combine(Here(), SnapshotName)).Where(l => l.Length > 0) .Select(l => JsonSerializer.Deserialize(l, Json)!.Template).ToList(); templates.Should().OnlyHaveUniqueItems(); templates.Should().BeInAscendingOrder(StringComparer.Ordinal); } // ── one template ───────────────────────────────────────────────────────── /// One line of the snapshot. public sealed record Entry( string Template, int[][] CompilerHoles, int[][] StringExpressionHoles, int[][] EndpointOptionHoles, string? SinglePlaceholder, string Text, string Value, string Condition, string OptionBinding, bool GateWarnsComparison, string? ResolveExpression = null, string? Interpreted = null, string? Ast = null); private static readonly JsonSerializerOptions Json = new() { Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping, }; private static string Serialize(Entry entry) => JsonSerializer.Serialize(entry, Json); private static readonly Regex Varying = new( @"(?i)\b(now|today|date|time|timestamp|random|uuid|guid|ticks|exchangeId|messageId|stats|messagehistory|elapsed|env)\b|\{\{", RegexOptions.Compiled); private static Entry Characterize(string template) { var culture = CultureInfo.CurrentCulture; var uiCulture = CultureInfo.CurrentUICulture; CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; try { var varies = Varying.IsMatch(template); return new Entry( template, HoleSpans(template, HolePattern.Compiler), HoleSpans(template, HolePattern.StringExpression), HoleSpans(template, HolePattern.EndpointOption), ExpressionResolver.TryGetSinglePlaceholder(template, out var single) ? single : null, Outcome(() => ExpressionResolver.ProcessTemplate(template, Fixture()), varies), Outcome(() => new StringExpression(template).Evaluate(Fixture()), varies), Outcome(() => PredicateFactory.FromString(template).Matches(Fixture()), varies), Outcome(() => OptionIsDynamic(template), varies), GateWarnsComparison(template), // The three positions rows 2+22 reconcile: the public entry a payload template's expr() calls, the // interpreted AST (where row 27 lives), and the AST compiler alone. Outcome(() => ExpressionResolver.ResolveExpression(template, Fixture()), varies), Outcome(() => new redb.Route.Expressions.Ast.Parser(new redb.Route.Expressions.Ast.Tokenizer(template).GetAllTokens()) .Parse().Evaluate(Fixture()), varies), Outcome(() => ExpressionResolver.GetCompiledValueExpressionWithAst(template)(Fixture()), varies)); } finally { CultureInfo.CurrentCulture = culture; CultureInfo.CurrentUICulture = uiCulture; } } /// The same message for every evaluation: fixed headers, properties and a structured body. private static Exchange Fixture() { var body = new Dictionary { ["Name"] = "ann", ["Amount"] = 10, ["Price"] = 2.5, ["Items"] = new List { 1, 2, 3 }, ["Customer"] = new Dictionary { ["Name"] = "bob", ["Vip"] = true }, }; var exchange = new Exchange(new Message(body)); foreach (var (key, value) in new (string, object?)[] { ("qty", 3), ("price", 2.5), ("amount", 5000), ("kind", "order"), ("flag", true), ("name", "ann"), ("orderId", "A-42"), ("orderNo", "A-42"), ("tripId", "T1"), ("count", 2), ("go", "yes"), ("CamelFileName", "in.txt"), ("Content-Type", "application/json"), ("status", 200), }) exchange.In.Headers[key] = value; exchange.Properties["tenant"] = "acme"; exchange.Properties["retries"] = 1; return exchange; } private static string Outcome(Func evaluate, bool varies) { object? value; try { value = evaluate(); } catch (Exception ex) { var inner = ex is TargetInvocationException { InnerException: { } e } ? e : ex; return varies ? $"!{inner.GetType().Name}" : $"!{inner.GetType().Name}: {Stable(inner.Message)}"; } if (value is null) return "null"; var type = value.GetType().Name; return varies ? $"{type}" : $"{type}: {Stable(Render(value))}"; } private static string Render(object value) => value switch { string s => s, IFormattable f => f.ToString(null, CultureInfo.InvariantCulture), System.Collections.IDictionary d => "{" + string.Join(", ", d.Keys.Cast().Select(k => $"{k}={Render(d[k]!)}")) + "}", System.Collections.IEnumerable e => "[" + string.Join(", ", e.Cast().Select(i => i is null ? "null" : Render(i))) + "]", _ => value.ToString() ?? "", }; private static readonly Regex Ids = new(@"\b[0-9a-f]{32}\b|\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b", RegexOptions.Compiled); private static readonly Regex AssemblyVersions = new(@"Version=\d+(\.\d+){3}", RegexOptions.Compiled); /// Ids and the runtime's assembly versions (each target framework differs) are not part of the behaviour. private static string Stable(string text) => AssemblyVersions.Replace(Ids.Replace(text, ""), "Version=*").ReplaceLineEndings("\n"); private sealed class ProbeOptions : EndpointOptions { public DynamicValue Value { get; set; } public override void Validate() { } } private static bool OptionIsDynamic(string template) { var options = new ProbeOptions(); options.BindFromUri(new Dictionary { ["value"] = template }); return options.Value.IsDynamic; } private static bool GateWarnsComparison(string template) => (bool)typeof(RoutePackage) .GetMethod("LooksLikeTemplateComparison", BindingFlags.NonPublic | BindingFlags.Static)! .Invoke(null, [template])!; // ── the hole reader (the one helper step b may switch to the shared scanner) ── private enum HolePattern { Compiler, StringExpression, EndpointOption } /// The [start, length] of every hole each place finds, read through the shared template scanner. private static int[][] HoleSpans(string template, HolePattern place) { // Every place reads holes through the shared scanner since step b; the place argument stays so the three // recorded columns keep their meaning. _ = place; return [.. TemplateScanner.Scan(template).Holes.Select(h => new[] { h.Start, h.Length })]; } // ── the corpus ─────────────────────────────────────────────────────────── private static readonly Regex Quoted = new(@"""((?:[^""\\\r\n]|\\.)*\$\{(?:[^""\\\r\n]|\\.)*)""", RegexOptions.Compiled); private static readonly Regex Backticked = new(@"`([^`\r\n]*\$\{[^`\r\n]*)`", RegexOptions.Compiled); private static readonly Regex DocCode = new(@"([^<\r\n]*\$\{[^<\r\n]*)", RegexOptions.Compiled); private static readonly Regex ElementText = new(@">([^<>\r\n]*\$\{[^<>\r\n]*)<", RegexOptions.Compiled); /// /// Every distinct template written in the Route tree: quoted strings and attribute values, inline code of the /// docs, <c> spans of XML docs and element text of route files, up to 300 characters. /// private static List ExtractCorpus(string root) { var files = new[] { "README.md", "UPGRADING.md", "TRANSACTIONS.md", "CONCURRENCY.md" } .Select(f => Path.Combine(root, f)).Where(File.Exists) .Concat(new[] { "docs", "src", "tests", "demos", "demo", "tools" } .Select(d => Path.Combine(root, d)).Where(Directory.Exists) .SelectMany(d => Directory.EnumerateFiles(d, "*.*", SearchOption.AllDirectories))) .Where(f => f.EndsWith(".md", StringComparison.Ordinal) || f.EndsWith(".cs", StringComparison.Ordinal) || f.EndsWith(".xml", StringComparison.Ordinal)) .Where(f => !f.Contains($"{Path.DirectorySeparatorChar}bin{Path.DirectorySeparatorChar}", StringComparison.Ordinal) && !f.Contains($"{Path.DirectorySeparatorChar}obj{Path.DirectorySeparatorChar}", StringComparison.Ordinal) && !f.Contains("node_modules", StringComparison.Ordinal) && !f.EndsWith(SnapshotName, StringComparison.Ordinal)); var corpus = new SortedSet(EdgeCases, StringComparer.Ordinal); foreach (var file in files) { var isCs = file.EndsWith(".cs", StringComparison.Ordinal); foreach (var line in File.ReadLines(file)) { if (!line.Contains("${", StringComparison.Ordinal)) continue; foreach (Match m in Quoted.Matches(line)) Add(corpus, isCs ? UnescapeCs(m.Groups[1].Value) : WebUtility.HtmlDecode(m.Groups[1].Value)); foreach (Match m in Backticked.Matches(line)) Add(corpus, m.Groups[1].Value); foreach (Match m in DocCode.Matches(line)) Add(corpus, WebUtility.HtmlDecode(m.Groups[1].Value)); if (!isCs) foreach (Match m in ElementText.Matches(line)) Add(corpus, WebUtility.HtmlDecode(m.Groups[1].Value)); } } return [.. corpus]; } /// /// The shapes a balanced scanner reads differently from the first-'}' patterns, written down so their current /// reading is on record: braces and quotes inside a hole, unbalanced and empty holes, adjacent holes, nesting. /// private static readonly string[] EdgeCases = [ "${'}'}", "${\"}\"}", "${header.a == '}'}", "${body} '}'", "${a ${b}", "${a ${b}}", "${${body}}", "${}", "$${body}", "${body}}", "{${body}}", "}${body}{", "${ body }", "${header.a}${header.b}", "text ${", "text ${body", "${body} and ${", "${header.flag ? 'yes' : 'no'}", "${header.flag?'a':'b'}", "${bean:svc.Check(${body})}", "${bean:svc.Check(body)}", "${concat('a', '}', 'b')}", "${header.list[0]}", "${body.Items[1]}", "${upper(header.name)}", "${header.qty * header.price}", "${header.kind} == 'order'", "${header.kind == 'order'}", "pre ${header.name} mid ${header.kind} post", "${header.name}\n${header.kind}", "${header['Content-Type']}", "${property.tenant}", ]; private static void Add(SortedSet corpus, string template) { template = template.Trim(); if (template.Length is > 0 and <= 300 && template.Contains("${", StringComparison.Ordinal)) corpus.Add(template); } private static string UnescapeCs(string text) => text.Replace("\\\"", "\"", StringComparison.Ordinal).Replace("\\\\", "\\", StringComparison.Ordinal); } Path: redb-route/tests/redb.Route.Tests.Xml/ComponentSidesLoadAndGateTests.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.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/ComponentSidesLoadAndGateTests.cs ---- using AwesomeAssertions; using redb.Route.Core; using redb.Route.Xml; using redb.Route.Xml.Packaging; namespace redb.Route.Tests.Xml; /// /// A scheme on the side its component lacks ([EndpointRole] on the class) is refused at load and by /// check, at its position, in the words the runtime uses. /// public sealed class ComponentSidesLoadAndGateTests : IAsyncLifetime, IDisposable { private readonly RouteContext _context = new(); private readonly string _root = Path.Combine(Path.GetTempPath(), "redb-xml-sides-" + Guid.NewGuid().ToString("N")); public ComponentSidesLoadAndGateTests() => Directory.CreateDirectory(_root); public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() => await _context.DisposeAsync(); public void Dispose() => Directory.Delete(_root, recursive: true); private Action Load(string from, string to) => () => _context.AddXmlRoutesFromContent($""" """, "sides.xml"); [Fact] public void Loader_refuses_a_route_from_a_producer_only_scheme_in_the_uri_form() => Load(""" uri="log://x"/>""", """ uri="direct://out"/>""").Should().Throw() .WithMessage("*sides.xml(3,*: log has no consumer side: a route cannot start from it (log is producer-only).*"); [Fact] public void Loader_refuses_a_route_from_a_producer_only_scheme_in_the_structured_form() => Load(""">""", """ uri="direct://out"/>""").Should().Throw() .WithMessage("*sides.xml(3,*: log has no consumer side*"); [Fact] public void Loader_refuses_a_target_that_is_consumer_only() => Load(""" uri="direct://in"/>""", """>""").Should().Throw() .WithMessage("*sides.xml(4,*: timer has no producer side: a route cannot send to it (timer is consumer-only). Use it as a From() source.*"); [Fact] public void Loader_takes_each_scheme_on_its_own_side() => Load(""" uri="timer://t?period=3600000&delay=3600000"/>""", """ uri="log://x"/>""").Should().NotThrow(); [Fact] public void Gate_reports_a_scheme_on_its_missing_side_in_both_forms_without_bin() { var dir = RouteProjectScaffold.Create(_root, "Sides"); File.WriteAllText(Path.Combine(dir, "routes", "main.route.xml"), """ """); var errors = RoutePackage.Check(dir, "p", "1.0.0").Errors.ToList(); errors.Should().Contain(e => e.File.StartsWith("routes/main.route.xml(3,") && e.Message.Contains(": log has no consumer side: a route cannot start from it")); errors.Should().Contain(e => e.File.StartsWith("routes/main.route.xml(4,") && e.Message.Contains(": timer has no producer side: a route cannot send to it")); errors.Should().Contain(e => e.File.StartsWith("routes/main.route.xml(7,") && e.Message.Contains(": log has no consumer side")); errors.Should().Contain(e => e.File.StartsWith("routes/main.route.xml(8,") && e.Message.Contains(": timer has no producer side")); errors.Should().NotContain(e => e.File.StartsWith("routes/main.route.xml(11,") || e.File.StartsWith("routes/main.route.xml(12,")); } } Path: redb-route/tests/redb.Route.Tests.Xml/ComponentSidesSchemaTests.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.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/ComponentSidesSchemaTests.cs ---- using System.Xml.Linq; using AwesomeAssertions; using redb.Route.Components; using redb.Route.Core; using redb.Route.Xml; namespace redb.Route.Tests.Xml; /// /// A component with one side ([EndpointRole] on its class) carries it in the catalog, and the editor schema /// offers the scheme only on that side: no <from><log/></from>, no /// <to><timer/></to>. /// public sealed class ComponentSidesSchemaTests { private static readonly IReadOnlyList Catalog = ComponentCatalog.Build([new LogComponent(), new TimerComponent(), new DirectComponent()]); private static IReadOnlyList<(int Line, int Column, string Message)> Validate(string from, string to) => XmlRouteSchema.Validate(XDocument.Parse($""" {from} {to} """, LoadOptions.SetLineInfo), ElementRegistry.CreateDefault(), Catalog); [Fact] public void Catalog_carries_the_only_side_and_nothing_for_both() { Catalog.Single(c => c.Scheme == "log").Role.Should().Be(EndpointRole.Producer); Catalog.Single(c => c.Scheme == "timer").Role.Should().Be(EndpointRole.Consumer); Catalog.Single(c => c.Scheme == "direct").Role.Should().BeNull("absent means both sides"); ComponentCatalog.ToJson(ComponentCatalog.Build([new TimerComponent()])).Should().Contain("\"role\": \"consumer\""); ComponentCatalog.ToJson(ComponentCatalog.Build([new DirectComponent()])).Should().NotContain("\"role\""); } [Fact] public void Schema_has_no_type_for_the_missing_side() { var schema = XmlRouteSchema.Generate(ElementRegistry.CreateDefault(), Catalog).ToString(); schema.Should().Contain("name=\"logProducer\"").And.NotContain("name=\"logConsumer\""); schema.Should().Contain("name=\"timerConsumer\"").And.NotContain("name=\"timerProducer\""); schema.Should().Contain("name=\"directProducer\"").And.Contain("name=\"directConsumer\""); } [Fact] public void Schema_refuses_a_producer_only_scheme_in_from() => Validate("""""", """""") .Should().Contain(p => p.Line == 3 && p.Message.Contains("log")); [Fact] public void Schema_refuses_a_consumer_only_scheme_in_to() => Validate("""""", """""") .Should().ContainSingle().Which.Line.Should().Be(4); [Fact] public void Schema_takes_each_scheme_on_its_own_side() => Validate("""""", """""").Should().BeEmpty(); } Path: redb-route/tests/redb.Route.Tests.Xml/ConnectionFactoryGateTests.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.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/ConnectionFactoryGateTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Xml; using redb.Route.Xml.Packaging; namespace redb.Route.Tests.Xml; /// A broker-like connector: a named connection factory, or the connection on the URI. public sealed class ProbeConnComponent : ComponentBase { public override string Scheme => "probeconn"; public override IEndpoint CreateEndpoint(EndpointUri uri) => throw new NotSupportedException("catalog-only test component"); } /// The options of , declared the way RabbitMQ declares its own. public sealed class ProbeConnEndpointOptions : EndpointOptions { [ConnectionFactoryReference] public string? ConnectionFactory { get; set; } [ConnectionParameter] public string? Host { get; set; } [ConnectionParameter] public int Port { get; set; } public string? Queue { get; set; } public override void Validate() { } } /// /// A named connection factory is the whole connection (abead3e8): a connection parameter written /// beside it is refused when the endpoint is created. The catalog carries the declarations, and /// the package gate reports the conflict with its position, URI form and structured form alike. /// public sealed class ConnectionFactoryGateTests : IDisposable { private readonly string _root = Path.Combine(Path.GetTempPath(), "redb-xml-connfactory-" + Guid.NewGuid().ToString("N")); public ConnectionFactoryGateTests() => Directory.CreateDirectory(_root); public void Dispose() => Directory.Delete(_root, recursive: true); private static readonly IReadOnlyList Catalog = ComponentCatalog.Build([new ProbeConnComponent()]); private static Type? Resolve(string typeName) => typeof(ProbeConnComponent).Assembly.GetType(typeName); [Fact] public void Catalog_CarriesTheConnectionDeclarations() { var options = Catalog.Single().Options; options.Single(o => o.Name == "ConnectionFactory").ConnectionFactoryReference.Should().BeTrue(); options.Single(o => o.Name == "Host").ConnectionParameter.Should().BeTrue(); options.Single(o => o.Name == "Queue").ConnectionParameter.Should().BeFalse(); ComponentCatalog.ToJson(Catalog).Should().Contain("\"connectionParameter\": true") .And.Contain("\"connectionFactoryReference\": true"); } [Fact] public void Gate_RefusesAConnectionParameterBesideTheFactory_InBothForms() { var dir = RouteProjectScaffold.Create(_root, "Conn"); File.WriteAllText(Path.Combine(dir, "routes", "main.route.xml"), """ """); var errors = RoutePackage.Check(dir, "p", "1.0.0", Resolve, catalog: Catalog).Errors.ToList(); errors.Should().Contain(e => e.File.StartsWith("routes/main.route.xml(3,") && e.Message.Contains("connectionFactory 'main' sets the whole connection, so host cannot be given on the URI as well")); errors.Should().Contain(e => e.File.StartsWith("routes/main.route.xml(8,") && e.Message.Contains("connectionFactory 'main' sets the whole connection, so port cannot be given")); errors.Should().NotContain(e => e.File.StartsWith("routes/main.route.xml(11,") || e.File.StartsWith("routes/main.route.xml(12,"), "a factory alone, or the connection alone on the URI, is fine"); } } Path: redb-route/tests/redb.Route.Tests.Xml/ContributionLoaderTests.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.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/ContributionLoaderTests.cs ---- using System.Reflection; using System.Runtime.Loader; using AwesomeAssertions; using redb.Route.Http.Rest; using redb.Route.Xml; using redb.Route.Xml.CodeGen; namespace redb.Route.Tests.Xml; /// /// redb-route-xml check --bin reads the connector contributions from a build output that also holds a copy of /// redb.Route.Xml.dll. On macOS the directory listing put that copy before the connectors, the connectors bound to it, /// their contributions were a different type and every connector element /// (rest, redbQuery, redbSave) was reported as an invalid child of routes. /// public sealed class ContributionLoaderTests : IDisposable { private readonly string _bin = Path.Combine(Path.GetTempPath(), "redb-contrib-" + Guid.NewGuid().ToString("N")); public ContributionLoaderTests() => Directory.CreateDirectory(_bin); public void Dispose() { try { Directory.Delete(_bin, recursive: true); } catch (IOException) { } catch (UnauthorizedAccessException) { } } /// The tool runs on redb.Route and redb.Route.Xml; the connectors are only in the directory. private static Assembly? ToolAssemblies(string? simpleName) => simpleName is "redb.Route" or "redb.Route.Xml" ? AssemblyLoadContext.Default.Assemblies.FirstOrDefault(a => a.GetName().Name == simpleName) : null; /// /// The order is passed explicitly: a directory listing is alphabetical on NTFS and not on ext4 or APFS, so a /// listing would test one order on one machine and the other one somewhere else. /// [Theory] [InlineData(true)] [InlineData(false)] public void TheXmlCopyInTheDirectory_NeverHidesTheConnectorContributions(bool xmlCopyFirst) { var xml = typeof(IXmlElementContribution).Assembly; var xmlCopy = Path.Combine(_bin, "redb.Route.Xml.dll"); var connector = Path.Combine(_bin, "redb.Route.Zz.dll"); File.Copy(xml.Location, xmlCopy); File.Copy(typeof(RestXmlContribution).Assembly.Location, connector); string[] order = xmlCopyFirst ? [xmlCopy, connector] : [connector, xmlCopy]; var contributions = ContributionLoader.Load(_bin, order, ToolAssemblies); var rest = contributions.Should() .ContainSingle(c => c.GetType().FullName == typeof(RestXmlContribution).FullName).Subject; AssemblyLoadContext.GetLoadContext(rest.GetType().Assembly).Should() .NotBe(AssemblyLoadContext.Default, "the connector comes from the directory, not from the test host"); contributions.Should().NotContain(c => c.GetType().Assembly == xml, "the tool's own elements are built in and must not be registered a second time"); } [Fact] public void ThePackageChecks_AreFoundTheSameWay() { var format = Path.Combine(_bin, "redb.Route.DataFormats.XmlJson.dll"); File.Copy(typeof(redb.Route.DataFormats.XmlJson.XmlJsonPackageCheck).Assembly.Location, format); var (contributions, checks) = ContributionLoader.LoadAll(_bin, [format], ToolAssemblies); var check = checks.Should().ContainSingle().Subject; check.GetType().FullName.Should().Be(typeof(redb.Route.DataFormats.XmlJson.XmlJsonPackageCheck).FullName); check.Should().BeAssignableTo("the contract type is the tool's own"); contributions.Should().BeEmpty("the format brings no element of its own"); } } Path: redb-route/tests/redb.Route.Tests.Xml/DataFormatCatalogTests.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.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/DataFormatCatalogTests.cs ---- using System.Runtime.Loader; using AwesomeAssertions; using redb.Route.Xml.CodeGen; namespace redb.Route.Tests.Xml; /// /// The generator's data format catalog (redb-route-dataformats.json): formats found in a bin with their name, content /// types, markup attributes by the CreateSerializer rule, kinds (Path by rule and data, Enum with values), defaults, /// descriptions from the XML docs, and the unmarshal targets where a format has a fixed set. /// public sealed class DataFormatCatalogTests { private static readonly List Catalog = DataFormatCatalog.Load( [AppContext.BaseDirectory], name => name is null ? null : AssemblyLoadContext.Default.Assemblies.FirstOrDefault(a => a.GetName().Name == name)); private static DataFormatEntry Entry(string name) => Catalog.Single(e => e.Name == name); [Fact] public void Xmljson_ItsAttributesKindsAndTargets() { var xmljson = Entry("xmljson"); xmljson.Type.Should().Be("redb.Route.DataFormats.XmlJson.XmlJsonDataFormat, redb.Route.DataFormats.XmlJson"); xmljson.ContentType.Should().Be("application/x-xmljson"); xmljson.Attributes.Single(a => a.Name == "schema").Kind.Should().Be("Path"); xmljson.Attributes.Single(a => a.Name == "schemaRoot").Kind.Should().Be("Path"); xmljson.Attributes.Single(a => a.Name == "arrays").Kind.Should().Be("String"); var namespaces = xmljson.Attributes.Single(a => a.Name == "namespaces"); namespaces.Kind.Should().Be("Enum"); namespaces.EnumValues.Should().Equal("Keep", "Drop"); namespaces.Default.Should().Be("Keep"); xmljson.Attributes.Single(a => a.Name == "textKey").Default.Should().Be("#text"); xmljson.Attributes.Should().OnlyContain(a => a.Description.Length > 0); xmljson.UnmarshalTargets.Should().Contain("System.Text.Json.Nodes.JsonNode, System.Text.Json"); } [Fact] public void Mime_TakesItsOptionsObjectsProperties() { var mime = Entry("mimeMultipart"); mime.Attributes.Select(a => a.Name).Should().Contain(["maxParts", "subType"]); mime.UnmarshalTargets.Should().BeNull("a format without a fixed set of targets takes any type"); } [Fact] public void TheCoreFormats_AreListedWithoutAName() { Catalog.Should().Contain(e => e.Type.StartsWith("redb.Route.Serialization.JsonMessageSerializer,", StringComparison.Ordinal) && e.Name == null); Catalog.Should().Contain(e => e.Type.StartsWith("redb.Route.Serialization.GZipMessageSerializer,", StringComparison.Ordinal), "a built-in wrapper with only optional constructor parameters is a format too"); } [Fact] public void ASerializerWithoutANameOrADefaultRegistration_IsNotADataFormat() { // ProbeDataFormat (this test assembly) is an IMessageSerializer, as Telegram's update reader is: neither names a format. Catalog.Should().NotContain(e => e.Type.StartsWith(typeof(ProbeDataFormat).FullName + ",", StringComparison.Ordinal)); } [Fact] public void ADocFile_IsFoundInTheDocDirs_TheNewestFirst() { var root = Path.Combine(Path.GetTempPath(), "redb-docs-" + Guid.NewGuid().ToString("N")); try { Directory.CreateDirectory(Path.Combine(root, "old")); Directory.CreateDirectory(Path.Combine(root, "new", "bin")); var older = Path.Combine(root, "old", "Pkg.xml"); var newer = Path.Combine(root, "new", "bin", "Pkg.xml"); File.WriteAllText(older, ""); File.WriteAllText(newer, ""); File.SetLastWriteTimeUtc(older, DateTime.UtcNow.AddDays(-1)); DataFormatCatalog.DocFileIn([root], "Pkg.xml").Should().Be(newer); DataFormatCatalog.DocFileIn([root], "None.xml").Should().BeNull(); DataFormatCatalog.DocFileIn([Path.Combine(root, "missing")], "Pkg.xml").Should().BeNull(); } finally { Directory.Delete(root, recursive: true); } } } Path: redb-route/tests/redb.Route.Tests.Xml/DataFormatContextTests.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.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/DataFormatContextTests.cs ---- using System.Text; using System.Xml.Linq; using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Serialization; using redb.Route.Xml; namespace redb.Route.Tests.Xml; /// A format with one option, as the redb.Route.DataFormats.* serializers are. public sealed class ProbeDataFormat : IMessageSerializer { public string Prefix { get; set; } = "plain"; public string ContentType => "application/x-probe"; public byte[] Serialize(T value) => Encoding.UTF8.GetBytes($"{Prefix}:{value}"); public T? Deserialize(byte[] data) => (T?)Deserialize(data, typeof(T)); public object? Deserialize(byte[] data, Type type) => Encoding.UTF8.GetString(data); } /// The options of , as CsvDataFormatOptions is for CsvDataFormat. public sealed class OptionsBuiltFormatOptions { public string Delimiter { get; set; } = ","; } /// Built from an options object only, the shape of the redb.Route.DataFormats.* serializers. public sealed class OptionsBuiltFormat(OptionsBuiltFormatOptions? options = null) : IMessageSerializer { private readonly OptionsBuiltFormatOptions _options = options ?? new(); public string ContentType => "text/x-built"; public byte[] Serialize(T value) => Encoding.UTF8.GetBytes($"a{_options.Delimiter}{value}"); public T? Deserialize(byte[] data) => (T?)Deserialize(data, typeof(T)); public object? Deserialize(byte[] data, Type type) => Encoding.UTF8.GetString(data); } /// /// <dataFormat> in context.xml registers a format for <marshal format="…"/>, as /// context.AddDataFormat(...) does in code. Before, a module in markup could not register one, and on the Tsak /// worker <marshal format="csv"/> failed with "Data format 'csv' is not registered". /// public sealed class DataFormatContextTests : IAsyncLifetime { private static readonly string ProbeType = $"{typeof(ProbeDataFormat).FullName}, {typeof(ProbeDataFormat).Assembly.GetName().Name}"; private readonly RouteContext _context = new(); public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() => await _context.DisposeAsync(); private void LoadContext(string inner) => new XmlContextLoader(_context).Load(XDocument.Parse($""" {inner} """, LoadOptions.SetLineInfo), "context.xml"); private async Task MarshalAsync(string format) { object? body = null; _context.AddRoutes(r => r.From("direct://df-out").Process(e => body = e.In.Body)); _context.AddXmlRoutesFromContent($""" """); await _context.Start(); var producer = _context.GetEndpoint("direct://df-in").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("order"))); return body; } [Fact] public async Task A_format_declared_in_context_xml_is_found_by_its_name_with_its_options() { LoadContext($""""""); var body = await MarshalAsync("probe"); Encoding.UTF8.GetString((byte[])body!).Should().Be("csv-like:order"); } [Fact] public async Task A_format_is_also_found_by_its_own_content_type() { LoadContext($""""""); var body = await MarshalAsync("application/x-probe"); Encoding.UTF8.GetString((byte[])body!).Should().Be("plain:order"); } [Fact] public async Task A_format_built_from_an_options_object_gets_its_options_from_the_attributes() { var built = $"{typeof(OptionsBuiltFormat).FullName}, {typeof(OptionsBuiltFormat).Assembly.GetName().Name}"; LoadContext($""""""); var body = await MarshalAsync("csv"); Encoding.UTF8.GetString((byte[])body!).Should().Be("a;order", "the format has no parameterless constructor; the attributes set its options object"); } [Fact] public void A_type_that_is_not_a_serializer_is_an_error_of_the_document() { var act = () => LoadContext(""""""); act.Should().Throw().Which.Errors.Should().Contain(e => e.Contains("IMessageSerializer")); } } Path: redb-route/tests/redb.Route.Tests.Xml/DeadLetterChannelXmlTests.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.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/DeadLetterChannelXmlTests.cs ---- using AwesomeAssertions; using redb.Route.Core; using redb.Route.ErrorHandling; using redb.Route.TestKit; using redb.Route.Xml; namespace redb.Route.Tests.Xml; /// /// <deadLetterChannel uri="..."/> in context.xml — the context's dead letter channel, Apache Camel's /// errorHandlerRef on <camelContext>: a context-level element only, and one error handler per context. /// public class DeadLetterChannelXmlTests : 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 InContext_EveryRouteSendsItsUntakenFailureThere() { _context.AddXmlContextFromContent(""" """, ""); _context.AddXmlRoutesFromContent(""" """, ""); await _context.Start(); _context.ErrorHandler.Should().BeOfType() .Which.DeadLetterUri.Should().Be("mock://xml-dlc-errors"); try { await _context.SendBody("direct://xml-dlc-orders", "x"); } catch (InvalidOperationException) { } await _context.Mock("mock://xml-dlc-errors").ExpectBodies("x").AssertIsSatisfiedAsync(TimeSpan.FromSeconds(2)); } [Fact] public void InARoute_IsAPositionedError() { var act = () => _context.AddXmlRoutesFromContent(""" """, ""); act.Should().Throw(); } [Fact] public void OverAnErrorHandlerAlreadySet_IsAnError() { _context.ErrorHandler = new DeadLetterErrorHandler(_context, "mock://first"); var act = () => _context.AddXmlContextFromContent(""" """, ""); act.Should().Throw().WithMessage("*already has an error handler*"); } } Path: redb-route/tests/redb.Route.Tests.Xml/DiRegistrationTests.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.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/DiRegistrationTests.cs ---- using AwesomeAssertions; using Microsoft.Extensions.DependencyInjection; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Extensions; using redb.Route.Xml; namespace redb.Route.Tests.Xml; /// /// DI surface: XML routes registered inside AddRedbRoute(...) load through /// the standard hook — the way an ordinary ASP.NET host /// runs them, no Tsak involved. /// public class DiRegistrationTests { [Fact] public async Task AddXmlRoutesFromContent_InsideAddRedbRoute_LoadsAtContextStart() { var services = new ServiceCollection(); services.AddRedbRoute(route => route.AddXmlRoutesFromContent(""" """, "di.xml")); await using var provider = services.BuildServiceProvider(); var context = provider.GetRequiredService(); // The hosted service applies configurators before Start; the test does the same by hand. foreach (var configurator in provider.GetServices()) configurator.Configure(context); await context.Start(); try { var producer = context.GetEndpoint("direct://di-in").CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("x")); await producer.Process(exchange); context.Routes.Select(r => r.RouteId).Should().Contain("di-route"); exchange.In.Headers["via"].Should().Be("di"); } finally { await context.DisposeAsync(); } } [Fact] public async Task BrokenXml_RegisteredInDi_FailsWhenConfiguratorsApply() { var services = new ServiceCollection(); services.AddRedbRoute(route => route.AddXmlRoutesFromContent(""" """, "di-broken.xml")); await using var provider = services.BuildServiceProvider(); var context = provider.GetRequiredService(); try { var act = () => { foreach (var configurator in provider.GetServices()) configurator.Configure(context); }; act.Should().Throw().WithMessage("*di-broken.xml*nosuch*"); } finally { await context.DisposeAsync(); } } } Path: redb-route/tests/redb.Route.Tests.Xml/EditorResourcesTests.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.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/EditorResourcesTests.cs ---- using System.Text.Json; using System.Xml.Linq; using AwesomeAssertions; using redb.Route.Xml; namespace redb.Route.Tests.Xml; /// /// The VS Code extension reads four generated resources: media/redb-route-1.0.catalog.xsd (the schema /// catalog.xml binds the namespace to, so it is the one the editor validates a document against), /// media/redb-route-1.0.xsd, media/redb-route-elements.json (palette and property panels) and media/redb-route-dataformats.json (formats on <dataFormat> and <marshal type>). Regenerating /// them is a hand step at release time, and nothing noticed when /// it was skipped: <route tracing="false"> reached the engine in 4.2.2, the editor went on /// refusing the attribute, and logHandled/logContinued were about to repeat it (2026-10-08). /// /// The resources are generated WITH the package contributions, so the committed files carry more than the /// core list of this test project: what is pinned is that every core element and every core attribute is /// among them, not equality of the files. /// public class EditorResourcesTests { private static readonly ElementRegistry Registry = ElementRegistry.CreateDefault(); private static string MediaDir { get; } = Locate(); private static string Locate() { var probed = new List(); for (var current = new DirectoryInfo(AppContext.BaseDirectory); current is not null; current = current.Parent) { var candidate = Path.Combine(current.FullName, "redb.Route", "tools", "vscode-redb-route", "media"); probed.Add(candidate); if (Directory.Exists(candidate)) return candidate; } throw new DirectoryNotFoundException( "The extension's media directory was not found above the test output. Probed: " + string.Join("; ", probed)); } /// Every attribute a schema declares per element name (a nested element's attributes count to /// its parent too — a superset is harmless for the check below). private static Dictionary> DeclaredAttributes(string schemaPath) { var document = XDocument.Load(schemaPath); var xs = document.Root!.Name.Namespace; var declared = new Dictionary>(StringComparer.Ordinal); // An element declared with type="r:name" (the step , type beanStep) carries its attributes in the // named complex type, not below itself. var namedTypes = document.Root.Elements(xs + "complexType") .Where(t => t.Attribute("name") is not null) .ToDictionary(t => (string)t.Attribute("name")!, StringComparer.Ordinal); foreach (var element in document.Descendants(xs + "element")) { if ((string?)element.Attribute("name") is not { } name) continue; if (!declared.TryGetValue(name, out var attributes)) declared[name] = attributes = new HashSet(StringComparer.Ordinal); var sources = new List { element }; if ((string?)element.Attribute("type") is { } typeName && namedTypes.TryGetValue(typeName[(typeName.IndexOf(':') + 1)..], out var namedType)) sources.Add(namedType); foreach (var attribute in sources.SelectMany(s => s.Descendants(xs + "attribute"))) if ((string?)attribute.Attribute("name") is { } attributeName) attributes.Add(attributeName); } return declared; } private static List MissingCoreAttributes(Dictionary> declared) { var missing = new List(); foreach (var contribution in Registry.Contributions) { var spec = contribution.Spec; foreach (var attribute in spec.Attributes) if (!declared.TryGetValue(spec.Name, out var attributes) || !attributes.Contains(attribute.Name)) missing.Add($"<{spec.Name} {attribute.Name}=\"...\">"); } return missing; } [Fact] public void CatalogSchema_DeclaresEveryCoreAttribute() { // The schema the editor actually validates against: an attribute missing here is underlined in every // document that uses it, however well the engine accepts it. var path = Path.Combine(MediaDir, "redb-route-1.0.catalog.xsd"); MissingCoreAttributes(DeclaredAttributes(path)).Should().BeEmpty( $"{Path.GetFileName(path)} is regenerated from the element list — " + "run redb-route-xml catalog, elements and xsd with --bin and commit the result"); } [Fact] public void LightweightSchema_DeclaresEveryCoreAttribute() { var path = Path.Combine(MediaDir, "redb-route-1.0.xsd"); MissingCoreAttributes(DeclaredAttributes(path)).Should().BeEmpty( $"{Path.GetFileName(path)} is regenerated together with the catalog schema"); } [Fact] public void CatalogSchema_Compiles() { // The file the editor binds through catalog.xml: a schema that does not compile is no schema at all, // and the editor reports the damage on every document rather than at its own load (2026-09-20, a // component whose path synonym was also an option declared one attribute twice). var path = Path.Combine(MediaDir, "redb-route-1.0.catalog.xsd"); var errors = new List(); var set = new System.Xml.Schema.XmlSchemaSet(); set.ValidationEventHandler += (_, e) => errors.Add(e.Message); set.Add("urn:redb:route:1.0", System.Xml.XmlReader.Create(path)); set.Compile(); errors.Should().BeEmpty($"{Path.GetFileName(path)} must compile against the namespace catalog.xml binds"); } [Fact] public void ElementsJson_ListsEveryCoreElementAndItsAttributes() { var path = Path.Combine(MediaDir, "redb-route-elements.json"); using var document = JsonDocument.Parse(File.ReadAllText(path)); var declared = new Dictionary>(StringComparer.Ordinal); foreach (var element in document.RootElement.EnumerateArray()) { var name = element.GetProperty("name").GetString()!; declared[name] = element.GetProperty("attributes").EnumerateArray() .Select(attribute => attribute.GetProperty("name").GetString()!) .ToHashSet(StringComparer.Ordinal); } MissingCoreAttributes(declared).Should().BeEmpty( $"{Path.GetFileName(path)} drives the palette and the property panel, so an element or an " + "attribute missing from it is one the editor cannot offer"); } /// /// The data formats this test project carries, with the markup attributes their type binds (the serializer's own /// writable properties with a parameterless constructor, else its options object's), in the value types an /// attribute can carry. The committed catalog must list each, by name and type, with every such attribute. /// [Theory] [InlineData(typeof(redb.Route.DataFormats.XmlJson.XmlJsonDataFormat), "xmljson")] [InlineData(typeof(redb.Route.DataFormats.Mime.MimeMultipartDataFormat), "mimeMultipart")] public void DataFormatsJson_ListsEveryFormatAndItsAttributes(Type format, string name) { var path = Path.Combine(MediaDir, "redb-route-dataformats.json"); using var document = JsonDocument.Parse(File.ReadAllText(path)); var typeName = $"{format.FullName}, {format.Assembly.GetName().Name}"; var entry = document.RootElement.EnumerateArray() .FirstOrDefault(e => e.GetProperty("type").GetString() == typeName); entry.ValueKind.Should().Be(JsonValueKind.Object, $"{Path.GetFileName(path)} is regenerated with the data format bins; {typeName} is missing from it"); entry.GetProperty("name").GetString().Should().Be(name); var listed = entry.GetProperty("attributes").EnumerateArray().Select(a => a.GetProperty("name").GetString()!).ToHashSet(); MarkupAttributes(format).Except(listed).Should().BeEmpty( $"{Path.GetFileName(path)} drives completion on and ; regenerate it"); } private static IEnumerable MarkupAttributes(Type format) { var target = format.GetConstructor(Type.EmptyTypes) is not null ? format : format.GetConstructors().Select(c => c.GetParameters()).First(p => p.Length == 1)[0].ParameterType; Type[] carried = [typeof(string), typeof(bool), typeof(int), typeof(long), typeof(double), typeof(float), typeof(decimal), typeof(TimeSpan)]; return target.GetProperties() .Where(p => p.SetMethod is { IsPublic: true }) .Where(p => (Nullable.GetUnderlyingType(p.PropertyType) ?? p.PropertyType) is var t && (t.IsEnum || carried.Contains(t))) .Select(p => char.ToLowerInvariant(p.Name[0]) + p.Name[1..]); } } Path: redb-route/tests/redb.Route.Tests.Xml/EndpointChildSchemaTests.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.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/EndpointChildSchemaTests.cs ---- using System.Runtime.CompilerServices; using System.Text.RegularExpressions; using System.Xml; using System.Xml.Linq; using System.Xml.Schema; using AwesomeAssertions; using redb.Route.Core; using redb.Route.Xml; namespace redb.Route.Tests.Xml; /// /// The structured endpoint child in the schema the loader validates against (no component catalog). The wildcard /// used to be processContents="lax", which validates a child against a global declaration of the same name: /// <to><bean path/></to> was read as the bean declaration and <to><log/></to> /// as the log step, and both were refused. It is skip now; the child is checked where the endpoint is bound. /// The change may only accept more: every document the old schema accepted is still accepted. /// public class EndpointChildSchemaTests : IAsyncLifetime { private readonly RouteContext _context = new(); public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { await _context.DisposeAsync(); GC.SuppressFinalize(this); } /// /// The root of the redb.Route tree: redb.Route/ in the monorepo, the repository root of the public /// mirror. The test file sits two levels below it in both (tests/redb.Route.Tests.Xml/). /// private static string RouteTreeRoot([CallerFilePath] string file = "") => Path.GetFullPath(Path.Combine(Path.GetDirectoryName(file)!, "..", "..")); /// /// Documents of the redb.Route tree alone, the set the public mirror also has: 231 here on 2026-11-05, of which /// at most 5 are docs examples the mirror does not ship. /// private const int RouteTreeDocumentsAtLeast = 200; /// The schema as it was: the same generated document with the endpoint wildcard back on lax. private static XmlSchemaSet PreviousCoreSchema() { var document = XmlRouteSchema.Generate(ElementRegistry.CreateDefault()); XNamespace xs = "http://www.w3.org/2001/XMLSchema"; var wildcards = document.Descendants(xs + "any") .Where(a => (string?)a.Attribute("processContents") == "skip" && (string?)a.Attribute("namespace") == "##targetNamespace") .ToList(); wildcards.Should().NotBeEmpty("the no-catalog endpoint wildcard is the one this change touched"); foreach (var wildcard in wildcards) wildcard.SetAttributeValue("processContents", "lax"); var set = new XmlSchemaSet(); using var reader = document.CreateReader(); set.Add(XmlRouteLoader.Namespace, reader); set.Compile(); return set; } private static string[] Problems(XDocument document, XmlSchemaSet schema) => [.. XmlRouteSchema.Validate(document, schema).Select(p => $"{p.Line}:{p.Column}: {p.Message}")]; /// Step names and the bean declaration that a component of a default context shares. private string[] CollidingSchemes() { var elements = ElementRegistry.CreateDefault().Contributions.Select(c => c.Name).Append("bean").ToHashSet(StringComparer.Ordinal); return [.. _context.GetComponentNames().Where(elements.Contains).Order(StringComparer.Ordinal)]; } [Fact] public void EveryComponentNamedLikeAnElement_LoadsAsAStructuredChild_WithoutACatalog() { var colliding = CollidingSchemes(); colliding.Should().Contain(["bean", "log"], "the two reported collisions are among them"); foreach (var scheme in colliding) { var document = XDocument.Parse($""" <{scheme} path="#target" method="M"/> """, LoadOptions.SetLineInfo); Problems(document, XmlRouteSchema.CoreSet).Should().BeEmpty($"<{scheme}/> is an endpoint child"); Problems(document, PreviousCoreSchema()).Should().NotBeEmpty( $"the lax wildcard validated <{scheme}> against the element of the same name"); } } [Fact] public void BeanAndLogChildren_LoadThroughTheLoader() { _context.AddXmlRoutesFromContent(""" """); _context.RouteBuilders.Should().ContainSingle(); } [Fact] public void EveryDocumentThePreviousSchemaAccepted_IsStillAccepted() { var previous = PreviousCoreSchema(); var documents = FixtureDocuments().ToList(); var routeTree = documents.Count(d => d.RouteTree); routeTree.Should().BeGreaterThanOrEqualTo(RouteTreeDocumentsAtLeast, "the redb.Route tree's own fixtures, present in the monorepo and in the public mirror alike"); var acceptedBefore = 0; foreach (var (source, _, document) in documents) { var before = Problems(document, previous); var after = Problems(document, XmlRouteSchema.CoreSet); after.Should().BeSubsetOf(before, $"{source}: the change may only accept more"); if (before.Length == 0) acceptedBefore++; } acceptedBefore.Should().BeGreaterThanOrEqualTo(RouteTreeDocumentsAtLeast / 2, "most fixtures are valid documents, so the subset check is not vacuous"); } [Fact] public void MalformedChildShape_IsStillAPositionedLoadError() { var act = () => _context.AddXmlRoutesFromContent(""" """); act.Should().Throw().WithMessage("*(4,*must be a family entry*"); } [Fact] public async Task UnknownOptionOnAStrictChild_IsRefusedWhereTheEndpointIsBound() { _context.AddXmlRoutesFromContent(""" """); var start = () => _context.Start(); (await start.Should().ThrowAsync()) .Which.ToString().Should().Contain("'sizee' is not an option of the Seda endpoint"); } // ── fixtures ───────────────────────────────────────────────────────────── private static readonly Regex RawXml = new("\"\"\"\\s*(?<(?:routes|context)\\b.*?)\"\"\"", RegexOptions.Singleline | RegexOptions.Compiled); /// /// Every route document the products' tests and examples load. From the redb.Route tree: XML files of the /// examples, the demos (demos/ here, demo/ in the public mirror) and the Xml tests, and the /// raw-string documents in the Xml tests. Beside the tree, when the monorepo has them: the route-xml templates and /// the raw-string documents of the Tsak tests. Interpolated documents that do not parse as written are left out. /// private static IEnumerable<(string Source, bool RouteTree, XDocument Document)> FixtureDocuments() { var route = RouteTreeRoot(); var beside = Path.GetDirectoryName(route)!; foreach (var (directory, routeTree) in new[] { (Path.Combine(route, "docs", "Route-XML", "examples"), true), (Path.Combine(route, "demos"), true), (Path.Combine(route, "demo"), true), (Path.Combine(route, "tests", "redb.Route.Tests.Xml"), true), (Path.Combine(beside, "redb.Templates", "templates", "route-xml"), false), }) { if (!Directory.Exists(directory)) continue; foreach (var file in Directory.EnumerateFiles(directory, "*.xml", SearchOption.AllDirectories).Where(NotBuildOutput)) if (TryParse(File.ReadAllText(file)) is { } document && IsRouteDocument(document)) yield return (Path.GetRelativePath(beside, file), routeTree, document); } foreach (var (directory, routeTree) in new[] { (Path.Combine(route, "tests", "redb.Route.Tests.Xml"), true), (Path.Combine(beside, "redb.Tsak", "tests"), false), }) { if (!Directory.Exists(directory)) continue; foreach (var file in Directory.EnumerateFiles(directory, "*.cs", SearchOption.AllDirectories).Where(NotBuildOutput)) { var index = 0; foreach (Match match in RawXml.Matches(File.ReadAllText(file))) { index++; if (TryParse(match.Groups["xml"].Value) is { } document && IsRouteDocument(document)) yield return ($"{Path.GetRelativePath(beside, file)}#{index}", routeTree, document); } } } } private static bool NotBuildOutput(string file) => !file.Contains($"{Path.DirectorySeparatorChar}bin{Path.DirectorySeparatorChar}", StringComparison.Ordinal) && !file.Contains($"{Path.DirectorySeparatorChar}obj{Path.DirectorySeparatorChar}", StringComparison.Ordinal); private static bool IsRouteDocument(XDocument document) => document.Root?.Name.NamespaceName == XmlRouteLoader.Namespace; private static XDocument? TryParse(string xml) { try { return XDocument.Parse(xml, LoadOptions.SetLineInfo); } catch (XmlException) { return null; } } } Path: redb-route/tests/redb.Route.Tests.Xml/EndpointRoleOptionsTests.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.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/EndpointRoleOptionsTests.cs ---- using System.Xml.Linq; using AwesomeAssertions; using redb.Route.Core; using redb.Route.Http; using redb.Route.Xml; using redb.Route.Xml.Packaging; namespace redb.Route.Tests.Xml; /// /// An option only one side of an endpoint reads ([EndpointRole]) is refused by the /// connector on the other side: username is what an http: producer sends, inboundAuth /// is what an http: consumer requires. Route-XML reads the same declaration: the catalog carries /// it, the editor schema refuses the option on the wrong side, the package gate reports it with /// its position — before the route starts. /// public sealed class EndpointRoleOptionsTests : IDisposable { private readonly string _root = Path.Combine(Path.GetTempPath(), "redb-xml-role-" + Guid.NewGuid().ToString("N")); public EndpointRoleOptionsTests() => Directory.CreateDirectory(_root); public void Dispose() => Directory.Delete(_root, recursive: true); private static readonly IReadOnlyList Catalog = ComponentCatalog.Build([new HttpComponent()]); private static Type? Resolve(string typeName) => typeof(HttpComponent).Assembly.GetType(typeName); [Fact] public void Catalog_CarriesTheSideThatReadsAnOption() { var http = Catalog.Single(c => c.Scheme == "http"); http.Options.Single(o => o.Name == "Username").Role.Should().Be(EndpointRole.Producer); http.Options.Single(o => o.Name == "InboundAuth").Role.Should().Be(EndpointRole.Consumer); http.Options.Single(o => o.Name == "Method").Role.Should().BeNull("both sides read it"); ComponentCatalog.ToJson(Catalog).Should().Contain("\"role\": \"producer\"").And.Contain("\"role\": \"consumer\""); } private static IReadOnlyList<(int Line, int Column, string Message)> Validate(string from, string to) => XmlRouteSchema.Validate(XDocument.Parse($""" {from} {to} """, LoadOptions.SetLineInfo), ElementRegistry.CreateDefault(), Catalog); [Fact] public void Schema_RefusesAnOption_OnTheSideThatDoesNotReadIt_EvenOnALenientConnector() { var problems = Validate( """""", """"""); problems.Should().Contain(p => p.Line == 3 && p.Message.Contains("username") && p.Message.Contains("producerOnlyOption")); problems.Should().Contain(p => p.Line == 4 && p.Message.Contains("inboundAuth") && p.Message.Contains("consumerOnlyOption")); } [Fact] public void Schema_AcceptsEachOption_OnItsOwnSide() => Validate( """""", """""") .Should().BeEmpty(); [Fact] public void Gate_ReportsAnOptionOnTheWrongSide_InBothForms() { var dir = RouteProjectScaffold.Create(_root, "Role"); File.WriteAllText(Path.Combine(dir, "routes", "main.route.xml"), """ """); var errors = RoutePackage.Check(dir, "p", "1.0.0", Resolve, catalog: Catalog).Errors.ToList(); errors.Should().Contain(e => e.File.StartsWith("routes/main.route.xml(3,") && e.Message.Contains("'username' is read only by the producer side of the http endpoint; creates the consumer")); errors.Should().Contain(e => e.File.StartsWith("routes/main.route.xml(4,") && e.Message.Contains("'inboundAuth' is read only by the consumer side of the http endpoint; creates the producer")); errors.Should().NotContain(e => e.File.StartsWith("routes/main.route.xml(7,") || e.File.StartsWith("routes/main.route.xml(8,"), "each option is on its own side there"); errors.Should().Contain(e => e.File.StartsWith("routes/main.route.xml(12,") && e.Message.Contains("'inboundAuth' is read only by the consumer side of the http endpoint; creates the producer"), "the structured form names the step, not the endpoint element"); } } Path: redb-route/tests/redb.Route.Tests.Xml/Examples/ExampleHarness.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.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/Examples/ExampleHarness.cs ---- using redb.Route.Abstractions; using redb.Route.Components.Bean; using redb.Route.Core; namespace redb.Route.Tests.Xml.Examples; // ── Doubles for the examples (thin sugar in the TEST project, never shipped) ────────────── // The examples reference demo types by name (`Acme.*`, connector factories). The doubles carry // the same shapes — methods the bean: URIs call, properties the sections bind — and a // mapping type resolver serves them under the example's exact type names. /// Stamps the demo exchanges: batch keys and trace ids (eip/main-pipeline examples). public class DemoStampsDouble { private int _tick; public void SetBatchIdAndBody(IExchange exchange) { var tick = Interlocked.Increment(ref _tick); exchange.In.Headers["batchId"] = $"batch-{tick % 3}"; exchange.In.Body = $"evt-{tick}"; } public void NewTraceId(IExchange exchange) => exchange.In.Headers["traceId"] = Guid.NewGuid().ToString("N"); } /// Builds the demo JSON response (main-pipeline example). public class ResponseBuilderDouble { public string Build(IExchange exchange) => $$"""{"traceId":"{{exchange.In.Headers["traceId"]}}","mode":"{{exchange.In.Headers["mode"]}}"}"""; } /// The scope diagnostics probe (scope-diag example). public class ScopeDiagProbeDouble { private int _probes; public void Reset(IExchange exchange) { _probes = 0; exchange.In.Body = Enumerable.Range(1, 50).Select(i => (object?)$"item-{i}").ToList(); } public void ProbeItem(IExchange exchange) => Interlocked.Increment(ref _probes); public void Summarize(IExchange exchange) => exchange.In.Body = $"probed:{_probes}"; } /// Type test: the body is a collection of strings (deep-dsl-showcase example). public class IsStringListDouble : IPredicate { public bool Matches(IExchange exchange) => exchange.In.Body is IEnumerable; } /// Type test: the body is a non-empty string (deep-dsl-showcase example). public class IsNonEmptyStringDouble : IPredicate { public bool Matches(IExchange exchange) => exchange.In.Body is string { Length: > 0 }; } /// Shape of the LDAP connection factory the factories example configures. public class LdapConnectionFactoryDouble { public string? Server { get; set; } public int Port { get; set; } public bool Ssl { get; set; } public string? BindDn { get; set; } public string? BindPassword { get; set; } public bool FollowReferrals { get; set; } } /// Shape of the mail connection factory the factories example configures. public class MailConnectionFactoryDouble { public string? Host { get; set; } public int Port { get; set; } public string? Security { get; set; } public string? Username { get; set; } public string? Password { get; set; } } /// Options object built as a nested anonymous bean in the factories example. public class SqlConnectionOptionsDouble { public string? ConnectionString { get; set; } } /// Constructor-injected factory, as real integrations build them (the factories example). public class SqlConnectionFactoryDouble(SqlConnectionOptionsDouble options) { public SqlConnectionOptionsDouble Options { get; } = options; } /// Registration-only component for the schemes the examples address. public sealed class SchemeStubComponent(string scheme) : ComponentBase { public override string Scheme { get; } = scheme; public override IEndpoint CreateEndpoint(EndpointUri uri) => throw new NotSupportedException($"'{Scheme}' is a registration-only stub in the example tests"); } /// Serves the example documents' exact type names with local doubles. public sealed class MappingTypeResolver : IBeanTypeResolver { private static readonly Dictionary Map = new(StringComparer.Ordinal) { ["Acme.Demo.DemoStamps, Acme.Demo"] = typeof(DemoStampsDouble), ["Acme.Demo.ResponseBuilder, Acme.Demo"] = typeof(ResponseBuilderDouble), ["Acme.Demo.Predicates.IsStringList, Acme.Demo"] = typeof(IsStringListDouble), ["Acme.Demo.Predicates.IsNonEmptyString, Acme.Demo"] = typeof(IsNonEmptyStringDouble), ["Acme.Diagnostics.ScopeDiagProbe, Acme.Diagnostics"] = typeof(ScopeDiagProbeDouble), ["redb.Route.Ldap.LdapConnectionFactory, redb.Route.Ldap"] = typeof(LdapConnectionFactoryDouble), ["redb.Route.Mail.MailConnectionFactory, redb.Route.Mail"] = typeof(MailConnectionFactoryDouble), ["redb.Route.Sql.Connection.SqlConnectionFactory, redb.Route.Sql"] = typeof(SqlConnectionFactoryDouble), ["redb.Route.Sql.Connection.SqlConnectionOptions, redb.Route.Sql"] = typeof(SqlConnectionOptionsDouble), }; public Type? Resolve(string typeName) => Map.TryGetValue(typeName, out var mapped) ? mapped : DefaultBeanTypeResolver.Instance.Resolve(typeName); } /// /// The shared setup for loading the shipped examples: the repo examples directory, a context /// with stub schemes, the mapping resolver and the examples directory as the resource root. /// internal static class ExampleHarness { internal static string Dir { get; } = Locate(); internal static RouteContext NewContext() { var context = new RouteContext(); foreach (var scheme in new[] { "http", "ldap", "smtp", "sql" }) context.AddComponent(new SchemeStubComponent(scheme)); context.AddService(typeof(IBeanTypeResolver), new MappingTypeResolver()); context.AddService(typeof(IRouteResourceResolver), new RouteResourceResolver { ResourceRoot = Dir }); // The factories example binds beans from deployment configuration; the keys without a // {{key:default}} must be present before the load — exactly the deployment contract. context.SetProperty("ldap.server", "ldap.example.test"); context.SetProperty("ldap.service.dn", "cn=svc,dc=example,dc=test"); context.SetProperty("ldap.service.password", "test-not-a-secret"); context.SetProperty("mail.host", "smtp.example.test"); context.SetProperty("mail.user", "mailer"); context.SetProperty("mail.password", "test-not-a-secret"); context.SetProperty("db.main.connection", "Host=db.example.test;Database=demo"); return context; } /// /// Every definition tree a document produced: the builder-level handlers (container /// onException / intercepts / onCompletion — they live on the builder, not among the /// routes) first, then the routes. Golden files and equivalence must see ALL of it, or a /// parse drift in the container handlers goes invisible. /// internal static IReadOnlyList Definitions(RouteContext context) { var definitions = new List(); foreach (var builder in context.RouteBuilders) { if (!builder.IsBuilt) builder.InternalBuild(context); definitions.AddRange(builder.ExceptionDefinitions); definitions.AddRange(builder.Intercepts); definitions.AddRange(builder.OnCompletions); definitions.AddRange(builder.Definitions); } return definitions; } private static string Locate() { var probed = new List(); for (var current = new DirectoryInfo(AppContext.BaseDirectory); current is not null; current = current.Parent) { var candidate = Path.Combine(current.FullName, "docs", "Route-XML", "examples"); probed.Add(candidate); if (Directory.Exists(candidate)) return candidate; } throw new DirectoryNotFoundException( "The examples directory was not found above the test output. Probed: " + string.Join("; ", probed)); } } Path: redb-route/tests/redb.Route.Tests.Xml/Examples/ExamplesCodeGenTests.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.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/Examples/ExamplesCodeGenTests.cs ---- using System.Xml.Linq; using AwesomeAssertions; using redb.Route.Xml; namespace redb.Route.Tests.Xml.Examples; /// /// Every shipped example generates C# that is committed next to the tests /// (Generated/*.cs), compiled as part of this project, and — in ExamplesGeneratedEquivalenceTests — /// executed to prove the generated tree is byte-identical to the loaded XML. The committed file /// is a golden: regenerate deliberately with REDB_XML_CODEGEN_REGEN=1, never to make a diff go /// away. /// public class ExamplesCodeGenTests { internal static string GeneratedDir { get; } = Path.Combine( Directory.GetParent(ExampleHarness.Dir)!.Parent!.Parent!.FullName, "tests", "redb.Route.Tests.Xml", "Examples", "Generated"); internal static string ClassNameFor(string fileName) { var stem = Path.GetFileName(fileName).Replace(".route.xml", "", StringComparison.Ordinal); var parts = stem.Split('-', StringSplitOptions.RemoveEmptyEntries); return string.Concat(parts.Select(p => char.ToUpperInvariant(p[0]) + p[1..])) + "Routes"; } public static TheoryData Examples() { var data = new TheoryData(); foreach (var file in Directory.GetFiles(ExampleHarness.Dir, "*.route.xml").OrderBy(f => f, StringComparer.Ordinal)) data.Add(Path.GetFileName(file)); return data; } private static string Generate(string fileName, CodeGenStyle style) { var path = Path.Combine(ExampleHarness.Dir, fileName); var document = XDocument.Load(path, LoadOptions.SetLineInfo); return XmlCodeGenerator.Generate(document, ClassNameFor(fileName), "redb.Route.Tests.Xml.Examples.Generated", style, path); } [Theory] [MemberData(nameof(Examples))] public void GeneratedCode_MatchesTheCommittedFile(string fileName) { var generated = Generate(fileName, CodeGenStyle.Readable) .Replace(ExampleHarness.Dir.Replace('\\', '/'), "", StringComparison.Ordinal); var committedPath = Path.Combine(GeneratedDir, ClassNameFor(fileName) + ".cs"); if (Environment.GetEnvironmentVariable("REDB_XML_CODEGEN_REGEN") == "1") { Directory.CreateDirectory(GeneratedDir); File.WriteAllText(committedPath, generated); return; } File.Exists(committedPath).Should().BeTrue($"the generated {ClassNameFor(fileName)}.cs must be committed"); File.ReadAllText(committedPath).Replace("\r\n", "\n", StringComparison.Ordinal) .Should().Be(generated, "a diff means either an intended generator change (explain it) or a regression"); } [Theory] [MemberData(nameof(Examples))] public void Generation_IsDeterministic(string fileName) { Generate(fileName, CodeGenStyle.Machine).Should().Be(Generate(fileName, CodeGenStyle.Machine)); } [Fact] public void MachineStyle_MapsDiagnosticsBackToTheXml() { var machine = Generate("scope-diag.route.xml", CodeGenStyle.Machine); machine.Should().Contain("#line ").And.Contain("scope-diag.route.xml\""); machine.Should().EndWith("#line default\n"); Generate("scope-diag.route.xml", CodeGenStyle.Readable).Should().NotContain("#line "); } } Path: redb-route/tests/redb.Route.Tests.Xml/Examples/ExamplesEquivalenceTests.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.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/Examples/ExamplesEquivalenceTests.cs ---- using AwesomeAssertions; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Aggregation; using redb.Route.Core; using redb.Route.Diagnostics; using redb.Route.Xml; using static redb.Route.Core.RouteBuilder; namespace redb.Route.Tests.Xml.Examples; /// /// For each example, the definition tree loaded from XML is IDENTICAL to /// the tree built by the post-V4 fluent C# — proven by comparing /// output byte-for-byte. This is the promise made executable: one engine, two spellings. /// public class ExamplesEquivalenceTests { private static string DescribeExample(string fileName) { using var context = ExampleHarness.NewContext(); context.AddXmlRoutes(Path.Combine(ExampleHarness.Dir, fileName)); return RouteDescriber.Describe(ExampleHarness.Definitions(context)); } private static string DescribeTwin(Action addRoutes) { using var context = new RouteContext(); addRoutes(context); return RouteDescriber.Describe(ExampleHarness.Definitions(context)); } [Fact] public void ScopeDiag_XmlAndCSharp_AreTheSameTree() { var twin = DescribeTwin(ctx => ctx.AddRoutes(r => r.From("timer://scope-diag?period=60000&delay=10000") .RouteId("demo-scope-diag") .Description("Diagnostics of the parallel splitter's scopes") .AutoStart(false) .Log("[SCOPE-DIAG] Starting parallel split: 50 items, maxDop=5") .To("bean:#scopeDiag?method=Reset") .Split(Expr("body")).ParallelProcessing().MaxParallelism(5) .To("bean:#scopeDiag?method=ProbeItem") .EndSplit() .To("bean:#scopeDiag?method=Summarize"))); DescribeExample("scope-diag.route.xml").Should().Be(twin); } [Fact] public void DeepDslShowcase_XmlAndCSharp_AreTheSameTree() { var twin = DescribeTwin(ctx => ctx.AddRoutes(r => { var choice1 = r.From("direct://demo-choice-richlog") .RouteId("demo-choice-richlog") .Description("Branching by body type with a rich log") .SetHeader("step", "start") .Choice(); var whenList = choice1.When(new IsStringListDouble()).Description("The body is a collection of strings") .SetHeader("branch", "list"); whenList.Log(LogLevel.Information).ShowRouteId() .Message("opening list branch").Header("branch").Property("trace") .EndLog(); var listSplit = whenList.Split(Expr("body")); listSplit.SetBody(Expr("${upper(body)}")) .Log("[tmpl] item=${body} branch=${header.branch} [${routeId}]") .Log(LogLevel.Information).ShowRouteId() .Message("[rich-tmpl] item=${body}").Header("branch").Property("item-index") .EndLog(); listSplit.EndSplit(); whenList.Log("list branch done [${routeId}]"); choice1.When(new IsNonEmptyStringDouble()).Description("The body is a non-empty string") .SetHeader("branch", "string") .SetBody(Expr("STR:${body}")); var otherwise1 = choice1.Otherwise() .SetHeader("branch", "fallback") .SetBody("FALLBACK"); var route1 = choice1.EndChoice(); route1.Log(LogLevel.Information).ShowRouteId().Message("route complete").EndLog(); var choice2 = r.From("direct://demo-trycatch-richlog") .RouteId("demo-trycatch-richlog") .Description("TryCatch with a rich log in catch") .Choice(); var when2 = choice2.When(new IsNonEmptyStringDouble()); var tryCatch = when2.TryCatch(); tryCatch.ThrowException(typeof(InvalidOperationException), "boom"); var handler = tryCatch.Catch(typeof(InvalidOperationException)); handler.Log("[tmpl] caught: ${exception.type} - ${exception.message} [${routeId}]"); handler.Log(LogLevel.Warning).ShowRouteId() .Message("[rich-tmpl] ${exception.type}: ${exception.message}") .EndLog(); handler.SetHeader("caught", "true"); handler.EndCatch(); tryCatch.EndTryCatch(); choice2.EndChoice(); var choice3 = r.From("direct://demo-nested-scopes") .RouteId("demo-nested-scopes") .Description("Nested scopes: choice - when - split - richLog") .Choice(); var when3 = choice3.When("true"); var split3 = when3.Split(Expr("body")); split3.Log(LogLevel.Information).Message("inside").EndLog(); split3.Log("item=${body}"); split3.EndSplit(); var route3 = choice3.EndChoice(); route3.SetHeader("after-close", "ok") .Log("nested scopes demo done"); })); DescribeExample("deep-dsl-showcase.route.xml").Should().Be(twin); } [Fact] public void Eip_XmlAndCSharp_AreTheSameTree() { var twin = DescribeTwin(ctx => ctx.AddRoutes(r => { r.From("timer://agg-source?period=2000&repeatCount=9") .RouteId("demo-aggregator") .Description("Aggregator: 3 events of one batch into one") .To("bean:#demoStamps?method=SetBatchIdAndBody") .Log("[AGG] Event: batchId=${header.batchId}, body=${body}") .Aggregate("${header.batchId}", AggregationStrategies.ByName("concat: + "), completionSize: 3) .ForceCompletionOnStop() .Log("[AGG] Aggregated 3 events: ${body}") .EndAggregate(); r.From("direct://demo-multicast") .RouteId("demo-multicast") .Description("Broadcast to three endpoints") .Log("[MCAST] Broadcasting to 3 endpoints...") .Multicast().ParallelProcessing() .To("direct://mcast-a") .To("direct://mcast-b") .To("direct://mcast-c") .EndMulticast() .Log("[MCAST] All endpoints received the message"); r.From("direct://mcast-a").RouteId("demo-mcast-a") .Log("[MCAST-A] Received copy: ${body}") .SetHeader("mcast.a", "done"); r.From("direct://mcast-b").RouteId("demo-mcast-b") .Log("[MCAST-B] Received copy: ${body}") .Delay(TimeSpan.FromMilliseconds(100)) .Log("[MCAST-B] Done after 100ms delay"); r.From("direct://mcast-c").RouteId("demo-mcast-c") .Log("[MCAST-C] Received copy: ${body}") .SetHeader("mcast.c", "done"); r.From("direct://demo-recipient-list") .RouteId("demo-recipient-list") .Description("Dynamic list of recipients") .Log("[RCPT] Routing to dynamic recipients: targets=${header.targets}") .RecipientList("${header.targets}", ",", parallelProcessing: true) .Log("[RCPT] All recipients processed"); r.From("direct://rcpt-a").RouteId("demo-rcpt-a").Log("[RCPT-A] Got message: ${body}"); r.From("direct://rcpt-b").RouteId("demo-rcpt-b").Log("[RCPT-B] Got message: ${body}"); r.From("direct://demo-dynamic-router") .RouteId("demo-dynamic-router") .Description("Step-by-step routing by state") .SetProperty("router.step", Expr("0")) .Log("[DROUTER] Starting dynamic routing...") .DynamicRouter("property.router.step == 0 ? 'direct://drouter-validate' : (property.router.step == 1 ? 'direct://drouter-transform' : (property.router.step == 2 ? 'direct://drouter-store' : null))") .Log("[DROUTER] Complete, went through ${property.router.step} hops"); r.From("direct://drouter-validate").RouteId("demo-drouter-validate") .Log("[DROUTER] Step 1: Validate") .SetHeader("validated", "true") .SetProperty("router.step", Expr("${property.router.step + 1}")); r.From("direct://drouter-transform").RouteId("demo-drouter-transform") .Log("[DROUTER] Step 2: Transform") .SetBody(Expr("${upper(body)}")) .SetProperty("router.step", Expr("${property.router.step + 1}")); r.From("direct://drouter-store").RouteId("demo-drouter-store") .Log("[DROUTER] Step 3: Store - body=${body}") .SetProperty("router.step", Expr("${property.router.step + 1}")); r.From("direct://demo-loop") .RouteId("demo-loop") .Description("Loop: the body grows on every iteration") .Log("[LOOP] Looping 3 times...") .Loop(3) .Log("[LOOP] iteration...") .SetBody(Expr("${body + '-loop'}")) .EndLoop() .Log("[LOOP] Result: ${body}"); r.From("direct://demo-resequencer") .RouteId("demo-resequencer") .Description("Restoring the order by seqNum") .Log("[RESEQ] Received seq=${header.seqNum}: ${body}") .Resequence("${header.seqNum}", 5, TimeSpan.FromSeconds(3)) .Log("[RESEQ] Delivered in order: seq=${header.seqNum}, body=${body}") .EndResequence(); r.From("direct://demo-enrich") .RouteId("demo-enrich") .Description("Enrichment: the reply into the header enriched.data") .Log("[ENRICH] Original body: ${body}") .Enrich("direct://enrichment-source", AggregationStrategies.ByName("intoHeader:enriched.data")) .Log("[ENRICH] Enriched: body=${body}, enriched.data=${header.enriched.data}"); r.From("direct://enrichment-source").RouteId("demo-enrichment-source") .Log("[ENRICH-SRC] Providing enrichment data") .SetBody(Expr("extra-info-for-${header.traceId ?? 'unknown'}")) .Log("[ENRICH-SRC] Returning: ${body}"); r.From("direct://demo-idempotent") .RouteId("demo-idempotent") .Description("Deduplication by messageId") .Log("[IDEMP] messageId=${header.messageId}") .IdempotentConsumer("${header.messageId}", "idempotentRepo", skipDuplicate: true) .Log("[IDEMP] First time seeing this message, processing...") .SetHeader("idempotent.processed", "true") .Log("[IDEMP] Done") .EndIdempotentConsumer(); var throttle = r.From("direct://demo-throttle") .RouteId("demo-throttle") .Description("Rate limit: 5/sec") .Log("[THROTTLE] Incoming request...") .Throttle(5); throttle.Period(TimeSpan.FromSeconds(1)); throttle .Log("[THROTTLE] Passed rate limiter (5/sec)") .Log("[THROTTLE] Done") .EndThrottle(); })); DescribeExample("eip.route.xml").Should().Be(twin); } [Fact] public void MainPipeline_XmlAndCSharp_AreTheSameTree() { var schemaJson = File.ReadAllText(Path.Combine(ExampleHarness.Dir, "resources", "message.schema.json")); var twin = DescribeTwin(ctx => ctx.AddRoutes(r => { var onException = r.OnException(typeof(Exception)); onException.Description("Global handler of all demo routes"); onException.Handled() .MaximumRedeliveries(2) .RedeliveryDelay(TimeSpan.FromSeconds(1)) .UseExponentialBackOff() .BackOffMultiplier(2.0) .Log("[GLOBAL-ERR] route=${routeId}: ${exception.type} - ${exception.message}, body=${body}", LogLevel.Error) .Log("[GLOBAL-ERR] ${exception.message} - handled after retries"); var entry = r.From("http:{{demo.http.listen:0.0.0.0:5088}}/api/demo?inOut=true") .RouteId("demo-http-entry") .Description("HTTP entry of the demo pipeline") .ConvertBody(typeof(string)) .Throttle(10) .Log("[1-HTTP] Received: body=${body}, contentType=${contentType}") .To("bean:#stamps?method=NewTraceId") .SetHeader("startedAt", Expr("${dateformat(now(), 'o')}")) .Log("[1-HTTP] traceId=${header.traceId}, mode=${header.mode}, priority=${header.priority}") .ValidateJsonSchema(schemaJson, throwOnFailure: true) .Log("[1-HTTP] JSON schema valid") .IdempotentConsumer("${header.traceId}", "idempotentRepo") .Log("[1-HTTP] Not a duplicate") .To("direct://pipeline") .EndIdempotentConsumer(); entry.EndThrottle(); var pipeline = r.From("direct://pipeline") .RouteId("demo-pipeline") .Description("Main processing pipeline") .Log("[2-PIPE] Pipeline started, traceId=${header.traceId}"); var filter = pipeline.Filter("length(body) > 0") .Log("[2-PIPE] Body is non-empty"); var choice = filter.Choice(); var whenFull = choice.When("header.mode == 'full'") .SetHeader("fastTrack", Expr("header.priority == 'high' ? 'true' : 'false'")); var normalize = whenFull.TryCatch(); normalize .Filter("!(header.priority == 'high' || header.priority == 'normal' || header.priority == 'low')") .ThrowException(typeof(InvalidOperationException), "unknown priority") .EndFilter(); normalize.SetHeader("stamp.dsl.priority", Expr("${header.priority}")); var caught = normalize.Catch(typeof(InvalidOperationException)); caught.Log(LogLevel.Warning).ShowRouteId() .Message("priority normalization failed: ${exception.type}") .Header("priority") .EndLog(); caught.SetHeader("stamp.dsl.priority", "unknown") .SetHeader("stamp.dsl.caught", "true"); caught.EndCatch(); normalize.EndTryCatch(); whenFull.SetHeader("stamp.dsl", "full-branch"); choice.When("header.mode == 'short'") .SetHeader("fastTrack", "false") .SetHeader("stamp.dsl", "short-branch"); choice.Otherwise() .SetHeader("mode", "default") .SetHeader("fastTrack", "false") .SetHeader("stamp.dsl", "default-branch"); choice.EndChoice(); filter.Log(LogLevel.Information).ShowRouteId() .Message("pipeline branch decided") .Header("mode").Header("priority").Header("fastTrack") .Header("stamp.dsl").Header("stamp.dsl.priority") .EndLog(); filter.Log("[2-PIPE] mode=${header.mode}, fastTrack=${header.fastTrack}"); filter.Traced("broker-roundtrips") .Log("[3-RABBIT] Sending to RabbitMQ RPC...") .To("{{demo.rabbit.producer}}") .Log("[3-RABBIT] stamp.rabbit=${header.stamp.rabbit}") .Log("[4-AMQP] Sending to AMQP/Artemis RPC...") .To("{{demo.amqp.producer}}") .Log("[4-AMQP] stamp.amqp=${header.stamp.amqp}") .Log("[5-GRPC] Sending to gRPC server...") .To("{{demo.grpc.producer}}") .Log("[5-GRPC] stamp.grpc=${header.stamp.grpc}") .Log("[6-WMQ] Sending to IBM MQ RPC...") .To("{{demo.wmq.rpc.producer}}") .Log("[6-WMQ] stamp.wmq=${header.stamp.wmq}") .EndTraced(); filter.ConvertBody(typeof(string)) .Log("[5-GRPC] Body converted to string: ${body}") .Log("[5b-DVM] Calling direct-vm://enricher...") .To("direct-vm://enricher") .Log("[5b-DVM] stamp.vm=${header.stamp.vm}") .SetProperty("originalBody", Expr("${body}")); var metered = filter.Metered("sql-operations"); metered.BeginTransaction(); metered.Log("[6-TX] Transaction opened") .Log("[6-SQL] INSERT demo_log: traceId=${header.traceId}, mode=${header.mode}") .To("{{demo.sql.insert}}") .Log("[6-SQL] Insert complete") .Log("[6b-SQL] SELECT last 5 rows from demo_log") .To("{{demo.sql.select}}") .Split(Expr("body")) .Log("[6b-SQL] row: id=${body['id']}, msg=${body['message']}, status=${body['status']}") .EndSplit(); metered.CommitTransaction(); metered.Log("[6-TX] Transaction committed"); metered.EndMetered(); filter.SetBody(Expr("${property.originalBody ?? body}")) .Log("[6-RESTORE] Body restored: ${body}") .WireTap("{{demo.kafka.wiretap}}") .Log("[7-TAP] Kafka: demo-audit topic") .WireTap("direct://demo-file-audit") .Log("[7-TAP] File: output/traceId.json") .WireTap("vm://audit-log") .Log("[7-TAP] VM: async audit-log queue") .WireTap("direct://demo-redis-pub") .WireTap("direct://demo-mqtt-pub") .WireTap("direct://demo-wmq-pub") .WireTap("direct://demo-seda-send") .Log("[8-DONE] Pipeline complete for traceId=${header.traceId}") .SetHeader("Content-Type", "application/json") .To("bean:#responseBuilder?method=Build"); filter.EndFilter(); r.From("direct://demo-file-audit").RouteId("demo-file-audit") .To("bean:#responseBuilder?method=Build") .To("{{demo.file.wiretap}}"); r.From("{{demo.rabbit.consumer}}").RouteId("demo-rabbit-worker") .Log("[RABBIT-W] Received: ${body}") .SetHeader("stamp.rabbit", Expr("ok:${dateformat(now(), 'HH:mm:ss.fff')}")) .Log("[RABBIT-W] Stamped, replying"); r.From("{{demo.amqp.consumer}}").RouteId("demo-amqp-worker") .Log("[AMQP-W] Received: ${body}") .SetHeader("stamp.amqp", Expr("ok:${dateformat(now(), 'HH:mm:ss.fff')}")) .Log("[AMQP-W] Stamped, replying"); r.From("{{demo.grpc.consumer}}").RouteId("demo-grpc-worker") .Log("[GRPC-W] Received: ${body}") .SetHeader("stamp.grpc", Expr("ok:${dateformat(now(), 'HH:mm:ss.fff')}")) .Log("[GRPC-W] Stamped, replying"); r.From("{{demo.wmq.rpc.consumer}}").RouteId("demo-wmq-worker") .Log("[WMQ-W] Received: ${body}") .SetHeader("stamp.wmq", Expr("ok:${dateformat(now(), 'HH:mm:ss.fff')}")) .Log("[WMQ-W] Stamped, replying"); r.From("direct-vm://enricher").RouteId("demo-vm-enricher") .Log("[DVM-W] Enriching: traceId=${header.traceId}") .SetHeader("stamp.vm", Expr("enriched:${dateformat(now(), 'HH:mm:ss.fff')}")) .Log("[DVM-W] Enriched, returning"); r.From("vm://audit-log?concurrentConsumers=2").RouteId("demo-vm-audit") .Log("[VM-AUDIT] Audit event: traceId=${header.traceId}, mode=${header.mode}") .SetHeader("audit.processed", Expr("${header.traceId}:${header.mode}:${dateformat(now(), 'HH:mm:ss.fff')}")) .Log("[VM-AUDIT] Processed: ${header.audit.processed}"); })); DescribeExample("main-pipeline.route.xml").Should().Be(twin); } } Path: redb-route/tests/redb.Route.Tests.Xml/Examples/ExamplesGeneratedEquivalenceTests.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.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/Examples/ExamplesGeneratedEquivalenceTests.cs ---- using AwesomeAssertions; using redb.Route.Core; using redb.Route.Diagnostics; using redb.Route.Xml; namespace redb.Route.Tests.Xml.Examples; /// /// The mechanical honesty check: the committed generated builders (compiled /// as part of this project) produce definition trees BYTE-IDENTICAL to loading the source XML. /// This is what catches a wrong overload, a lost attribute, an eaten branch or a swapped /// argument in the generator. /// public class ExamplesGeneratedEquivalenceTests { private static string DescribeXml(string fileName) { using var context = ExampleHarness.NewContext(); context.AddXmlRoutes(Path.Combine(ExampleHarness.Dir, fileName)); return RouteDescriber.Describe(ExampleHarness.Definitions(context)); } private static string DescribeGenerated(RouteBuilder builder) { using var context = ExampleHarness.NewContext(); context.AddRoutes(builder); return RouteDescriber.Describe(ExampleHarness.Definitions(context)); } [Fact] public void ScopeDiag_GeneratedCode_IsTheSameTree() => DescribeGenerated(new Generated.ScopeDiagRoutes()).Should().Be(DescribeXml("scope-diag.route.xml")); [Fact] public void Eip_GeneratedCode_IsTheSameTree() => DescribeGenerated(new Generated.EipRoutes()).Should().Be(DescribeXml("eip.route.xml")); [Fact] public void DeepDslShowcase_GeneratedCode_IsTheSameTree() => DescribeGenerated(new Generated.DeepDslShowcaseRoutes()).Should().Be(DescribeXml("deep-dsl-showcase.route.xml")); [Fact] public void Factories_GeneratedCode_IsTheSameTree() => DescribeGenerated(new Generated.FactoriesRoutes()).Should().Be(DescribeXml("factories.route.xml")); [Fact] public void MainPipeline_GeneratedCode_IsTheSameTree() => DescribeGenerated(new Generated.MainPipelineRoutes()).Should().Be(DescribeXml("main-pipeline.route.xml")); } Path: redb-route/tests/redb.Route.Tests.Xml/Examples/ExamplesGoldenTests.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.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/Examples/ExamplesGoldenTests.cs ---- using AwesomeAssertions; using redb.Route.Diagnostics; using redb.Route.Xml; namespace redb.Route.Tests.Xml.Examples; /// /// Every shipped example loads through the real loader (stub schemes, mapped /// bean types, the examples directory as the resource root) and its description matches the /// committed golden file. A golden is NEVER updated to make a test green: a diff means either /// an intended semantic change (explained in the commit) or a parser regression. Regenerate /// deliberately with REDB_XML_GOLDEN_REGEN=1. /// public class ExamplesGoldenTests { public static TheoryData Examples() { var data = new TheoryData(); foreach (var file in Directory.GetFiles(ExampleHarness.Dir, "*.route.xml").OrderBy(f => f, StringComparer.Ordinal)) data.Add(Path.GetFileName(file)); return data; } [Theory] [MemberData(nameof(Examples))] public async Task Example_LoadsAndMatchesItsGolden(string fileName) { var path = Path.Combine(ExampleHarness.Dir, fileName); await using var context = ExampleHarness.NewContext(); context.AddXmlRoutes(path); var described = RouteDescriber.Describe(ExampleHarness.Definitions(context)); var goldenPath = Path.ChangeExtension(path, null) + ".expected.txt"; // x.route.xml → x.route.expected.txt if (Environment.GetEnvironmentVariable("REDB_XML_GOLDEN_REGEN") == "1") { File.WriteAllText(goldenPath, described); return; } File.Exists(goldenPath).Should().BeTrue($"the golden {Path.GetFileName(goldenPath)} must be committed next to the example"); var golden = File.ReadAllText(goldenPath).Replace("\r\n", "\n", StringComparison.Ordinal); described.Should().Be(golden); } [Theory] [MemberData(nameof(Examples))] public async Task Example_RendersItsMermaidDiagram(string fileName) { var path = Path.Combine(ExampleHarness.Dir, fileName); await using var context = ExampleHarness.NewContext(); context.AddXmlRoutes(path); var diagram = Route.Diagnostics.MermaidRenderer.Render(ExampleHarness.Definitions(context)); diagram.Should().StartWith("flowchart TD", "top-down is the default: Mermaid cannot wrap a long chain, vertical scrolls like text"); var goldenPath = Path.ChangeExtension(path, null) + ".mmd"; // x.route.xml → x.route.mmd if (Environment.GetEnvironmentVariable("REDB_XML_GOLDEN_REGEN") == "1") { File.WriteAllText(goldenPath, diagram); return; } File.Exists(goldenPath).Should().BeTrue($"the diagram {Path.GetFileName(goldenPath)} must be committed next to the example"); File.ReadAllText(goldenPath).Replace("\r\n", "\n", StringComparison.Ordinal).Should().Be(diagram); } } Path: redb-route/tests/redb.Route.Tests.Xml/Examples/Generated/DeepDslShowcaseRoutes.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.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/Examples/Generated/DeepDslShowcaseRoutes.cs ---- // /deep-dsl-showcase.route.xml — do not edit; regenerate instead. /> #nullable enable using System; using System.Collections.Generic; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Aggregation; using redb.Route.ControlBus; using redb.Route.Core; using redb.Route.Transactions; using redb.Route.Xml; using redb.Route.Xslt; namespace redb.Route.Tests.Xml.Examples.Generated; /// A generated route builder — see the header for the source file. public sealed class DeepDslShowcaseRoutes : RouteBuilder { protected override void Configure() { Context!.AddToRegistry("isStringList", XmlBeans.Create(Context!, "Acme.Demo.Predicates.IsStringList, Acme.Demo", [], [])); Context!.AddToRegistry("isNonEmptyString", XmlBeans.Create(Context!, "Acme.Demo.Predicates.IsNonEmptyString, Acme.Demo", [], [])); // Branching by body type with a rich log var route0 = From("direct://demo-choice-richlog"); route0.RouteId("demo-choice-richlog"); route0.Description("Branching by body type with a rich log"); route0.SetHeader("step", "start"); var s1 = route0.Choice(); var b2 = s1.When(Context!.GetFromRegistry("isStringList")!); b2.Description("The body is a collection of strings"); b2.SetHeader("branch", "list"); var s3 = b2.Log(LogLevel.Information); s3.ShowRouteId(); s3.Message("opening list branch"); s3.Header("branch"); s3.Property("trace"); s3.EndLog(); var s4 = b2.Split(Expr("body")); s4.SetBody(Expr("${upper(body)}")); s4.Log("[tmpl] item=${body} branch=${header.branch} [${routeId}]"); var s5 = s4.Log(LogLevel.Information); s5.ShowRouteId(); s5.Message("[rich-tmpl] item=${body}"); s5.Header("branch"); s5.Property("item-index"); s5.EndLog(); s4.EndSplit(); b2.Log("list branch done [${routeId}]"); var b6 = s1.When(Context!.GetFromRegistry("isNonEmptyString")!); b6.Description("The body is a non-empty string"); b6.SetHeader("branch", "string"); b6.SetBody(Expr("STR:${body}")); var b7 = s1.Otherwise(); b7.SetHeader("branch", "fallback"); b7.SetBody("FALLBACK"); s1.EndChoice(); var s8 = route0.Log(LogLevel.Information); s8.ShowRouteId(); s8.Message("route complete"); s8.EndLog(); // TryCatch with a rich log in catch var route9 = From("direct://demo-trycatch-richlog"); route9.RouteId("demo-trycatch-richlog"); route9.Description("TryCatch with a rich log in catch"); var s10 = route9.Choice(); var b11 = s10.When(Context!.GetFromRegistry("isNonEmptyString")!); var s12 = b11.TryCatch(); s12.ThrowException(typeof(global::System.InvalidOperationException), "boom"); var b13 = s12.Catch(typeof(global::System.InvalidOperationException)); b13.Log("[tmpl] caught: ${exception.type} - ${exception.message} [${routeId}]"); var s14 = b13.Log(LogLevel.Warning); s14.ShowRouteId(); s14.Message("[rich-tmpl] ${exception.type}: ${exception.message}"); s14.EndLog(); b13.SetHeader("caught", "true"); b13.EndCatch(); s12.EndTryCatch(); s10.EndChoice(); // Nested scopes: choice - when - split - richLog var route15 = From("direct://demo-nested-scopes"); route15.RouteId("demo-nested-scopes"); route15.Description("Nested scopes: choice - when - split - richLog"); var s16 = route15.Choice(); var b17 = s16.When("true"); var s18 = b17.Split(Expr("body")); var s19 = s18.Log(LogLevel.Information); s19.Message("inside"); s19.EndLog(); s18.Log("item=${body}"); s18.EndSplit(); s16.EndChoice(); route15.SetHeader("after-close", "ok"); route15.Log("nested scopes demo done"); } } Path: redb-route/tests/redb.Route.Tests.Xml/Examples/Generated/EipRoutes.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.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/Examples/Generated/EipRoutes.cs ---- // /eip.route.xml — do not edit; regenerate instead. /> #nullable enable using System; using System.Collections.Generic; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Aggregation; using redb.Route.ControlBus; using redb.Route.Core; using redb.Route.Transactions; using redb.Route.Xml; using redb.Route.Xslt; namespace redb.Route.Tests.Xml.Examples.Generated; /// A generated route builder — see the header for the source file. public sealed class EipRoutes : RouteBuilder { protected override void Configure() { Context!.AddToRegistry("idempotentRepo", XmlBeans.Create(Context!, "redb.Route.Processors.InMemoryIdempotentRepository, redb.Route", [], [])); Context!.AddToRegistry("demoStamps", XmlBeans.Create(Context!, "Acme.Demo.DemoStamps, Acme.Demo", [], [])); // Aggregator: 3 events of one batch into one var route0 = From("timer://agg-source?period=2000&repeatCount=9"); route0.RouteId("demo-aggregator"); route0.Description("Aggregator: 3 events of one batch into one"); route0.To("bean:#demoStamps?method=SetBatchIdAndBody"); route0.Log("[AGG] Event: batchId=${header.batchId}, body=${body}"); var s1 = route0.Aggregate("${header.batchId}", AggregationStrategies.ByName("concat: + "), null, 3); s1.ForceCompletionOnStop(); s1.Log("[AGG] Aggregated 3 events: ${body}"); s1.EndAggregate(); // Broadcast to three endpoints var route2 = From("direct://demo-multicast"); route2.RouteId("demo-multicast"); route2.Description("Broadcast to three endpoints"); route2.Log("[MCAST] Broadcasting to 3 endpoints..."); var s3 = route2.Multicast(); s3.ParallelProcessing(); s3.To("direct://mcast-a"); s3.To("direct://mcast-b"); s3.To("direct://mcast-c"); s3.EndMulticast(); route2.Log("[MCAST] All endpoints received the message"); var route4 = From("direct://mcast-a"); route4.RouteId("demo-mcast-a"); route4.Log("[MCAST-A] Received copy: ${body}"); route4.SetHeader("mcast.a", "done"); var route5 = From("direct://mcast-b"); route5.RouteId("demo-mcast-b"); route5.Log("[MCAST-B] Received copy: ${body}"); route5.Delay(TimeSpan.FromMilliseconds(100)); route5.Log("[MCAST-B] Done after 100ms delay"); var route6 = From("direct://mcast-c"); route6.RouteId("demo-mcast-c"); route6.Log("[MCAST-C] Received copy: ${body}"); route6.SetHeader("mcast.c", "done"); // Dynamic list of recipients var route7 = From("direct://demo-recipient-list"); route7.RouteId("demo-recipient-list"); route7.Description("Dynamic list of recipients"); route7.Log("[RCPT] Routing to dynamic recipients: targets=${header.targets}"); route7.RecipientList("${header.targets}", ",", true); route7.Log("[RCPT] All recipients processed"); var route8 = From("direct://rcpt-a"); route8.RouteId("demo-rcpt-a"); route8.Log("[RCPT-A] Got message: ${body}"); var route9 = From("direct://rcpt-b"); route9.RouteId("demo-rcpt-b"); route9.Log("[RCPT-B] Got message: ${body}"); // Step-by-step routing by state var route10 = From("direct://demo-dynamic-router"); route10.RouteId("demo-dynamic-router"); route10.Description("Step-by-step routing by state"); route10.SetProperty("router.step", Expr("0")); route10.Log("[DROUTER] Starting dynamic routing..."); route10.DynamicRouter("property.router.step == 0 ? 'direct://drouter-validate' : (property.router.step == 1 ? 'direct://drouter-transform' : (property.router.step == 2 ? 'direct://drouter-store' : null))"); route10.Log("[DROUTER] Complete, went through ${property.router.step} hops"); var route11 = From("direct://drouter-validate"); route11.RouteId("demo-drouter-validate"); route11.Log("[DROUTER] Step 1: Validate"); route11.SetHeader("validated", "true"); route11.SetProperty("router.step", Expr("${property.router.step + 1}")); var route12 = From("direct://drouter-transform"); route12.RouteId("demo-drouter-transform"); route12.Log("[DROUTER] Step 2: Transform"); route12.SetBody(Expr("${upper(body)}")); route12.SetProperty("router.step", Expr("${property.router.step + 1}")); var route13 = From("direct://drouter-store"); route13.RouteId("demo-drouter-store"); route13.Log("[DROUTER] Step 3: Store - body=${body}"); route13.SetProperty("router.step", Expr("${property.router.step + 1}")); // Loop: the body grows on every iteration var route14 = From("direct://demo-loop"); route14.RouteId("demo-loop"); route14.Description("Loop: the body grows on every iteration"); route14.Log("[LOOP] Looping 3 times..."); var s15 = route14.Loop(3); s15.Log("[LOOP] iteration..."); s15.SetBody(Expr("${body + '-loop'}")); s15.EndLoop(); route14.Log("[LOOP] Result: ${body}"); // Restoring the order by seqNum var route16 = From("direct://demo-resequencer"); route16.RouteId("demo-resequencer"); route16.Description("Restoring the order by seqNum"); route16.Log("[RESEQ] Received seq=${header.seqNum}: ${body}"); var s17 = route16.Resequence("${header.seqNum}", 5, TimeSpan.FromSeconds(3)); s17.Log("[RESEQ] Delivered in order: seq=${header.seqNum}, body=${body}"); s17.EndResequence(); // Enrichment: the reply into the header enriched.data var route18 = From("direct://demo-enrich"); route18.RouteId("demo-enrich"); route18.Description("Enrichment: the reply into the header enriched.data"); route18.Log("[ENRICH] Original body: ${body}"); route18.Enrich("direct://enrichment-source", AggregationStrategies.ByName("intoHeader:enriched.data")); route18.Log("[ENRICH] Enriched: body=${body}, enriched.data=${header.enriched.data}"); var route19 = From("direct://enrichment-source"); route19.RouteId("demo-enrichment-source"); route19.Log("[ENRICH-SRC] Providing enrichment data"); route19.SetBody(Expr("extra-info-for-${header.traceId ?? 'unknown'}")); route19.Log("[ENRICH-SRC] Returning: ${body}"); // Deduplication by messageId var route20 = From("direct://demo-idempotent"); route20.RouteId("demo-idempotent"); route20.Description("Deduplication by messageId"); route20.Log("[IDEMP] messageId=${header.messageId}"); var s21 = route20.IdempotentConsumer("${header.messageId}", "idempotentRepo", true); s21.Log("[IDEMP] First time seeing this message, processing..."); s21.SetHeader("idempotent.processed", "true"); s21.Log("[IDEMP] Done"); s21.EndIdempotentConsumer(); // Rate limit: 5/sec var route22 = From("direct://demo-throttle"); route22.RouteId("demo-throttle"); route22.Description("Rate limit: 5/sec"); route22.Log("[THROTTLE] Incoming request..."); var s23 = route22.Throttle(5); s23.Period(TimeSpan.FromSeconds(1)); s23.Log("[THROTTLE] Passed rate limiter (5/sec)"); s23.Log("[THROTTLE] Done"); s23.EndThrottle(); } } Path: redb-route/tests/redb.Route.Tests.Xml/Examples/Generated/FactoriesRoutes.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.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/Examples/Generated/FactoriesRoutes.cs ---- // /factories.route.xml — do not edit; regenerate instead. /> #nullable enable using System; using System.Collections.Generic; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Aggregation; using redb.Route.ControlBus; using redb.Route.Core; using redb.Route.Transactions; using redb.Route.Xml; using redb.Route.Xslt; namespace redb.Route.Tests.Xml.Examples.Generated; /// A generated route builder — see the header for the source file. public sealed class FactoriesRoutes : RouteBuilder { protected override void Configure() { Context!.AddToRegistry("corp-ldap", XmlBeans.Create(Context!, "redb.Route.Ldap.LdapConnectionFactory, redb.Route.Ldap", [], [("Server", "{{ldap.server}}"), ("Port", "{{ldap.port:636}}"), ("Ssl", "{{ldap.ssl:true}}"), ("BindDn", "{{ldap.service.dn}}"), ("BindPassword", "{{ldap.service.password}}"), ("FollowReferrals", "false")])); Context!.AddToRegistry("corp-smtp", XmlBeans.Create(Context!, "redb.Route.Mail.MailConnectionFactory, redb.Route.Mail", [], [("Host", "{{mail.host}}"), ("Port", "{{mail.port:587}}"), ("Security", "Auto"), ("Username", "{{mail.user}}"), ("Password", "{{mail.password}}")])); Context!.AddToRegistry("main-db", XmlBeans.Create(Context!, "redb.Route.Sql.Connection.SqlConnectionFactory, redb.Route.Sql", [XmlBeans.Create(Context!, "redb.Route.Sql.Connection.SqlConnectionOptions, redb.Route.Sql", [], [("ConnectionString", "{{db.main.connection}}")])], [])); // LDAP authentication issuing a JWT var route0 = From("http:{{api.listen:0.0.0.0:5090}}/auth/login?inOut=true"); route0.RouteId("auth-login"); route0.Description("LDAP authentication issuing a JWT"); route0.To("ldap://{{ldap.base.dn}}?action=bind&connectionFactory=#corp-ldap"); route0.To("bean:#auth-processor?method=IssueToken"); // Login audit into main-db var route1 = From("direct://auth-audit"); route1.RouteId("auth-audit"); route1.Description("Login audit into main-db"); route1.To("sql:INSERT INTO auth_log(login, at) VALUES (:#login, :#at)?dataSource=#main-db¶m.login=${header.login}¶m.at=${dateformat(now(), 'o')}"); // Order notification over SMTP var route2 = From("direct://notify-mail"); route2.RouteId("notify-mail"); route2.Description("Order notification over SMTP"); route2.SetHeader("mail.subject", Expr("Order ${header.orderId}: ${header.status}")); route2.To("smtp://{{mail.from}}?to={{mail.to}}&connectionFactory=#corp-smtp"); } } Path: redb-route/tests/redb.Route.Tests.Xml/Examples/Generated/MainPipelineRoutes.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.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/Examples/Generated/MainPipelineRoutes.cs ---- // /main-pipeline.route.xml — do not edit; regenerate instead. /> #nullable enable using System; using System.Collections.Generic; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Aggregation; using redb.Route.ControlBus; using redb.Route.Core; using redb.Route.Transactions; using redb.Route.Xml; using redb.Route.Xslt; namespace redb.Route.Tests.Xml.Examples.Generated; /// A generated route builder — see the header for the source file. public sealed class MainPipelineRoutes : RouteBuilder { protected override void Configure() { Context!.AddToRegistry("responseBuilder", XmlBeans.Create(Context!, "Acme.Demo.ResponseBuilder, Acme.Demo", [], [])); Context!.AddToRegistry("stamps", XmlBeans.Create(Context!, "Acme.Demo.DemoStamps, Acme.Demo", [], [])); Context!.AddToRegistry("idempotentRepo", XmlBeans.Create(Context!, "redb.Route.Processors.InMemoryIdempotentRepository, redb.Route", [], [])); var handler0 = OnException(typeof(global::System.Exception)); handler0.Description("Global handler of all demo routes"); handler0.Handled(true); handler0.MaximumRedeliveries(2); handler0.RedeliveryDelay(TimeSpan.FromSeconds(1)); handler0.UseExponentialBackOff(true); handler0.BackOffMultiplier(2.0); handler0.Log("[GLOBAL-ERR] route=${routeId}: ${exception.type} - ${exception.message}, body=${body}", LogLevel.Error); handler0.Log("[GLOBAL-ERR] ${exception.message} - handled after retries"); // HTTP entry of the demo pipeline var route1 = From("http:{{demo.http.listen:0.0.0.0:5088}}/api/demo?inOut=true"); route1.RouteId("demo-http-entry"); route1.Description("HTTP entry of the demo pipeline"); route1.ConvertBody(typeof(global::System.String)); var s2 = route1.Throttle(10); s2.Log("[1-HTTP] Received: body=${body}, contentType=${contentType}", LogLevel.Information); s2.To("bean:#stamps?method=NewTraceId"); s2.SetHeader("startedAt", Expr("${dateformat(now(), 'o')}")); s2.Log("[1-HTTP] traceId=${header.traceId}, mode=${header.mode}, priority=${header.priority}"); s2.ValidateJsonSchema(""" { "$schema": "https://json-schema.org/draft/2020-12/schema", "title": "Demo pipeline message", "type": "object", "required": ["orderId"], "properties": { "orderId": { "type": "string" }, "amount": { "type": "number" }, "status": { "type": "string" } } } """, true); s2.Log("[1-HTTP] JSON schema valid"); var s3 = s2.IdempotentConsumer("${header.traceId}", "idempotentRepo"); s3.Log("[1-HTTP] Not a duplicate"); s3.To("direct://pipeline"); s3.EndIdempotentConsumer(); s2.EndThrottle(); // Main processing pipeline var route4 = From("direct://pipeline"); route4.RouteId("demo-pipeline"); route4.Description("Main processing pipeline"); route4.Log("[2-PIPE] Pipeline started, traceId=${header.traceId}"); var s5 = route4.Filter("length(body) > 0"); s5.Log("[2-PIPE] Body is non-empty"); var s6 = s5.Choice(); var b7 = s6.When("header.mode == 'full'"); b7.SetHeader("fastTrack", Expr("header.priority == 'high' ? 'true' : 'false'")); var s8 = b7.TryCatch(); var s9 = s8.Filter("!(header.priority == 'high' || header.priority == 'normal' || header.priority == 'low')"); s9.ThrowException(typeof(global::System.InvalidOperationException), "unknown priority"); s9.EndFilter(); s8.SetHeader("stamp.dsl.priority", Expr("${header.priority}")); var b10 = s8.Catch(typeof(global::System.InvalidOperationException)); var s11 = b10.Log(LogLevel.Warning); s11.ShowRouteId(); s11.Message("priority normalization failed: ${exception.type}"); s11.Header("priority"); s11.EndLog(); b10.SetHeader("stamp.dsl.priority", "unknown"); b10.SetHeader("stamp.dsl.caught", "true"); b10.EndCatch(); s8.EndTryCatch(); b7.SetHeader("stamp.dsl", "full-branch"); var b12 = s6.When("header.mode == 'short'"); b12.SetHeader("fastTrack", "false"); b12.SetHeader("stamp.dsl", "short-branch"); var b13 = s6.Otherwise(); b13.SetHeader("mode", "default"); b13.SetHeader("fastTrack", "false"); b13.SetHeader("stamp.dsl", "default-branch"); s6.EndChoice(); var s14 = s5.Log(LogLevel.Information); s14.ShowRouteId(); s14.Message("pipeline branch decided"); s14.Header("mode"); s14.Header("priority"); s14.Header("fastTrack"); s14.Header("stamp.dsl"); s14.Header("stamp.dsl.priority"); s14.EndLog(); s5.Log("[2-PIPE] mode=${header.mode}, fastTrack=${header.fastTrack}"); var s15 = s5.Traced("broker-roundtrips"); s15.Log("[3-RABBIT] Sending to RabbitMQ RPC..."); s15.To("{{demo.rabbit.producer}}"); s15.Log("[3-RABBIT] stamp.rabbit=${header.stamp.rabbit}"); s15.Log("[4-AMQP] Sending to AMQP/Artemis RPC..."); s15.To("{{demo.amqp.producer}}"); s15.Log("[4-AMQP] stamp.amqp=${header.stamp.amqp}"); s15.Log("[5-GRPC] Sending to gRPC server..."); s15.To("{{demo.grpc.producer}}"); s15.Log("[5-GRPC] stamp.grpc=${header.stamp.grpc}"); s15.Log("[6-WMQ] Sending to IBM MQ RPC..."); s15.To("{{demo.wmq.rpc.producer}}"); s15.Log("[6-WMQ] stamp.wmq=${header.stamp.wmq}"); s15.EndTraced(); s5.ConvertBody(typeof(global::System.String)); s5.Log("[5-GRPC] Body converted to string: ${body}"); s5.Log("[5b-DVM] Calling direct-vm://enricher..."); s5.To("direct-vm://enricher"); s5.Log("[5b-DVM] stamp.vm=${header.stamp.vm}"); s5.SetProperty("originalBody", Expr("${body}")); var s16 = s5.Metered("sql-operations"); s16.BeginTransaction(); s16.Log("[6-TX] Transaction opened"); s16.Log("[6-SQL] INSERT demo_log: traceId=${header.traceId}, mode=${header.mode}"); s16.To("{{demo.sql.insert}}"); s16.Log("[6-SQL] Insert complete"); s16.Log("[6b-SQL] SELECT last 5 rows from demo_log"); s16.To("{{demo.sql.select}}"); var s17 = s16.Split(Expr("body")); s17.Log("[6b-SQL] row: id=${body['id']}, msg=${body['message']}, status=${body['status']}"); s17.EndSplit(); s16.CommitTransaction(); s16.Log("[6-TX] Transaction committed"); s16.EndMetered(); s5.SetBody(Expr("${property.originalBody ?? body}")); s5.Log("[6-RESTORE] Body restored: ${body}"); s5.WireTap("{{demo.kafka.wiretap}}"); s5.Log("[7-TAP] Kafka: demo-audit topic"); s5.WireTap("direct://demo-file-audit"); s5.Log("[7-TAP] File: output/traceId.json"); s5.WireTap("vm://audit-log"); s5.Log("[7-TAP] VM: async audit-log queue"); s5.WireTap("direct://demo-redis-pub"); s5.WireTap("direct://demo-mqtt-pub"); s5.WireTap("direct://demo-wmq-pub"); s5.WireTap("direct://demo-seda-send"); s5.Log("[8-DONE] Pipeline complete for traceId=${header.traceId}"); s5.SetHeader("Content-Type", "application/json"); s5.To("bean:#responseBuilder?method=Build"); s5.EndFilter(); var route18 = From("direct://demo-file-audit"); route18.RouteId("demo-file-audit"); route18.To("bean:#responseBuilder?method=Build"); route18.To("{{demo.file.wiretap}}"); var route19 = From("{{demo.rabbit.consumer}}"); route19.RouteId("demo-rabbit-worker"); route19.Log("[RABBIT-W] Received: ${body}"); route19.SetHeader("stamp.rabbit", Expr("ok:${dateformat(now(), 'HH:mm:ss.fff')}")); route19.Log("[RABBIT-W] Stamped, replying"); var route20 = From("{{demo.amqp.consumer}}"); route20.RouteId("demo-amqp-worker"); route20.Log("[AMQP-W] Received: ${body}"); route20.SetHeader("stamp.amqp", Expr("ok:${dateformat(now(), 'HH:mm:ss.fff')}")); route20.Log("[AMQP-W] Stamped, replying"); var route21 = From("{{demo.grpc.consumer}}"); route21.RouteId("demo-grpc-worker"); route21.Log("[GRPC-W] Received: ${body}"); route21.SetHeader("stamp.grpc", Expr("ok:${dateformat(now(), 'HH:mm:ss.fff')}")); route21.Log("[GRPC-W] Stamped, replying"); var route22 = From("{{demo.wmq.rpc.consumer}}"); route22.RouteId("demo-wmq-worker"); route22.Log("[WMQ-W] Received: ${body}"); route22.SetHeader("stamp.wmq", Expr("ok:${dateformat(now(), 'HH:mm:ss.fff')}")); route22.Log("[WMQ-W] Stamped, replying"); var route23 = From("direct-vm://enricher"); route23.RouteId("demo-vm-enricher"); route23.Log("[DVM-W] Enriching: traceId=${header.traceId}"); route23.SetHeader("stamp.vm", Expr("enriched:${dateformat(now(), 'HH:mm:ss.fff')}")); route23.Log("[DVM-W] Enriched, returning"); var route24 = From("vm://audit-log?concurrentConsumers=2"); route24.RouteId("demo-vm-audit"); route24.Log("[VM-AUDIT] Audit event: traceId=${header.traceId}, mode=${header.mode}"); route24.SetHeader("audit.processed", Expr("${header.traceId}:${header.mode}:${dateformat(now(), 'HH:mm:ss.fff')}")); route24.Log("[VM-AUDIT] Processed: ${header.audit.processed}"); } } Path: redb-route/tests/redb.Route.Tests.Xml/Examples/Generated/ScopeDiagRoutes.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.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/Examples/Generated/ScopeDiagRoutes.cs ---- // /scope-diag.route.xml — do not edit; regenerate instead. /> #nullable enable using System; using System.Collections.Generic; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Aggregation; using redb.Route.ControlBus; using redb.Route.Core; using redb.Route.Transactions; using redb.Route.Xml; using redb.Route.Xslt; namespace redb.Route.Tests.Xml.Examples.Generated; /// A generated route builder — see the header for the source file. public sealed class ScopeDiagRoutes : RouteBuilder { protected override void Configure() { Context!.AddToRegistry("scopeDiag", XmlBeans.Create(Context!, "Acme.Diagnostics.ScopeDiagProbe, Acme.Diagnostics", [], [])); // Diagnostics of the parallel splitter's scopes var route0 = From("timer://scope-diag?period=60000&delay=10000"); route0.RouteId("demo-scope-diag"); route0.Description("Diagnostics of the parallel splitter's scopes"); route0.AutoStart(false); route0.Log("[SCOPE-DIAG] Starting parallel split: 50 items, maxDop=5"); route0.To("bean:#scopeDiag?method=Reset"); var s1 = route0.Split(Expr("body")); s1.ParallelProcessing(); s1.MaxParallelism(5); s1.To("bean:#scopeDiag?method=ProbeItem"); s1.EndSplit(); route0.To("bean:#scopeDiag?method=Summarize"); } } Path: redb-route/tests/redb.Route.Tests.Xml/ExpressionBeanCallGateTests.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.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/ExpressionBeanCallGateTests.cs ---- using AwesomeAssertions; using redb.Route.Xml.Packaging; namespace redb.Route.Tests.Xml; /// A bean the gate holds expression calls against. public class GateRules { public bool IsGold(string? name) => name == "ann"; public string Badge(string name, int points) => $"{name}:{points}"; public Task CheckAsync(string name) => Task.FromResult(name == "ann"); } /// /// The package gate on bean: calls in expressions (stage 2 step e): a call that does not parse is an error at /// its attribute; an undeclared bean is the usual #name warning; with the built assemblies, a call to a declared /// bean is held against its type: the method by name and bindable count, and synchronous. /// public sealed class ExpressionBeanCallGateTests : IDisposable { private readonly string _root = Path.Combine(Path.GetTempPath(), "redb-xml-beanfn-" + Guid.NewGuid().ToString("N")); public ExpressionBeanCallGateTests() => Directory.CreateDirectory(_root); public void Dispose() => Directory.Delete(_root, recursive: true); private static Type? Resolve(string typeName) => Type.GetType(typeName); private static string Rules => $"{typeof(GateRules).FullName}, {typeof(GateRules).Assembly.GetName().Name}"; private string Project(string steps) { var dir = RouteProjectScaffold.Create(_root, "BeanFn" + Guid.NewGuid().ToString("N")[..6]); File.WriteAllText(Path.Combine(dir, "routes", "main.route.xml"), $""" {steps} """); return dir; } private PackageResult Check(string steps) => RoutePackage.Check(Project(steps), "p", "1.0.0", Resolve); [Theory] [InlineData("""""")] [InlineData("""""")] [InlineData("""""")] [InlineData("""""")] public void ACorrectCall_PassesTheGate(string step) { Check(step).Errors.Should().BeEmpty(); } [Fact] public void ACallThatDoesNotParse_IsAnErrorAtTheAttribute() { Check("""""").Errors.Should().Contain(e => e.Message == "expr= a bean: call names its method: bean:rules.Method(...) (position 1 within the expression)." && e.File.Contains("main.route.xml(")); } [Theory] [InlineData("""""", "*'#rules' has no public method 'Missing' taking 1 argument(s)*")] [InlineData("""""", "*'#rules' has no public method 'Badge' taking 1 argument(s)*")] public void AWrongMethodOrArity_OnADeclaredBean_IsAnError(string step, string message) { Check(step).Errors.Should().Contain(e => e.Message.StartsWith("expr= ", StringComparison.Ordinal) && Matches(e.Message, message)); } [Fact] public void AnAsyncMethod_OnADeclaredBean_IsAnError() { Check("""""").Errors .Should().Contain(e => e.Message.Contains("bean:rules.CheckAsync returns Task`1: a bean: call in an expression is synchronous")); } [Fact] public void AnUndeclaredBean_IsTheUsualReferenceWarning() { var result = Check(""""""); result.Errors.Should().BeEmpty("a bean registered by module code is checked when it is called"); result.Warnings.Should().Contain(w => w.Message.Contains("'#pricing' is not declared by any of this package")); } [Theory] [InlineData("""""")] [InlineData("""""")] public void ABareCallWithPlaceholderArguments_IsWarned_WithBothCorrectSpellings(string step) { var result = Check(step); result.Warnings.Should().Contain(w => w.Message.StartsWith("expr= holds a bean: call outside ${...} with ${...} arguments", StringComparison.Ordinal) && w.Message.Contains("bean:svc.Check(header.x)") && w.Message.Contains("${bean:svc.Check(${header.x})}") && w.File.Contains("main.route.xml(")); } [Theory] [InlineData("""""")] [InlineData("""""")] [InlineData("""""")] public void TheCorrectSpellings_AreNotWarned(string step) { Check(step).Warnings.Should().NotContain(w => w.Message.Contains("outside ${...} with ${...} arguments")); } [Theory] [InlineData("""""")] [InlineData("""""")] [InlineData("""""")] public void AnUndeclaredRefName_IsTheUsualReferenceWarning(string step) { var result = Check(step); result.Errors.Should().BeEmpty(); result.Warnings.Should().Contain(w => w.Message.Contains("'#chat.settings' is not declared by any of this package")); } [Theory] [InlineData("""""")] [InlineData("""""")] public void ARefNameOutsidePlaceholders_InATemplate_IsWarned_WithBothCorrectSpellings(string step) { var result = Check(step); result.Warnings.Should().Contain(w => w.Message.StartsWith("expr= holds a ref: name outside ${...} in a text with ${...}", StringComparison.Ordinal) && w.Message.Contains("ref:limit > header.x") && w.Message.Contains("${ref:limit > header.x}") && w.File.Contains("main.route.xml(")); result.Warnings.Should().NotContain(w => w.Message.Contains("holds a bean: call")); } [Theory] [InlineData("""""")] [InlineData("""""")] [InlineData("""""")] public void TheCorrectRefSpellings_AreNotWarned(string step) { Check(step).Warnings.Should().NotContain(w => w.Message.Contains("ref: name outside ${...}")); } // Findings register row 32: the gate compiles each expression as the engine does, so what fails the route at build // fails the package, in the engine's words. [Theory] [InlineData("""""", "unexpected 'garbage' at position 15 within the expression")] [InlineData("""""", "unexpected '|' at position 15 within the expression")] [InlineData("""""", "unexpected '7' at position 10 within the expression")] [InlineData("""""", "${FILE:NAME}: file keys are lowercase: ${file:name}.")] [InlineData("""""", "'nosuch' is not a file key")] [InlineData("""""", "Unexpected token: Eof")] public void AnExpressionTheEngineRefuses_IsAnError(string step, string detail) { var result = Check(step); result.Errors.Should().Contain(e => e.Message.Contains(detail, StringComparison.Ordinal) && e.File.Contains("main.route.xml(")); result.Warnings.Should().NotContain(w => w.Message.Contains("ignored at run time")); } [Theory] [InlineData("""""", "filter", "header.b 3", "'3' at position 10")] [InlineData("""""", "setBody", "exception.Message was", "'was' at position 19")] public void ABareValueThatBecomesText_IsWarned(string step, string _, string expression, string rest) { var result = Check(step); result.Errors.Should().BeEmpty(); result.Warnings.Should().Contain(w => w.Message == $"expr= \"{expression}\" reads as the text itself, not as an expression: {rest} does not continue it; in a condition the text is always true."); } [Theory] [InlineData("""""")] [InlineData("""""")] [InlineData("""""")] [InlineData("""""")] [InlineData("""""")] [InlineData("""""")] [InlineData("""""")] [InlineData("""""")] [InlineData("""""")] [InlineData("""""")] public void ACompleteExpression_OrAComponentSpelling_PassesTheGate(string step) { var result = Check(step); result.Errors.Should().BeEmpty(); result.Warnings.Should().NotContain(w => w.Message.Contains("reads as the text itself")); } [Fact] public void ADeclaredRefName_PassesWithoutAWarning() { var result = Check(""""""); result.Errors.Should().BeEmpty(); result.Warnings.Should().NotContain(w => w.Message.Contains("'#rules'")); } [Fact] public void ARefWithAParenthesis_IsAnErrorAtTheAttribute() { Check("""""").Errors.Should().Contain(e => e.Message.StartsWith("expr= ref:rules names a registry object and calls nothing", StringComparison.Ordinal)); } [Fact] public void BeanInsideAQuotedLiteral_IsNotACall() { Check("""""").Errors.Should().BeEmpty(); } private static bool Matches(string text, string pattern) => System.Text.RegularExpressions.Regex.IsMatch(text, "^" + System.Text.RegularExpressions.Regex.Escape(pattern).Replace("\\*", ".*") + "$"); } Path: redb-route/tests/redb.Route.Tests.Xml/HeaderFilterStrategyReferenceGateTests.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.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/HeaderFilterStrategyReferenceGateTests.cs ---- using AwesomeAssertions; using redb.Route.Core; using redb.Route.Xml; using redb.Route.Xml.Packaging; namespace redb.Route.Tests.Xml; /// /// headerFilterStrategy=#name in an endpoint URI, at the package gate: a name no bean declares is the usual /// undeclared-reference warning, and with the built assemblies at hand the named bean is held against /// , as a typed element attribute is. /// public sealed class HeaderFilterStrategyReferenceGateTests : IDisposable { private readonly string _root = Path.Combine(Path.GetTempPath(), "redb-xml-hfs-" + Guid.NewGuid().ToString("N")); public HeaderFilterStrategyReferenceGateTests() => Directory.CreateDirectory(_root); public void Dispose() => Directory.Delete(_root, recursive: true); private static Type? Resolve(string typeName) => Type.GetType(typeName); private static string T() => $"{typeof(TType).FullName}, {typeof(TType).Assembly.GetName().Name}"; private string Project(string beans) { var dir = RouteProjectScaffold.Create(_root, "Hfs" + Guid.NewGuid().ToString("N")[..6]); File.WriteAllText(Path.Combine(dir, "routes", "main.route.xml"), $""" {beans} """); return dir; } [Fact] public void AMissingStrategy_IsTheUndeclaredReferenceWarning() { var result = RoutePackage.Check(Project(""), "p", "1.0.0", Resolve); result.Warnings.Should().Contain(w => w.Message.Contains("'#filter' is not declared")); result.Errors.Should().BeEmpty(); } [Fact] public void AStrategyBean_Passes() { var dir = Project($""""""); RoutePackage.Check(dir, "p", "1.0.0", Resolve).Errors.Should().BeEmpty(); } [Fact] public void ABeanOfTheWrongType_IsAnError_InTheEnginesWords() { var dir = Project($""""""); RoutePackage.Check(dir, "p", "1.0.0", Resolve).Errors.Should().Contain(e => e.File.StartsWith("routes/main.route.xml(5,") && e.Message.Contains($"'filter' is registered as {typeof(DeepBeanTarget).FullName}, which is not an IHeaderFilterStrategy")); } } Path: redb-route/tests/redb.Route.Tests.Xml/MarkedReferenceGateTests.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.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/MarkedReferenceGateTests.cs ---- using AwesomeAssertions; using redb.Route.Core; using redb.Route.Xml; using redb.Route.Xml.Packaging; namespace redb.Route.Tests.Xml; /// /// Row 7 part 2: an option marked [RegistryReference] names a registry object bare as well as with #, in /// the URI form and in the structured form, so a name no <bean> declares is the usual undeclared-reference /// warning. The core's options are known without --bin; a connector's come with its catalog. A value built from /// configuration or an expression is left alone, and a bare value of an unmarked option is still text. /// public sealed class MarkedReferenceGateTests : IDisposable { private readonly string _root = Path.Combine(Path.GetTempPath(), "redb-xml-marked-" + Guid.NewGuid().ToString("N")); public MarkedReferenceGateTests() => Directory.CreateDirectory(_root); public void Dispose() => Directory.Delete(_root, recursive: true); private static readonly IReadOnlyList Catalog = ComponentCatalog.Build([new ProbeRefComponent()]); private static string T() => $"{typeof(TType).FullName}, {typeof(TType).Assembly.GetName().Name}"; private PackageResult Check(string steps, string beans = "", IReadOnlyList? catalog = null) { var dir = RouteProjectScaffold.Create(_root, "Mrk" + Guid.NewGuid().ToString("N")[..6]); File.WriteAllText(Path.Combine(dir, "routes", "main.route.xml"), $""" {beans} {steps} """); return RoutePackage.Check(dir, "p", "1.0.0", catalog: catalog); } private static IEnumerable Undeclared(PackageResult result) => result.Warnings.Select(w => w.Message).Where(m => m.Contains("is not declared by any ", StringComparison.Ordinal)); [Fact] public void ABareNameInACoreMarkedOption_IsAReference_WithoutBin() { Undeclared(Check("""""")) .Should().ContainSingle().Which.Should().StartWith("'#filter' is not declared by any of this package"); } [Fact] public void ABareNameDeclaredByABean_Passes() { Undeclared(Check("""""", $"""""")) .Should().BeEmpty(); } [Fact] public void AHashName_IsReadAsBefore_Once() { Undeclared(Check("""""")).Should().ContainSingle(); } [Theory] [InlineData("""""")] [InlineData("""""")] [InlineData("""""")] public void PlaceholdersAndUnmarkedOptions_AreLeftAlone(string step) { Undeclared(Check(step)).Should().BeEmpty(); } [Fact] public void AConnectorsMarkedOption_IsAReference_WithItsCatalog_InTheUriForm() { Undeclared(Check("""""", catalog: Catalog)) .Should().ContainSingle().Which.Should().StartWith("'#main' is not declared"); } [Fact] public void AConnectorsMarkedOption_IsAReference_WithItsCatalog_InTheStructuredForm() { Undeclared(Check("""""", catalog: Catalog)) .Should().BeEquivalentTo( "'#main' is not declared by any of this package — either module code registers it at startup (fine), or it is a dangling reference.", "'#other' is not declared by any of this package — either module code registers it at startup (fine), or it is a dangling reference."); } [Fact] public void WithoutItsCatalog_AConnectorsBareName_IsNotKnown() { Undeclared(Check("""""")).Should().BeEmpty(); } } Path: redb-route/tests/redb.Route.Tests.Xml/OptionGroupXmlTests.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.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/OptionGroupXmlTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Xml; using redb.Route.Xml.Packaging; using System.Xml.Linq; namespace redb.Route.Tests.Xml; /// A connector with an option group, as mail's searchTerm. public sealed class ProbeGroupComponent : ComponentBase { public override string Scheme => "probegroup"; public override IEndpoint CreateEndpoint(EndpointUri uri) => throw new NotSupportedException("catalog-only test component"); } /// The group of . public sealed class ProbeGroupFilter { [OptionGroupValue] public string? Reference { get; set; } public bool Unseen { get; set; } = true; public string? Subject { get; set; } [Sensitive] public string? Token { get; set; } } /// The options of . public sealed class ProbeGroupEndpointOptions : EndpointOptions { public string? Host { get; set; } [EndpointRole(EndpointRole.Consumer)] [OptionGroup] public ProbeGroupFilter? Filter { get; set; } public override void Validate() { } } /// /// An option group in route XML: written as attributes named group.member (an XML name may hold a dot), listed /// in the catalog member by member with the group's side, and checked by the package gate as the binder checks it. /// public sealed class OptionGroupXmlTests : IDisposable { private readonly string _root = Path.Combine(Path.GetTempPath(), "redb-xml-optiongroup-" + Guid.NewGuid().ToString("N")); public OptionGroupXmlTests() => Directory.CreateDirectory(_root); public void Dispose() => Directory.Delete(_root, recursive: true); private static readonly IReadOnlyList Catalog = ComponentCatalog.Build([new ProbeGroupComponent()]); private static Type? Resolve(string typeName) => typeof(ProbeGroupComponent).Assembly.GetType(typeName); [Fact] public void Catalog_lists_each_member_of_a_group_with_the_groups_side() { var options = Catalog.Single().Options; options.Select(o => o.Name).Should().BeEquivalentTo("Host", "Filter", "Filter.Unseen", "Filter.Subject", "Filter.Token"); options.Single(o => o.Name == "Filter.Unseen").Default.Should().Be("true"); options.Single(o => o.Name == "Filter.Unseen").Type.Should().Be("bool"); options.Single(o => o.Name == "Filter.Subject").Role.Should().Be(EndpointRole.Consumer); options.Single(o => o.Name == "Filter.Token").Sensitive.Should().BeTrue(); options.Single(o => o.Name == "Host").Role.Should().BeNull(); ComponentCatalog.ToJson(Catalog).Should().Contain("\"Filter.Subject\""); } [Fact] public void Gate_takes_a_member_and_refuses_an_unknown_one_in_both_forms() { var dir = RouteProjectScaffold.Create(_root, "Group"); File.WriteAllText(Path.Combine(dir, "routes", "main.route.xml"), """ """); var errors = RoutePackage.Check(dir, "p", "1.0.0", Resolve, catalog: Catalog).Errors.ToList(); errors.Should().Contain(e => e.File.StartsWith("routes/main.route.xml(3,") && e.Message.Contains("'filter.subjct' is not an option of the ProbeGroup endpoint: the group filter takes filter, filter.unseen, filter.subject, filter.token")); errors.Should().Contain(e => e.File.StartsWith("routes/main.route.xml(7,") && e.Message.Contains("'filter.unsen'")); errors.Should().NotContain(e => e.File.StartsWith("routes/main.route.xml(11,"), "every member written there exists"); } [Fact] public void The_schema_declares_a_group_member_as_the_uri_writes_it() { static string Route(string attribute) => $$""" """; XmlRouteSchema.Validate(XDocument.Parse(Route("filter.subject"), LoadOptions.SetLineInfo), ElementRegistry.CreateDefault(), Catalog) .Should().BeEmpty("the schema writes every segment of a group member camelCase"); XmlRouteSchema.Validate(XDocument.Parse(Route("filter.Subject"), LoadOptions.SetLineInfo), ElementRegistry.CreateDefault(), Catalog) .Should().NotBeEmpty("XML attribute names are case-sensitive"); } } Path: redb-route/tests/redb.Route.Tests.Xml/PackageTypeResolverTests.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.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/PackageTypeResolverTests.cs ---- using AwesomeAssertions; using redb.Route.Xml.Packaging; namespace redb.Route.Tests.Xml; /// /// The type lookup of redb-route-xml check|pack --bin: the build output first, then the shared framework, so markup /// naming a framework type the project's bin does not carry (onException exceptions="System.Net.Http.HttpRequestException") /// passes as it runs on the worker. /// public class PackageTypeResolverTests { // A real build output: this test project's own bin. private static readonly Func Resolve = PackageTypeResolver.Create(AppContext.BaseDirectory); [Fact] public void Framework_type_outside_bin_is_found_by_its_full_name() { Resolve("System.Net.Http.HttpRequestException").Should().Be(typeof(System.Net.Http.HttpRequestException)); } [Fact] public void Framework_type_that_moved_is_found_through_the_assembly_its_name_suggests() { Resolve("System.Net.Sockets.SocketException").Should().Be(typeof(System.Net.Sockets.SocketException)); } [Fact] public void Framework_type_with_its_assembly_name_is_found() { Resolve("System.Net.Http.HttpRequestException, System.Net.Http") .Should().Be(typeof(System.Net.Http.HttpRequestException)); } [Fact] public void Type_of_the_build_output_comes_from_the_bin() { var type = Resolve("redb.Route.Tests.Xml.DeepBeanTarget"); type.Should().NotBeNull(); type!.FullName.Should().Be("redb.Route.Tests.Xml.DeepBeanTarget"); type.Assembly.GetName().Name.Should().Be("redb.Route.Tests.Xml"); } [Fact] public void Unknown_type_is_not_found() { Resolve("System.Net.Http.NoSuchException").Should().BeNull(); Resolve("Nowhere.At.All").Should().BeNull(); } } Path: redb-route/tests/redb.Route.Tests.Xml/PackagedResourceTests.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.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/PackagedResourceTests.cs ---- using AwesomeAssertions; using redb.Route.Xml.Packaging; namespace redb.Route.Tests.Xml; /// /// The gate holds a resource reference to what Pack ships, the resources/ tree (findings register row 42). A file /// beside the project (next to the .csproj) used to pass check, since local runs find it, and the worker failed at /// run time because the package never carried it. /// public sealed class PackagedResourceTests : IDisposable { private const string XmlJsonType = "redb.Route.DataFormats.XmlJson.XmlJsonDataFormat, redb.Route.DataFormats.XmlJson"; private const string Xsd = """"""; private readonly string _root = Path.Combine(Path.GetTempPath(), "redb-xml-res-" + Guid.NewGuid().ToString("N")); public PackagedResourceTests() => Directory.CreateDirectory(_root); public void Dispose() => Directory.Delete(_root, recursive: true); private PackageResult Check(string step, string relativePath) { var dir = RouteProjectScaffold.Create(_root, "Res" + Guid.NewGuid().ToString("N")[..6]); var full = Path.Combine(dir, relativePath); Directory.CreateDirectory(Path.GetDirectoryName(full)!); File.WriteAllText(full, Xsd); File.WriteAllText(Path.Combine(dir, "routes", "main.route.xml"), $""" {step} """); return RoutePackage.Check(dir, "p", "1.0.0"); } [Theory] [InlineData("""""", "resources/order.xsd")] [InlineData("""""", "resources/order.xsd")] [InlineData("""""", "resources/schemas/order.xsd")] public void AResourceUnderResources_Passes(string step, string file) { Check(step, file).Errors.Should().NotContain(e => e.Message.Contains("resource '")); } [Fact] public void AResourceBesideTheProject_IsAnError_ThatSaysToMoveIt() { Check("""""", "order.xsd").Errors.Should().Contain(e => e.Message == "resource 'order.xsd' referenced by is at 'order.xsd', outside 'resources/': pack ships only 'resources/', so the worker would not find it. Move it under 'resources/'." && e.File.Contains("main.route.xml(")); } [Fact] public void AMissingResource_IsTheUsualError() { Check("""""", "resources/order.xsd").Errors .Should().Contain(e => e.Message == "resource 'none.xsd' referenced by is not under 'resources/'."); } [Fact] public void AnXmlJsonSchemaBesideTheProject_IsAnError() { Check($"""""", "order.xsd").Errors .Should().Contain(e => e.Message.StartsWith("xmljson schema 'order.xsd' is at 'order.xsd', outside 'resources/': pack ships only 'resources/'", StringComparison.Ordinal)); } [Fact] public void AnXmlJsonSchemaUnderResources_Passes() { Check($"""""", "resources/order.xsd").Errors .Should().NotContain(e => e.Message.Contains("xmljson schema")); } } Path: redb-route/tests/redb.Route.Tests.Xml/PoolAttributesXmlTests.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.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/PoolAttributesXmlTests.cs ---- using System.Xml.Linq; using AwesomeAssertions; using redb.Route.Configuration; using redb.Route.Core; using redb.Route.Xml; namespace redb.Route.Tests.Xml; /// /// The pool attributes of Camel's XML DSL: executorService on <wireTap>, parallelProcessing /// and executorService on <onCompletion>, in the loaded route and in the generated C#. /// public class PoolAttributesXmlTests : IAsyncLifetime { private readonly RouteContext _context = new(); public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() => await _context.DisposeAsync(); private const string Routes = """ """; [Fact] public async Task TheAttributes_LoadAndBuild_WithTheNamedProfileRegistered() { _context.AddThreadPoolProfile("audit", new ThreadPoolProfile { MaxConcurrency = 4 }); _context.AddXmlRoutesFromContent(Routes, ""); var act = () => _context.Start(); await act.Should().NotThrowAsync(); _context.Routes.Select(r => r.RouteId).Should().Contain("pool-xml"); } [Theory] [InlineData("""""")] [InlineData("""""")] public async Task AnUnknownProfile_FailsTheRouteBuild_NamingIt(string step) { _context.AddXmlRoutesFromContent($""" {step} """, ""); var act = () => _context.Start(); await act.Should().ThrowAsync().Where(e => Mentions(e, "no-such-pool")); } [Fact] public void TheGeneratedCode_CarriesTheAttributes() { var code = XmlCodeGenerator.Generate(XDocument.Parse(Routes), "Pools", "Tests.Generated", sourceName: ""); code.Should().Contain("WireTap(\"direct://pool-xml-sink\", executorService: \"audit\")"); code.Should().Contain("ParallelProcessing()"); code.Should().Contain("ExecutorService(\"audit\")"); } 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.Xml/RedbDataSourceReferenceGateTests.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.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/RedbDataSourceReferenceGateTests.cs ---- using AwesomeAssertions; using redb.Route.Sql; using redb.Route.Xml; using redb.Route.Xml.Packaging; namespace redb.Route.Tests.Xml; /// /// dataSource=redb and dataSource=redb:<name> name the sql: data source redb.Route.Core registers at /// start, so the package gate does not report them as references no <bean> declares. Any other undeclared data /// source is still the usual warning. /// public sealed class RedbDataSourceReferenceGateTests : IDisposable { private readonly string _root = Path.Combine(Path.GetTempPath(), "redb-xml-redbds-" + Guid.NewGuid().ToString("N")); public RedbDataSourceReferenceGateTests() => Directory.CreateDirectory(_root); public void Dispose() => Directory.Delete(_root, recursive: true); private static readonly IReadOnlyList Catalog = ComponentCatalog.Build([new SqlComponent()]); private IEnumerable Undeclared(string step) { var dir = RouteProjectScaffold.Create(_root, "Rds" + Guid.NewGuid().ToString("N")[..6]); File.WriteAllText(Path.Combine(dir, "routes", "main.route.xml"), $""" {step} """); return RoutePackage.Check(dir, "p", "1.0.0", catalog: Catalog).Warnings .Select(w => w.Message) .Where(m => m.Contains("is not declared by any ", StringComparison.Ordinal)); } [Theory] [InlineData("""""")] [InlineData("""""")] [InlineData("""""")] [InlineData("""""")] public void TheRedbDataSource_IsNotAnUndeclaredReference(string step) { Undeclared(step).Should().BeEmpty(); } [Fact] public void AnotherUndeclaredDataSource_IsStillReported() { Undeclared("""""") .Should().ContainSingle().Which.Should().StartWith("'#main' is not declared"); } } Path: redb-route/tests/redb.Route.Tests.Xml/RedbXmlContributionsTests.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.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/RedbXmlContributionsTests.cs ---- using System.Xml.Linq; using AwesomeAssertions; using Microsoft.Extensions.DependencyInjection; using NSubstitute; using redb.Core; using redb.Core.Models.Entities; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.RedbCore.Extensions; using redb.Route.RedbCore.Xml; using redb.Route.Xml; namespace redb.Route.Tests.Xml; /// A props type the markup references by CLR name. public sealed class RedbXmlOrderProps { /// Sample payload property. public string? Value { get; set; } /// Sample numeric property (ordering comparisons). public int Rank { get; set; } } /// /// The redb storage elements (the contribution of redb.Route.Core): /// routes with <redbGet>/<redbSave>/<redbDelete>/ /// <beginRedbTransaction> against a substituted , the /// <redb> context block, the schema pass and the generator face. /// public class RedbXmlContributionsTests : IAsyncLifetime { private static readonly XmlRouteLoaderOptions Options = new() { Extensions = [ new RedbGetXmlContribution(), new RedbSaveXmlContribution(), new RedbDeleteXmlContribution(), new RedbQueryXmlContribution(), new RedbContextXmlContribution(), ], }; private readonly RouteContext _context = new(); private readonly IRedbService _redb = Substitute.For(); public RedbXmlContributionsTests() => _context.AddService(typeof(IRedbService), _redb); public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { await _context.DisposeAsync(); GC.SuppressFinalize(this); } private static IExchange Msg(object? body = null, params (string Key, object? Value)[] headers) { var exchange = new Exchange(); exchange.In.Body = body; foreach (var (key, value) in headers) exchange.In.Headers[key] = value; return exchange; } private async Task StartAndProducer(string fromUri) { await _context.Start(); var producer = _context.GetEndpoint(fromUri).CreateProducer(); await producer.Start(); return producer; } // ── routes ─────────────────────────────────────────────────────── [Fact] public async Task RedbGet_WithoutType_IsTheRawJsonLoad() { _redb.LoadJsonAsync(11L, 2).Returns("{\"id\":11}"); _context.AddXmlRoutesFromContent(""" """, options: Options); var producer = await StartAndProducer("direct://redb-json-in"); var exchange = Msg(headers: ("oid", 11L)); await producer.Process(exchange); exchange.In.Body.Should().Be("{\"id\":11}"); } [Fact] public async Task RedbGet_WithType_LoadsTyped_IntoTheTarget() { var stored = new RedbObject(); _redb.LoadAsync(7L, 10).Returns(stored); _context.AddXmlRoutesFromContent(""" """, options: Options); var producer = await StartAndProducer("direct://redb-typed-in"); var exchange = Msg(body: "kept", headers: ("oid", 7L)); await producer.Process(exchange); exchange.In.Body.Should().Be("kept"); exchange.In.Headers["order"].Should().BeSameAs(stored); } [Fact] public async Task RedbSave_And_Delete_RoundTheBodyThroughTheService() { _redb.DeleteAsync(5L).Returns(true); _context.AddXmlRoutesFromContent(""" """, options: Options); var producer = await StartAndProducer("direct://redb-save-in"); var exchange = Msg(body: "{\"properties\":{\"Value\":\"x\"}}", headers: ("gone", 5L)); await producer.Process(exchange); await _redb.Received(1).SaveAsync(Arg.Is( o => o is RedbObject)); await _redb.Received(1).DeleteAsync(5L); exchange.In.Headers["redbDeleted"].Should().Be(true); } [Fact] public void RedbSave_ByUniqueWithoutType_IsALoadTimeError() { var act = () => _context.AddXmlRoutesFromContent(""" """, options: Options); act.Should().Throw() .Which.Errors.Should().ContainSingle(e => e.Contains("byUnique") && e.Contains("type=")); } [Fact] public void BeginRedbTransaction_IsNotAnElement_TheTransactionScopeIsTheOnePrimitive() { // The verb behind it is obsolete (TRANSACTIONS_GUIDE: one primitive, .Transacted()) and a // no-op under an ambient scope. Markup has no warning channel, so the element is gone — // the steps go inside instead. Red before the removal: the element loaded. var act = () => _context.AddXmlRoutesFromContent(""" """, options: Options); act.Should().Throw() .Which.Errors.Should().Contain(e => e.Contains("beginRedbTransaction")); } [Fact] public void RedbGet_AttributeTypo_IsCaughtByTheSchemaPass() { var act = () => _context.AddXmlRoutesFromContent(""" """, options: Options); act.Should().Throw() .Which.Errors.Should().Contain(e => e.Contains("[schema]") && e.Contains("dept")); } [Fact] public async Task RedbQuery_TranslatesTheWhereString_ServerSide() { var query = Substitute.For>(); System.Linq.Expressions.Expression>? captured = null; query.Where(Arg.Do>>(e => captured = e)) .Returns(query); query.Take(Arg.Any()).Returns(query); query.ToListAsync().Returns([new RedbObject()]); _redb.Query().Returns(query); _context.AddXmlRoutesFromContent(""" """, options: Options); var producer = await StartAndProducer("direct://redb-query-in"); var exchange = Msg(headers: ("wanted", "hit")); await producer.Process(exchange); query.Received(1).Take(5); captured.Should().NotBeNull(); var predicate = captured!.Compile(); predicate(new RedbXmlOrderProps { Value = "hit" }).Should().BeTrue(); predicate(new RedbXmlOrderProps { Value = "miss" }).Should().BeFalse(); exchange.In.Body.Should().BeOfType>>(); } [Fact] public void RedbQuery_UntranslatableWhere_IsAPositionedLoadError() { var act = () => _context.AddXmlRoutesFromContent(""" """, options: Options); act.Should().Throw() .Which.Errors.Should().ContainSingle(e => e.Contains("(4,") && e.Contains("Valeu") && e.Contains("Value"), "the refusal carries the element position and the property candidates"); } [Fact] public async Task RedbQuery_ConditionAsText_CdataFreesTheAngleBrackets() { var query = Substitute.For>(); System.Linq.Expressions.Expression>? captured = null; query.Where(Arg.Do>>(e => captured = e)) .Returns(query); query.Take(Arg.Any()).Returns(query); query.ToListAsync().Returns([]); _redb.Query().Returns(query); // The whole point of the text form: a raw `<` lives inside CDATA, no < anywhere. _context.AddXmlRoutesFromContent(""" """, options: Options); var producer = await StartAndProducer("direct://redb-query-text-in"); await producer.Process(Msg(headers: ("max", 10))); captured.Should().NotBeNull(); var predicate = captured!.Compile(); predicate(new RedbXmlOrderProps { Rank = 9, Value = "x" }).Should().BeTrue(); predicate(new RedbXmlOrderProps { Rank = 10, Value = "x" }).Should().BeFalse(); predicate(new RedbXmlOrderProps { Rank = 9 }).Should().BeFalse("Value is null"); } [Fact] public void RedbQuery_BothWhereFormsAtOnce_IsAnError() { var act = () => _context.AddXmlRoutesFromContent(""" Value == 'b' """, options: Options); act.Should().Throw() .Which.Errors.Should().ContainSingle(e => e.Contains("not both")); } // ── the context block ───────────────────────────────────── [Fact] public async Task ContextRedbBlock_SyncsSchemes_AndRegistersTheRepository() { _context.SetServiceProvider(new ServiceCollection().BuildServiceProvider()); var document = XDocument.Parse(""" """, System.Xml.Linq.LoadOptions.SetLineInfo); new XmlContextLoader(_context, Options).Load(document, "context.xml"); await _context.Start(); await _redb.Received(1).SyncSchemeAsync(); _context.GetFromRegistry("orders-idem") .Should().NotBeNull("the repository must be reachable by "); } [Fact] public async Task ContextRedbBlock_Storage_OpensTheRepositoryOnTheNamedInstance() { var instance = Substitute.For(); instance.CanCreateScope.Returns(true); instance.CreateScope().Returns(_ => new RedbScope(Substitute.For(), null)); _context.RegisterRedbService("local", instance); var document = XDocument.Parse(""" """, System.Xml.Linq.LoadOptions.SetLineInfo); new XmlContextLoader(_context, Options).Load(document, "context.xml"); await _context.Start(); instance.Received().CreateScope(); _context.GetFromRegistry("local-idem").Should().NotBeNull(); } [Fact] public void ContextRedbBlock_InRoutePosition_IsAnError() { var act = () => _context.AddXmlRoutesFromContent(""" """, options: Options); act.Should().Throw() .Which.Errors.Should().Contain(e => e.Contains("context-level")); } [Fact] public void UnknownContextSection_ErrorNamesTheContributedBlocks() { var document = XDocument.Parse(""" """, System.Xml.Linq.LoadOptions.SetLineInfo); var act = () => new XmlContextLoader(_context, Options).Load(document, "context.xml"); act.Should().Throw() .Which.Errors.Should().Contain(e => e.Contains("")); } // ── the generator face ─────────────────────────────────────────── [Fact] public void Generator_PrintsTheVerbs_AndTheirUsings() { var document = XDocument.Parse(""" """); var code = XmlCodeGenerator.Generate(document, "RedbGenerated", "Tests.Generated", options: Options); code.Should().Contain("using redb.Route.RedbCore.Extensions;"); code.Should().NotContain("BeginRedbTransaction", "the obsolete verb has no markup any more"); code.Should().Contain("RedbGetJson(\"${header.oid}\", depth: 2)"); code.Should().Contain("byUnique: true"); code.Should().Contain("RedbDelete(\"${header.gone}\", storage: \"archive\")"); code.Should().Contain("RedbQuery(").And.Contain("where: \"Value == 'x'\"") .And.Contain("orderBy: \"Value\"").And.Contain("descending: true").And.Contain("take: 5"); } // ── whereRedb / orderByRedb: the base fields of the stored object ─ [Fact] public async Task RedbQuery_WhereRedb_FiltersOnBaseFields_AndCombinesWithWhere() { var query = Substitute.For>(); System.Linq.Expressions.Expression>? capturedBase = null; System.Linq.Expressions.Expression>? capturedProps = null; query.WhereRedb(Arg.Do>>(e => capturedBase = e)) .Returns(query); query.Where(Arg.Do>>(e => capturedProps = e)) .Returns(query); query.OrderByRedb(Arg.Any>>()) .Returns(query); query.ToListAsync().Returns([]); _redb.Query().Returns(query); _context.AddXmlRoutesFromContent(""" """, options: Options); var producer = await StartAndProducer("direct://redb-query-base-in"); var key = Guid.NewGuid(); await producer.Process(Msg(headers: ("key", key.ToString()))); capturedProps.Should().NotBeNull("where= still filters the props"); capturedBase.Should().NotBeNull(); var predicate = capturedBase!.Compile(); predicate(new RedbObject { ValueGuid = key }).Should().BeTrue(); predicate(new RedbObject { ValueGuid = key, ParentId = 1 }).Should().BeFalse(); query.Received(1).OrderByRedb(Arg.Any>>()); } [Fact] public void RedbQuery_WhereRedbOnAPropsName_IsAPositionedLoadError() { var act = () => _context.AddXmlRoutesFromContent(""" """, options: Options); act.Should().Throw() .Which.Errors.Should().ContainSingle(e => e.Contains("(4,") && e.Contains("'Rank' is neither a base field") && e.Contains("ValueGuid")); } [Fact] public void Generator_PrintsWhereRedbAndOrderByRedb() { var document = XDocument.Parse(""" """); var code = XmlCodeGenerator.Generate(document, "RedbBaseGenerated", "Tests.Generated", options: Options); code.Should().Contain("whereRedb: \"ValueString == header.code\"").And.Contain("orderByRedb: \"DateCreate\""); } [Fact] public void Schema_KnowsWhereRedbAndOrderByRedb() { var document = XDocument.Parse(""" """, LoadOptions.SetLineInfo); XmlRouteSchema.Validate(document, ElementRegistry.CreateDefault(Options.Extensions)).Should().BeEmpty(); } [Fact] public async Task RedbQuery_OutputTypeFirst_LandsOneObject_AndPrints() { var query = Substitute.For>(); var found = new RedbObject(); query.WhereRedb(Arg.Any>>()) .Returns(query); query.FirstOrDefaultAsync().Returns(found); _redb.Query().Returns(query); const string xml = """ """; _context.AddXmlRoutesFromContent(xml, options: Options); var producer = await StartAndProducer("direct://redb-query-first-in"); var exchange = Msg(headers: ("key", Guid.NewGuid().ToString())); await producer.Process(exchange); exchange.Properties["existing"].Should().BeSameAs(found); XmlCodeGenerator.Generate(XDocument.Parse(xml), "FirstGenerated", "Tests.Generated", options: Options) .Should().Contain("outputType: RedbQueryOutput.First"); } [Fact] public void RedbQuery_UnknownOutputType_IsASchemaError() { var act = () => _context.AddXmlRoutesFromContent(""" """, options: Options); act.Should().Throw().Which.Errors.Should().Contain(e => e.Contains("Single")); } } Path: redb-route/tests/redb.Route.Tests.Xml/RepositoryBeanReferenceTests.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.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/RepositoryBeanReferenceTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Components; using redb.Route.Core; using redb.Route.Processors; using redb.Route.Xml; namespace redb.Route.Tests.Xml; /// /// A repository declared as a bean in markup is the one repository="#name" refers to: the name is the registry /// key as is, for idempotent repositories as for every other reference. /// public class RepositoryBeanReferenceTests : 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 A_bean_repository_starts_the_route_and_drops_the_repeat() { var received = new List(); _context.AddXmlRoutesFromContent($""" """); await _context.Start(); var producer = _context.GetEndpoint("direct://dedup-in").CreateProducer(); await producer.Start(); foreach (var _ in new[] { 1, 2 }) { var exchange = new Exchange(new Message("payload")); exchange.In.Headers["id"] = "order-1"; await producer.Process(exchange); } var mock = (MockEndpoint)_context.GetEndpoint("mock://dedup-out"); mock.ReceivedExchanges.Should().HaveCount(1, "the repository the bean declared remembers the first id"); } } Path: redb-route/tests/redb.Route.Tests.Xml/RepositoryReferenceGateTests.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.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/RepositoryReferenceGateTests.cs ---- using AwesomeAssertions; using redb.Route.RedbCore.Xml; using redb.Route.Xml; using redb.Route.Xml.Packaging; namespace redb.Route.Tests.Xml; /// /// Repositories are found by their bare name (1782f31b): <bean name="dedup"> and /// <redb><idempotentRepository name="dedup"> both declare the key /// repository="#dedup" looks up. The package gate counts both as declarations, and with /// the built assemblies at hand holds the named object against the interface the reference needs. /// public sealed class RepositoryReferenceGateTests : IDisposable { private readonly string _root = Path.Combine(Path.GetTempPath(), "redb-xml-repo-" + Guid.NewGuid().ToString("N")); public RepositoryReferenceGateTests() => Directory.CreateDirectory(_root); public void Dispose() => Directory.Delete(_root, recursive: true); private static readonly IReadOnlyList Extensions = [new RedbContextXmlContribution()]; private static Type? Resolve(string typeName) => Type.GetType(typeName); private const string InMemoryIdempotent = "redb.Route.Processors.InMemoryIdempotentRepository, redb.Route"; private string Project(string routes, string? context = null) { var dir = RouteProjectScaffold.Create(_root, "Repo" + Guid.NewGuid().ToString("N")[..6]); File.WriteAllText(Path.Combine(dir, "routes", "main.route.xml"), routes); if (context is not null) File.WriteAllText(Path.Combine(dir, RoutePackage.ContextFile), context); return dir; } private static string Consumer(string repositoryElement) => $""" {repositoryElement} """; [Fact] public void RedbIdempotentRepository_DeclaresItsName_ForTheGate() { var dir = Project( Consumer(""""""), """ """); var result = RoutePackage.Check(dir, "p", "1.0.0", Resolve, Extensions); result.Warnings.Should().NotContain(w => w.Message.Contains("'#dedup' is not declared"), " registers exactly that name"); result.Errors.Should().BeEmpty(); } [Fact] public void ABeanOfTheRightType_Passes() { var dir = Project($""" """); RoutePackage.Check(dir, "p", "1.0.0", Resolve, Extensions).Errors.Should().BeEmpty(); } [Fact] public void ABeanOfTheWrongType_IsAnError_InTheEnginesWords() { var dir = Project($""" """); var errors = RoutePackage.Check(dir, "p", "1.0.0", Resolve, Extensions).Errors.ToList(); errors.Should().Contain(e => e.File.StartsWith("routes/main.route.xml(6,") && e.Message.Contains($"'dedup' is registered as {typeof(DeepBeanTarget).FullName}, which is not an IIdempotentRepository")); errors.Should().Contain(e => e.File.StartsWith("routes/main.route.xml(7,") && e.Message.Contains("'store' is registered as redb.Route.Processors.InMemoryIdempotentRepository, which is not an IClaimCheckRepository")); } [Fact] public void WithoutTheBuiltAssemblies_TheTypeCheckStaysQuiet() { var dir = Project($""" """); RoutePackage.Check(dir, "p", "1.0.0", extensions: Extensions).Errors .Should().NotContain(e => e.Message.Contains("which is not an")); } } Path: redb-route/tests/redb.Route.Tests.Xml/RestXmlValidationTests.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.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/RestXmlValidationTests.cs ---- using System.Net; using System.Text.Json; using System.Xml.Linq; using AwesomeAssertions; using redb.Route.Core; using redb.Route.Http; using redb.Route.Http.Rest; using redb.Route.Xml; namespace redb.Route.Tests.Xml; /// /// Client request validation of <rest> in Route-XML: clientRequestValidation and /// errorHandler on the declaration, clientRequestValidation and <param> /// children on a verb — parsed into the same declarations as the fluent DSL, printed as the same /// C#, refused with a positioned error when malformed. /// public class RestXmlValidationTests { private static readonly XmlRouteLoaderOptions Options = new() { Extensions = [new RestXmlContribution()], }; [Fact] public async Task Params_and_the_option_reach_the_running_route_and_the_openapi_document() { var port = FreePort(); await using var servers = new SharedHttpServerManager(); await using var context = new RouteContext(); context.AddComponent(new HttpComponent { ServerManager = servers }); context.AddXmlRoutesFromContent($""" """, options: Options); await context.Start(); using var client = new HttpClient { BaseAddress = new Uri($"http://127.0.0.1:{port}") }; (await client.GetAsync("/api/items/7?limit=5")).StatusCode.Should().Be(HttpStatusCode.OK); var missing = await client.GetAsync("/api/items/7"); missing.StatusCode.Should().Be(HttpStatusCode.BadRequest); (await missing.Content.ReadAsStringAsync()).Should().Contain("limit"); (await client.GetAsync("/api/items/x?limit=5")).StatusCode.Should().Be(HttpStatusCode.BadRequest); using var wrongAccept = new HttpRequestMessage(System.Net.Http.HttpMethod.Get, "/api/free"); wrongAccept.Headers.TryAddWithoutValidation("Accept", "application/xml"); (await client.SendAsync(wrongAccept)).StatusCode.Should().Be(HttpStatusCode.OK, "the verb switched validation off"); using var doc = JsonDocument.Parse(await client.GetStringAsync("/api/openapi.json")); var parameters = doc.RootElement.GetProperty("paths").GetProperty("/api/items/{id}").GetProperty("get") .GetProperty("parameters").EnumerateArray().ToDictionary(p => p.GetProperty("name").GetString()!); parameters["id"].GetProperty("schema").GetProperty("type").GetString().Should().Be("integer"); parameters["limit"].GetProperty("in").GetString().Should().Be("query"); parameters["limit"].GetProperty("description").GetString().Should().Be("Page size"); } [Fact] public void Params_print_as_the_fluent_calls() { var code = XmlCodeGenerator.Generate(XDocument.Parse(""" """, LoadOptions.SetLineInfo), "RestRoutes", "Demo", options: Options); code.Should().Contain("options.ClientRequestValidation = true;") .And.Contain("options.ErrorHandler = \"#errors\";") .And.Contain(".Get(\"/{id}\").ClientRequestValidation(false).Param(\"id\", RestParamType.Path, dataType: RestParamDataType.Integer)" + ".Param(\"X-Tenant\", RestParamType.Header, required: true, description: \"Tenant\").To(\"direct://x\");") .And.Contain(".Post(\"\").Param(\"dryRun\", dataType: RestParamDataType.Boolean).Route()") .And.Contain("RemoveBody()"); } [Theory] [InlineData("""""", "*dataType='int'*string, integer, number, boolean*")] [InlineData("""""", "*type='cookie'*path, query, header*")] [InlineData("""""", "*code*not a segment*")] [InlineData("""""", "*cannot be optional*")] [InlineData("""""", "*limit*declared twice*")] public async Task A_malformed_param_is_a_positioned_schema_error(string param, string message) { await using var context = new RouteContext(); var act = () => context.AddXmlRoutesFromContent($""" {param} """, options: Options); act.Should().Throw().WithMessage(message); } [Fact] public async Task Inbound_basic_auth_on_rest_protects_its_verbs() { var port = FreePort(); await using var servers = new SharedHttpServerManager(); await using var context = new RouteContext(); context.AddComponent(new HttpComponent { ServerManager = servers }); context.AddXmlRoutesFromContent($""" """, options: Options); await context.Start(); using var client = new HttpClient { BaseAddress = new Uri($"http://127.0.0.1:{port}") }; var refused = await client.GetAsync("/api/items"); refused.StatusCode.Should().Be(HttpStatusCode.Unauthorized); refused.Headers.WwwAuthenticate.ToString().Should().Contain("realm=\"orders\""); using var request = new HttpRequestMessage(System.Net.Http.HttpMethod.Get, "/api/items"); request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue( "Basic", Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes("admin:s3cret"))); (await client.SendAsync(request)).StatusCode.Should().Be(HttpStatusCode.OK); } [Fact] public void Inbound_auth_prints_as_the_fluent_options() { var code = XmlCodeGenerator.Generate(XDocument.Parse(""" """, LoadOptions.SetLineInfo), "RestRoutes", "Demo", options: Options); code.Should().Contain("using redb.Route.Http;").And.Contain("using redb.Route.Http.Rest;") .And.Contain("options.InboundAuth = HttpAuthScheme.Bearer;") .And.Contain("options.TokenValidator = \"#tokens\";") .And.Contain("options.InboundRealm = \"orders\";"); } private static int FreePort() => global::redb.Route.Tests.Shared.TestPorts.Next(); } Path: redb-route/tests/redb.Route.Tests.Xml/RetryAndScopeKnobsTests.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.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/RetryAndScopeKnobsTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Components; using redb.Route.Core; using redb.Route.Xml; namespace redb.Route.Tests.Xml; /// /// The knobs the markup used to leave to C# only: an onException that decides whether it takes /// the failure at all and how loudly it retries, a transaction with its own retry and dead /// letter channel, a threads scope with a bounded queue, a metered scope split by tags. /// Behaviour where the engine can show it, generated C# where the setting only travels. /// public class RetryAndScopeKnobsTests : 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 ?? ""); private static string CodeOf(string xml) => XmlCodeGenerator.Generate(System.Xml.Linq.XDocument.Parse(xml), "Knobs", "Tests.Generated", sourceName: ""); // ── onException: when to take the failure ──────────────────────────────── [Fact] public async Task OnException_When_TakesTheFailureOnlyWhileTheConditionHolds() { Load(""" """); var producer = await StartAndProducer("direct://knob-onwhen-in"); var matching = new Exchange(new Message("x")); matching.In.Headers["rescue"] = "yes"; await producer.Process(matching); matching.Exception.Should().BeNull("the condition holds, so the handler takes the failure"); matching.In.Headers["rescued"].Should().Be("yes"); var other = new Exchange(new Message("x")); other.In.Headers["rescue"] = "no"; var act = () => producer.Process(other); await act.Should().ThrowAsync( "the condition fails, so the handler stands aside and the exception surfaces"); } [Fact] public async Task OnException_Continued_ResumesTheRouteAfterTheFailingStep() { Load(""" """); var producer = await StartAndProducer("direct://knob-continued-in"); var exchange = new Exchange(new Message("x")); await producer.Process(exchange); exchange.Exception.Should().BeNull("continued suppresses the exception"); exchange.ExceptionHandled.Should().BeTrue(); exchange.In.Headers["noted"].Should().Be("yes"); // Camel's continued(true): the route picks up at the step after the one that failed (implemented 2026-09-21). exchange.In.Headers["after"].Should().Be("yes", "continued resumes the route after the failing step"); } /// /// A condition reads a header whose NAME contains dots (the demos namespace their headers, /// serials.decision). Written with ${…} the same line is a template, and a template /// in a condition position is truthy whatever it renders — so the spelling matters. /// [Fact] public async Task ACondition_ReadsADottedHeaderName() { Load(""" """); var producer = await StartAndProducer("direct://knob-dotted-in"); var accepted = new Exchange(new Message("x")); accepted.In.Headers["serials.decision"] = "Accepted"; await producer.Process(accepted); accepted.In.Headers["branch"].Should().Be("accepted"); var rejected = new Exchange(new Message("x")); rejected.In.Headers["serials.decision"] = "Rejected"; await producer.Process(rejected); rejected.In.Headers["branch"].Should().Be("other", "the branch is chosen by the value, not by truthiness"); } // ── onException: the settings that only travel to the engine ───────────── [Fact] public void OnException_LoggingAndRetrySettings_ReachTheGeneratedCode() { var code = CodeOf(""" """); code.Should().Contain("UseOriginalBody()"); code.Should().Contain("LogStackTrace(false)"); code.Should().Contain("LogExhausted(true)"); code.Should().Contain("LogHandled(false)"); code.Should().Contain("LogContinued(true)"); code.Should().Contain("RetryAttemptedLogLevel(LogLevel.Debug)"); code.Should().Contain("RetriesExhaustedLogLevel(LogLevel.Critical)"); code.Should().Contain("RetryWhile(\"header.again == 'yes'\")"); } [Fact] public void OnException_AnUnknownLogLevel_IsAPositionedError() { var act = () => Load(""" """, "bad-level.xml"); act.Should().Throw().WithMessage("*bad-level.xml(4,*Loud*log level*"); } // ── onException: the three moments a bean can step into ────────────────── [Fact] public async Task OnException_CallbackBeans_RunAtTheirMoments() { var log = new List(); _context.AddToRegistry("occurred", new MarkProcessor("occurred", log)); _context.AddToRegistry("retry", new MarkProcessor("retry", log)); _context.AddToRegistry("prepare", new MarkProcessor("prepare", log)); Load(""" """); var producer = await StartAndProducer("direct://knob-callbacks-in"); var exchange = new Exchange(new Message("x")); await producer.Process(exchange); exchange.In.Headers["rescued"].Should().Be("yes"); log.Count(m => m == "retry").Should().Be(2, "one call before each of the two redeliveries"); log.Count(m => m == "occurred").Should().Be(3, "the first failure and the two failed retries"); log.Count(m => m == "prepare").Should().Be(1, "once, before the handler takes over for good"); log.Last().Should().Be("prepare", "preparation is the last thing before the handler"); } [Fact] public void OnException_ACallbackBeanThatIsNotRegistered_IsAPositionedError() { var act = () => Load(""" """, "missing-bean.xml"); act.Should().Throw().WithMessage("*missing-bean.xml(4,*onRedelivery*nowhere*"); } [Fact] public void OnException_CallbackBeans_ReachTheGeneratedCode() { var code = CodeOf(""" """); code.Should().Contain("OnExceptionOccurred(Context!.GetFromRegistry(\"occurred\")!)"); code.Should().Contain("OnRedelivery(Context!.GetFromRegistry(\"retry\")!)"); code.Should().Contain("OnPrepareFailure(Context!.GetFromRegistry(\"prepare\")!)"); } /// A registry bean that only records that it ran. private sealed class MarkProcessor(string mark, List log) : IProcessor { public Task Process(IExchange exchange, CancellationToken ct = default) { log.Add(mark); return Task.CompletedTask; } } // ── transaction: its own retry and dead letter channel ─────────────────── [Fact] public void Transaction_RetryAndDeadLetterChannel_ReachTheGeneratedCode() { var code = CodeOf(""" """); code.Should().Contain("DeadLetterChannel(\"direct://knob-dlq\")"); code.Should().Contain("Retry(4, TimeSpan.FromSeconds(5))"); } [Fact] public void Transaction_RetryAttemptsWithoutADelay_IsRefused() { var act = () => Load(""" """, "half-retry.xml"); act.Should().Throw().WithMessage("*half-retry.xml(4,*retryDelay*"); } // ── threads: a bounded queue in front of the pool ──────────────────────── [Fact] public void Threads_QueueBounds_ReachTheGeneratedCode() { var code = CodeOf(""" """); code.Should().Contain("Threads(4)"); code.Should().Contain("MaxQueueSize(100)"); code.Should().Contain("EnqueueTimeout(TimeSpan.FromSeconds(3))"); } // ── metered: the metric split by tags ──────────────────────────────────── [Fact] public void Metered_Tags_ReachTheGeneratedCode() { var code = CodeOf(""" """); code.Should().Contain("TagFromHeader(\"partner\", \"partnerId\")"); code.Should().Contain("Tag(\"kind\""); } [Fact] public void Metered_ATagWithNoSource_IsRefused() { var act = () => Load(""" """, "bad-tag.xml"); act.Should().Throw().WithMessage("*bad-tag.xml(5,*fromHeader*expr*"); } // ── split: stopOnException=false lets the rest of the batch run ────────── [Fact] public async Task Split_StopOnExceptionFalse_ProcessesTheRestAfterAFailure() { Load(""" """); var producer = await StartAndProducer("direct://knob-split-in"); var mock = (MockEndpoint)_context.GetEndpoint("mock://knob-split-out"); // The second of the three elements throws; the third must still be processed. await producer.Process(new Exchange(new Message("1,2,3"))); mock.ReceivedExchanges.Should().HaveCount(2, "the failing element is skipped and the elements after it still run"); } [Fact] public void Split_StopOnExceptionFalse_ReachesTheGeneratedCode() { var code = CodeOf(""" """); // StopOnException() defaults to true, so the false case has to survive the round trip. code.Should().Contain("StopOnException(false)"); code.Should().Contain("StopOnException()"); } } Path: redb-route/tests/redb.Route.Tests.Xml/RouteBuilderContextTests.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.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/RouteBuilderContextTests.cs ---- using System.Xml.Linq; using AwesomeAssertions; using redb.Route.Core; using redb.Route.Xml; using redb.Route.Xml.Packaging; namespace redb.Route.Tests.Xml; /// A C# route builder a context.xml names: answers on direct://rb-cs with the body it got, marked. public sealed class MarkupNamedRoute : RouteBuilder { protected override void Configure() { From("direct://rb-cs").RouteId("cs-orders") .Process(e => e.In.Body = $"cs:{e.In.Body}"); } } /// Not a candidate: abstract. public abstract class AbstractMarkupRoute : RouteBuilder; /// Not a candidate: a builder that needs a constructor argument. public sealed class ArgumentMarkupRoute(string name) : RouteBuilder { protected override void Configure() => From("direct://" + name).Log("x"); } /// Not a candidate: not public. internal sealed class HiddenMarkupRoute : RouteBuilder { protected override void Configure() => From("direct://hidden").Log("x"); } /// Not a candidate: not a route builder at all. public sealed class NotARouteBuilder; /// /// <routeBuilder type="…"/> in context.xml adds a C# route builder to the context, so one package carries /// routes in markup and in the DSL, side by side in one context. The type follows the rule of AddRoutes(Assembly[]), /// a wrong one is a load error with its position and, with the built assemblies at hand, a packaging error. /// public sealed class RouteBuilderContextTests : IAsyncLifetime, IDisposable { private readonly RouteContext _context = new(); private readonly string _root = Path.Combine(Path.GetTempPath(), "redb-xml-rb-" + Guid.NewGuid().ToString("N")); public RouteBuilderContextTests() => Directory.CreateDirectory(_root); public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() => await _context.DisposeAsync(); public void Dispose() => Directory.Delete(_root, recursive: true); private static string TypeName() => $"{typeof(T).FullName}, {typeof(T).Assembly.GetName().Name}"; private static string Context(string inner) => $""" {inner} """; private void LoadContext(string inner) => new XmlContextLoader(_context).Load(XDocument.Parse(Context(inner), LoadOptions.SetLineInfo), "context.xml"); [Fact] public async Task A_named_builder_runs_its_routes_next_to_the_markup_routes_in_one_context() { LoadContext($""""""); _context.AddXmlRoutesFromContent(""" """); await _context.Start(); await using var producer = new ProducerTemplate(_context); producer.Start(); var fromCode = await producer.RequestBody("direct://rb-cs", "order"); var fromMarkup = await producer.RequestBody("direct://rb-xml", "order"); fromCode.Should().Be("cs:order"); fromMarkup.Should().Be("xml:order"); _context.Routes.Select(r => r.RouteId).Should().BeEquivalentTo(["cs-orders", "xml-orders"]); } [Theory] [InlineData(typeof(AbstractMarkupRoute), "is abstract")] [InlineData(typeof(ArgumentMarkupRoute), "has no public parameterless constructor")] [InlineData(typeof(HiddenMarkupRoute), "is not public")] [InlineData(typeof(NotARouteBuilder), "does not derive from redb.Route.Core.RouteBuilder")] public void A_type_the_rule_refuses_is_a_load_error_with_its_position(Type type, string reason) { var load = () => LoadContext($""""""); load.Should().Throw().WithMessage($"*context.xml(2,**{reason}*"); _context.RouteBuilders.Should().BeEmpty(); } [Fact] public void An_unknown_type_is_a_load_error() { var load = () => LoadContext(""""""); load.Should().Throw().WithMessage("*context.xml(2,*'Nowhere.Route, Nowhere' was not found*"); } [Fact] public void A_missing_type_is_a_load_error() { var load = () => LoadContext(""); load.Should().Throw().WithMessage("*context.xml(2,*type*"); } [Fact] public void A_document_with_an_error_further_down_adds_no_builder() { var load = () => LoadContext($""" """); load.Should().Throw(); _context.RouteBuilders.Should().BeEmpty("a context.xml with errors must not leave routes running"); } [Fact] public void The_same_builder_named_twice_is_a_load_error() { var load = () => LoadContext($""" """); load.Should().Throw().WithMessage("*context.xml(3,*is already added to this context*"); } [Fact] public void A_builder_already_added_in_code_is_a_load_error() { _context.AddRoutes(new MarkupNamedRoute()); var load = () => LoadContext($""""""); load.Should().Throw().WithMessage("*is already added to this context*"); } [Fact] public void Inside_a_route_it_is_refused() { var load = () => _context.AddXmlRoutesFromContent($""" """); load.Should().Throw().WithMessage("*routeBuilder*"); } // ── the packaging check ───────────────────────────────────────────────── private string Project(string context) { var dir = RouteProjectScaffold.Create(_root, "Rb" + Guid.NewGuid().ToString("N")[..6]); File.WriteAllText(Path.Combine(dir, RoutePackage.ContextFile), context); return dir; } private static Type? Resolve(string typeName) => Type.GetType(typeName); [Fact] public void The_check_passes_a_builder_the_loader_accepts() { var dir = Project(Context($"""""")); var result = RoutePackage.Check(dir, "p", "1.0.0", Resolve); result.Errors.Should().BeEmpty(); } [Fact] public void The_check_fails_on_a_type_the_built_assemblies_lack() { var dir = Project(Context("""""")); var result = RoutePackage.Check(dir, "p", "1.0.0", Resolve); result.Errors.Should().ContainSingle() .Which.Message.Should().Contain("'Nowhere.Route, Nowhere' was not found in the built assemblies"); } [Theory] [InlineData(typeof(NotARouteBuilder), "does not derive from redb.Route.Core.RouteBuilder")] [InlineData(typeof(ArgumentMarkupRoute), "has no public parameterless constructor")] [InlineData(typeof(AbstractMarkupRoute), "is abstract")] public void The_check_fails_on_a_type_the_loader_refuses(Type type, string reason) { var dir = Project(Context($"""""")); var result = RoutePackage.Check(dir, "p", "1.0.0", Resolve); result.Errors.Should().ContainSingle().Which.Message.Should().Contain(reason); } [Fact] public void The_check_fails_on_a_builder_without_a_type_even_without_the_built_assemblies() { var dir = Project(Context("")); var result = RoutePackage.Check(dir, "p", "1.0.0"); result.Errors.Should().ContainSingle().Which.Message.Should().Contain(" needs type="); } } Path: redb-route/tests/redb.Route.Tests.Xml/RouteConfigurationXmlTests.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.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/RouteConfigurationXmlTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.TestKit; using redb.Route.Xml; namespace redb.Route.Tests.Xml; /// /// <routeConfiguration>, the markup form of a route configuration (Apache Camel's Route Configuration): /// <onException> blocks shared by the routes of the context — in a routes file, where they reach the routes /// of the other files too, and in context.xml. A route names configurations with routeConfigurationId; /// the configuration without an id is the default, for the routes that name none. /// public class RouteConfigurationXmlTests : IAsyncLifetime { private static readonly TimeSpan Wait = TimeSpan.FromSeconds(2); private readonly RouteContext _context = new(); public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { await _context.DisposeAsync(); GC.SuppressFinalize(this); } [Fact] public async Task AFileOfHandlers_ReachesTheRoutesOfAnotherFile() { // The layout a container-level no longer serves: one file of handlers for all the others. _context.AddXmlRoutesFromContent(""" """, "handlers.route.xml"); _context.AddXmlRoutesFromContent(""" """, "orders.route.xml"); await _context.Start(); await _context.SendBody("direct://xml-cfg-orders", "order-1"); await _context.Mock("mock://xml-cfg-rescued").ExpectBodies("order-1").AssertIsSatisfiedAsync(Wait); } [Fact] public async Task InContextXml_IsTheContextsSharedErrorHandling() { _context.AddXmlContextFromContent(""" """, "context.xml"); _context.AddRoutes(r => r.From("direct://xml-cfg-code").Process(_ => throw new InvalidOperationException("boom"))); await _context.Start(); await _context.SendBody("direct://xml-cfg-code", "from-code"); await _context.Mock("mock://xml-cfg-context").ExpectBodies("from-code").AssertIsSatisfiedAsync(Wait); } [Fact] public async Task AnId_IsForTheRoutesThatNameIt() { _context.AddXmlRoutesFromContent(""" """, ""); await _context.Start(); await _context.SendBody("direct://xml-cfg-named", "named"); var plain = async () => await _context.SendBody("direct://xml-cfg-plain", "plain"); await plain.Should().ThrowAsync("the route named no configuration"); await _context.Mock("mock://xml-cfg-audit").ExpectBodies("named").AssertIsSatisfiedAsync(Wait); } [Fact] public void TheDefinitionsItBuilds() { _context.AddXmlRoutesFromContent(""" """, ""); var builder = _context.RouteBuilders.Single(); var configuration = builder.RouteConfigurations.Should().ContainSingle().Subject; configuration.Id.Should().Be("retry"); configuration.ExceptionDefinitions.Select(d => d.ExceptionTypes.Single()) .Should().Equal(typeof(IOException), typeof(TimeoutException)); builder.ExceptionDefinitions.Should().BeEmpty("a configuration's handlers are not the builder's own"); builder.Definitions.Single().GetRouteConfigurationId().Should().Be("retry,audit*"); } [Theory] [InlineData("""""")] [InlineData("""""")] [InlineData("""""")] public void WhatIsNotAConfiguration_IsAPositionedError(string element) { var act = () => _context.AddXmlRoutesFromContent( $"""{element}""", ""); act.Should().Throw(); _context.RouteBuilders.Should().BeEmpty("a document with errors adds nothing"); } [Fact] public void InARoute_IsAPositionedError() { var act = () => _context.AddXmlRoutesFromContent(""" """, ""); act.Should().Throw(); } [Fact] public void AContextXmlWithAnError_AddsNoConfiguration() { var act = () => _context.AddXmlContextFromContent(""" """, "context.xml"); act.Should().Throw(); _context.RouteBuilders.Should().BeEmpty(); } [Fact] public void TheGeneratedCode_DeclaresTheConfigurationOnce_AndNamesItOnTheRoute() { var code = XmlCodeGenerator.Generate(System.Xml.Linq.XDocument.Parse(""" """), "Configured", "Tests.Generated", sourceName: ""); code.Should().Contain("= RouteConfiguration(\"retry\");"); code.Should().Contain("= RouteConfiguration();"); System.Text.RegularExpressions.Regex.Matches(code, @"RouteConfiguration\(""retry""\)").Should().HaveCount(1, "an id is unique: both handlers hang on the one configuration"); System.Text.RegularExpressions.Regex.Matches(code, @"configuration\d+\.OnException\(").Should().HaveCount(3); code.Should().Contain(".RouteConfigurationId(\"retry\");"); } [Fact] public void TheSchema_KnowsTheElementAndTheAttribute() { var schema = XmlRouteSchema.Generate(ElementRegistry.CreateDefault()).ToString(); schema.Should().Contain("name=\"routeConfiguration\""); schema.Should().Contain("ref=\"r:routeConfiguration\""); schema.Should().Contain("name=\"routeConfigurationId\""); // And it validates: a document with the element and the attribute has no schema error. XmlRouteSchema.Validate(System.Xml.Linq.XDocument.Parse(""" """, System.Xml.Linq.LoadOptions.SetLineInfo), XmlRouteSchema.CoreSet).Should().BeEmpty(); } } Path: redb-route/tests/redb.Route.Tests.Xml/RouteDescriberTests.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.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/RouteDescriberTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Diagnostics; using redb.Route.Xml; namespace redb.Route.Tests.Xml; /// /// — deterministic, human-readable text over a /// definition tree, the one visitor shared by equivalence tests (here), the code generator /// round-trip and Mermaid. The key promise: a route loaded from XML and the same route written /// in post-V4 C# describe IDENTICALLY. /// public class RouteDescriberTests : IAsyncLifetime { private readonly RouteContext _context = new(); public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { await _context.DisposeAsync(); GC.SuppressFinalize(this); } private const string Xml = """ """; private static IReadOnlyList Definitions(RouteContext context) { var definitions = new List(); foreach (var builder in context.RouteBuilders) { if (!builder.IsBuilt) builder.InternalBuild(context); definitions.AddRange(builder.Definitions); } return definitions; } [Fact] public void TwoLoadsOfTheSameXml_DescribeByteEqual() { _context.AddXmlRoutesFromContent(Xml); using var second = new RouteContext(); second.AddXmlRoutesFromContent(Xml); var first = RouteDescriber.Describe(Definitions(_context)); var again = RouteDescriber.Describe(Definitions(second)); again.Should().Be(first); first.Should().NotBeEmpty(); } [Fact] public void XmlRoute_AndItsPostV4CSharpTwin_DescribeIdentically() { _context.AddXmlRoutesFromContent(Xml); using var codeContext = new RouteContext(); codeContext.AddRoutes(r => r.From("direct://descr-in") .RouteId("descr-route") .SetHeader("priority", RouteBuilder.Expr("${header.amount} > 1000 ? 'high' : 'normal'")) .Filter("header.amount > 0") .Choice() .When("header.type == 'order'") .To("direct://descr-orders") .Otherwise() .To("direct://descr-dlq") .EndChoice() .EndFilter()); var fromXml = RouteDescriber.Describe(Definitions(_context)); var fromCode = RouteDescriber.Describe(Definitions(codeContext)); fromXml.Should().Be(fromCode); } [Fact] public void TheDescription_IsReadable_AndCarriesTheAuthoredText() { _context.AddXmlRoutesFromContent(Xml); var text = RouteDescriber.Describe(Definitions(_context)); text.Should().Contain("header.amount > 0", "the filter shows the condition as written"); text.Should().Contain("direct://descr-orders").And.Contain("direct://descr-dlq"); text.Should().Contain("${header.amount} > 1000 ? 'high' : 'normal'"); text.Should().NotContainAny("k__BackingField", "System.Func", "HashCode"); } [Fact] public void DifferentExpressions_DescribeDifferently() { // Guards the failure mode where the describer skips so much that everything looks equal. _context.AddXmlRoutesFromContent(""" """); using var other = new RouteContext(); other.AddXmlRoutesFromContent(""" """); RouteDescriber.Describe(Definitions(_context)) .Should().NotBe(RouteDescriber.Describe(Definitions(other))); } [Fact] public void BranchChildren_CarryIdAndDescriptionToo() { // Id/description are common to ALL elements — including the branch children // (, , ) that are parsed inside their parent's contribution. _context.AddXmlRoutesFromContent(""" """); var text = RouteDescriber.Describe(Definitions(_context)); text.Should().Contain("stepId=w-list").And.Contain("stepDescription=The list branch"); text.Should().Contain("stepId=w-rest").And.Contain("stepDescription=Everything else"); } [Fact] public void StepIdentity_FromXmlAttributes_IsPartOfTheDescription() { _context.AddXmlRoutesFromContent(""" """); var text = RouteDescriber.Describe(Definitions(_context)); text.Should().Contain("stepId=wipe").And.Contain("stepDescription=Clear the payload"); } } Path: redb-route/tests/redb.Route.Tests.Xml/RoutePackagingTests.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.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/RoutePackagingTests.cs ---- using System.IO.Compression; using System.Text.Json; using AwesomeAssertions; using redb.Route.Xml; using redb.Route.Xml.Packaging; namespace redb.Route.Tests.Xml; /// The bean target of the deep packaging checks. public class DeepBeanTarget { public string? Endpoint { get; set; } public string Handle(Abstractions.IExchange exchange) => "ok"; } /// /// The Tsak-independent half: a scaffolded project builds into the package /// layout (manifest + L4 identity config + artifacts + resources) with the packaging checks as the /// gate — a broken reference is a build error, never a deployment surprise — and every /// {{key}} without a default lands in the required-keys manifest. /// public class RoutePackagingTests : IDisposable { private readonly string _root = Path.Combine(Path.GetTempPath(), "redb-xml-pkg-" + Guid.NewGuid().ToString("N")); public RoutePackagingTests() => Directory.CreateDirectory(_root); public void Dispose() => Directory.Delete(_root, recursive: true); private string NewProject(string name = "Orders", string? context = null) => RouteProjectScaffold.Create(_root, name, context); // ── the scaffold ───────────────────────────────────────────────────────── [Fact] public void Scaffold_CreatesTheWholeConvention() { var dir = NewProject("Orders", "orders"); File.Exists(Path.Combine(dir, "Orders.csproj")).Should().BeTrue(); File.Exists(Path.Combine(dir, "context.xml")).Should().BeTrue(); File.Exists(Path.Combine(dir, "routes", "main.route.xml")).Should().BeTrue(); File.Exists(Path.Combine(dir, "config", "Orders.config.json")).Should().BeTrue(); File.Exists(Path.Combine(dir, "config", "context.sample.json")).Should().BeTrue(); File.Exists(Path.Combine(dir, "schema", "redb-route-1.0.xsd")).Should().BeTrue(); File.Exists(Path.Combine(dir, ".vscode", "settings.json")).Should().BeTrue(); // A route project is a library: without this NuGet assemblies never reach bin/, and the // build-time pack gate (--bin TargetDir) sees neither connectors nor markup contributions. File.ReadAllText(Path.Combine(dir, "Orders.csproj")) .Should().Contain("true", "the build-time gate reads the runtime from TargetDir"); // The L4 config is module identity ONLY — no settings, no secrets. using var l4 = JsonDocument.Parse(File.ReadAllText(Path.Combine(dir, "config", "Orders.config.json"))); l4.RootElement.EnumerateObject().Select(p => p.Name) .Should().BeEquivalentTo("//", "ContextName", "AutoStart"); l4.RootElement.GetProperty("ContextName").GetString().Should().Be("orders"); } [Fact] public void Scaffold_RefusesANonEmptyDirectory() { var dir = NewProject("Busy"); var act = () => RouteProjectScaffold.Create(_root, "Busy"); act.Should().Throw().WithMessage("*not empty*"); } // ── check and build ────────────────────────────────────────────────────── [Fact] public void FreshScaffold_PassesTheChecks_AndBuildsThePackage() { // The package name `pack` infers is the project name; the context comes from config/Orders.config.json. var dir = NewProject("Orders", "sales"); var outDir = Path.Combine(_root, "out"); var result = RoutePackage.Build(dir, "Orders", "1.2.3", outDir); result.Errors.Should().BeEmpty(); result.Warnings.Should().BeEmpty(); result.Manifest.Artifacts.Should().Equal("routes/main.route.xml"); result.Manifest.Context.Should().Be("sales"); var stage = Path.Combine(outDir, "Orders-1.2.3"); File.Exists(Path.Combine(stage, "manifest.json")).Should().BeTrue(); File.Exists(Path.Combine(stage, "Orders.config.json")).Should().BeTrue(); File.Exists(Path.Combine(stage, "routes", "main.route.xml")).Should().BeTrue(); File.Exists(Path.Combine(stage, "context.xml")).Should().BeTrue(); using var zip = ZipFile.OpenRead(Path.Combine(outDir, "Orders-1.2.3.tpkg")); zip.Entries.Select(e => e.FullName.Replace('\\', '/')) .Should().Contain(["manifest.json", "Orders.config.json", "routes/main.route.xml"]); } /// /// The config file name is matched with its letter case on every system. File.Exists ignored the case on Windows /// and kept it on Linux, so the same project and the same --name gave two different packages. /// [Fact] public void NameDifferingOnlyInCase_IsAWarning_AndPacksTheDefaultConfig_OnEverySystem() { var dir = NewProject("Orders", "sales"); var outDir = Path.Combine(_root, "out"); var result = RoutePackage.Build(dir, "orders", "1.2.3", outDir); result.Errors.Should().BeEmpty(); result.Warnings.Should().ContainSingle(w => w.File == "config/orders.config.json") .Which.Message.Should().Contain("config/Orders.config.json"); result.Manifest.Context.Should().BeNull("config/Orders.config.json is not the config of the package 'orders'"); using var l4 = JsonDocument.Parse(File.ReadAllText(Path.Combine(outDir, "orders-1.2.3", "orders.config.json"))); l4.RootElement.GetProperty("ContextName").GetString().Should().Be("orders"); } [Fact] public void EntryGivenAsABuildPath_IsNamedInTheManifestAsTheZipEntry() { var dir = NewProject("Orders", "orders"); var bin = Path.Combine(dir, "bin", "Release", "net10.0"); Directory.CreateDirectory(bin); File.WriteAllBytes(Path.Combine(bin, "Orders.dll"), [0x4D, 0x5A]); var outDir = Path.Combine(_root, "out"); var result = RoutePackage.Build(dir, "orders", "1.0.0", outDir, entryPoints: ["bin/Release/net10.0/Orders.dll"]); result.Errors.Should().BeEmpty(); result.Manifest.EntryPoints.Should().Equal("Orders.dll"); using var zip = ZipFile.OpenRead(Path.Combine(outDir, "orders-1.0.0.tpkg")); zip.GetEntry("Orders.dll").Should().NotBeNull("the loader looks the entry point up by the manifest's name"); using var manifest = JsonDocument.Parse(zip.GetEntry("manifest.json")!.Open()); manifest.RootElement.GetProperty("EntryPoints").EnumerateArray().Select(e => e.GetString()) .Should().Equal("Orders.dll"); } /// /// --depends writes the manifest Dependencies: the worker opens the named packages (a carrier of shared companion /// DLLs) before this one. The tool had no way to write them, so a pure XML package could not declare its carrier. /// [Fact] public void Dependencies_AreWrittenToTheManifest_AsGiven() { var dir = NewProject("Orders", "orders"); var outDir = Path.Combine(_root, "out"); var result = RoutePackage.Build(dir, "orders", "1.0.0", outDir, dependencies: ["shared-beans", "Billing"]); result.Errors.Should().BeEmpty(); result.Manifest.Dependencies.Should().Equal("shared-beans", "Billing"); using var zip = ZipFile.OpenRead(Path.Combine(outDir, "orders-1.0.0.tpkg")); using var manifest = JsonDocument.Parse(zip.GetEntry("manifest.json")!.Open()); manifest.RootElement.GetProperty("Dependencies").EnumerateArray().Select(e => e.GetString()) .Should().Equal("shared-beans", "Billing"); } [Fact] public void Without_dependencies_the_manifest_lists_none() { var dir = NewProject("Orders", "orders"); var result = RoutePackage.Check(dir, "orders", "1.0.0"); result.Errors.Should().BeEmpty(); result.Manifest.Dependencies.Should().BeEmpty(); } [Theory] [InlineData("", "not a package name")] [InlineData(" billing", "not a package name")] [InlineData("--bin", "is an option")] [InlineData("carrier.tpkg", "is a file")] [InlineData("pkg/carrier", "is a file")] [InlineData("Shared.Beans.dll", "is a file")] [InlineData("ORDERS", "cannot depend on itself")] public void A_dependency_of_the_wrong_shape_is_an_error(string dependency, string message) { var dir = NewProject("Orders", "orders"); var result = RoutePackage.Check(dir, "orders", "1.0.0", dependencies: [dependency]); result.Errors.Should().ContainSingle(e => e.File == "--depends").Which.Message.Should().Contain(message); } [Fact] public void A_dependency_listed_twice_is_an_error_and_refuses_the_build() { var dir = NewProject("Orders", "orders"); var outDir = Path.Combine(_root, "out"); var result = RoutePackage.Build(dir, "orders", "1.0.0", outDir, dependencies: ["billing", "Billing"]); result.Errors.Should().ContainSingle(e => e.File == "--depends").Which.Message.Should().Contain("more than once"); File.Exists(Path.Combine(outDir, "orders-1.0.0.tpkg")).Should().BeFalse(); } [Fact] public void ConfigOfAnotherName_IsAWarning_NamingBothFiles() { var dir = NewProject("Orders", "orders"); var result = RoutePackage.Check(dir, "billing", "1.0.0"); result.Errors.Should().BeEmpty(); result.Warnings.Should().ContainSingle(w => w.File == "config/billing.config.json") .Which.Message.Should().Contain("config/billing.config.json").And.Contain("config/Orders.config.json"); } [Fact] public void ConfigOfThePackageName_OrNoConfigAtAll_IsNotWarned() { var dir = NewProject("Orders", "orders"); RoutePackage.Check(dir, "Orders", "1.0.0").Warnings .Should().NotContain(w => w.Message.Contains("reads its config from")); File.Delete(Path.Combine(dir, "config", "Orders.config.json")); RoutePackage.Check(dir, "billing", "1.0.0").Warnings .Should().NotContain(w => w.Message.Contains("reads its config from"), "without any *.config.json the default config is the intended one"); } [Fact] public void RequiredConfigKeys_AreEveryPlaceholderWithoutADefault() { var dir = NewProject("Keys", "keys"); File.WriteAllText(Path.Combine(dir, "routes", "keys.route.xml"), """ """); var result = RoutePackage.Check(dir, "keys", "1.0.0"); result.Errors.Should().BeEmpty(); result.Manifest.RequiredConfigKeys.Should().Equal("mail.from", "mail.to", "tenant.name"); result.Warnings.Should().Contain(w => w.Message.Contains("#corp-smtp"), "an undeclared #reference is named: module code may register it, or it is dangling"); } [Theory] [InlineData("${header.kind} =~ 'order'", true)] [InlineData("${header.n} range '1..10'", true)] [InlineData("${header.n} not range '1..10'", true)] [InlineData("${header.kind =~ 'order'}", false)] [InlineData("header.n range '1..10'", false)] public void TheCamelComparisons_OutsideAPlaceholder_AreWarnedToo(string condition, bool warned) { var dir = NewProject("CondCamel", "condcamel"); File.WriteAllText(Path.Combine(dir, "routes", "cond.route.xml"), $""" """); var result = RoutePackage.Check(dir, "condcamel", "1.0.0"); result.Errors.Should().BeEmpty(); result.Warnings.Any(w => w.Message.Contains("compares OUTSIDE")).Should().Be(warned); } [Fact] public void AConditionThatComparesOutsideAPlaceholder_IsAWarning() { // ${header.kind} == 'order' renders to the text «refund == 'order'», which is non-empty and // therefore true whatever the header holds: the branch always wins, silently. The gate names // the line and leaves the decision to the author — a warning, not an error. var dir = NewProject("Cond", "cond"); File.WriteAllText(Path.Combine(dir, "routes", "cond.route.xml"), """ """); var result = RoutePackage.Check(dir, "cond", "1.0.0"); result.Errors.Should().BeEmpty("a template in a condition still loads and runs"); result.Warnings.Should().ContainSingle(w => w.Message.Contains("compares OUTSIDE")) .Which.File.Should().Contain("cond.route.xml(5,", "the warning carries the position of the attribute"); } [Fact] public void ConditionsThatAreSpelledProperly_AreNotWarnedAbout() { // Three shapes that read correctly and must stay silent: the comparison without braces, a // lone placeholder (it renders to true/false and is read as a boolean word), and a // comparison entirely inside the braces (evaluated, never rendered). Plus a VALUE position, // where a template with an operator is ordinary text. var dir = NewProject("CondOk", "condok"); File.WriteAllText(Path.Combine(dir, "routes", "condok.route.xml"), """ """); var result = RoutePackage.Check(dir, "condok", "1.0.0"); result.Errors.Should().BeEmpty(); result.Warnings.Should().NotContain(w => w.Message.Contains("compares OUTSIDE")); } // ── package resources named by package elements ────────────────────────── /// The two package elements that read a file from the package, as the worker's discovery sees them. private static readonly IReadOnlyList FileReadingContributions = [ new redb.Route.Templates.PayloadXmlContribution(), new redb.Route.JsonTransform.JsonTransformXmlContribution(), ]; [Fact] public void ATemplateMissingFromResources_IsAnError() { // The worker reads from the package's resources/ (a156cc49); a template // left out of it fails the context at start. The gate says so at build time instead, with // the position of the attribute, as it does for the format's own file=. var dir = NewProject("Tpl", "tpl"); File.WriteAllText(Path.Combine(dir, "routes", "tpl.route.xml"), """ """); var result = RoutePackage.Check(dir, "tpl", "1.0.0", extensions: FileReadingContributions); result.Errors.Should().Contain(e => e.Message.Contains("'templates/order.json.sbn'") && e.Message.Contains(" e.Message.Contains("'maps/order.jsonata'") && e.Message.Contains(" """); var result = RoutePackage.Check(dir, "tplok", "1.0.0", extensions: FileReadingContributions); result.Errors.Should().BeEmpty(); } [Fact] public void AnAssemblyLocatorOrAPlaceholder_IsNotCheckedAsAPackageFile() { // assembly: ships the text inside an assembly, and {{…}} is only known once configuration // resolves it: neither can be looked for under resources/ at build time. var dir = NewProject("TplSkip", "tplskip"); File.WriteAllText(Path.Combine(dir, "routes", "tplskip.route.xml"), """ """); var result = RoutePackage.Check(dir, "tplskip", "1.0.0", extensions: FileReadingContributions); result.Errors.Should().NotContain(e => e.Message.Contains("is not under")); } [Fact] public void RegistryReferences_AreValuesStartingWithHash_NotSqlParameters() { // The sql connector writes parameters Camel-style, :#name (wave 17.6). A '#' inside the // SQL text is a parameter, not a registry reference — only a value that STARTS with '#' // (an option value, the path after the scheme, a whole attribute) references the registry. var dir = NewProject("SqlParams", "sqlparams"); File.WriteAllText(Path.Combine(dir, "routes", "sqlparams.route.xml"), """ """); var result = RoutePackage.Check(dir, "sqlparams", "1.0.0"); result.Errors.Should().BeEmpty(); result.Warnings.Should().NotContain(w => w.Message.Contains("'#login'") || w.Message.Contains("'#at'"), ":#login and :#at are sql parameters, never registry references"); result.Warnings.Should().Contain(w => w.Message.Contains("'#main-db'"), "an option value starting with '#' is still a reference"); result.Warnings.Should().Contain(w => w.Message.Contains("'#auditor'"), "the path right after bean: is still a reference"); } // ── resources outside the gate: the tool reads them where the package keeps them ── [Fact] public void ResourceRoot_OfAPackageRoute_IsTheResourcesDirectory() { // A route under /routes/ references its schemas by file name, and the package // keeps them in /resources/ - where the gate and the Tsak loader look. The // generator looked next to the route file instead (SerialNumbers.Xml, 2026-09-18). var dir = NewProject("Res"); File.WriteAllText(Path.Combine(dir, "resources", "order.xsd"), """ """); var route = Path.Combine(dir, "routes", "res.route.xml"); File.WriteAllText(route, """ """); RoutePackage.ResourceRootFor(route).Should().Be(Path.Combine(dir, "resources")); var code = XmlCodeGenerator.Generate(System.Xml.Linq.XDocument.Load(route), "ResRoutes", "Tests.Generated", sourceName: route); // Row 37: the generated code keeps the file, so its imports resolve at runtime; the generator still finds it // in resources/ (a missing one fails the generation, see Generator_NamesEveryPlaceItLooked_WhenAResourceIsMissing). code.Should().Contain("""ValidateXsdFile("order.xsd")"""); } [Fact] public void ResourceRoot_OfALooseRouteFile_IsItsOwnDirectory() { var loose = Path.Combine(_root, "loose"); Directory.CreateDirectory(loose); RoutePackage.ResourceRootFor(Path.Combine(loose, "any.route.xml")).Should().Be(loose); } [Theory] [InlineData("order.xsd")] [InlineData("resources/order.xsd")] public void Generator_And_Check_ReadAResource_TheSameWay(string reference) { // The redb-route-file template writes file="resources/order.xsd": check accepted it, the // generator prefixed resources/ again and failed on resources/resources/order.xsd. var dir = NewProject("Both"); File.WriteAllText(Path.Combine(dir, "resources", "order.xsd"), """ """); var route = Path.Combine(dir, "routes", "both.route.xml"); File.WriteAllText(route, $""" """); RoutePackage.Check(dir, "both", "1.0.0").Errors.Should().NotContain(e => e.Message.Contains("order.xsd")); new RouteProjectResourceResolver(route).Resolve(reference) .Should().Be(Path.Combine(dir, "resources", "order.xsd")); XmlCodeGenerator.Generate(System.Xml.Linq.XDocument.Load(route), "BothRoutes", "Tests.Generated", sourceName: route) .Should().Contain($"""ValidateXsdFile("{reference}")""", "the schema is found, and the generated code keeps the file"); } [Fact] public void Generator_NamesEveryPlaceItLooked_WhenAResourceIsMissing() { var dir = NewProject("Missing"); var route = Path.Combine(dir, "routes", "missing.route.xml"); File.WriteAllText(route, """ """); var act = () => XmlCodeGenerator.Generate(System.Xml.Linq.XDocument.Load(route), "MissingRoutes", "Tests.Generated", sourceName: route); act.Should().Throw() .Where(e => e.Message.Contains(Path.Combine(dir, "resources", "nothing.xsd")) && e.Message.Contains(Path.Combine(dir, "nothing.xsd"))); } // ── steps that can never run ───────────────────────────────────────────── [Fact] public void StepsAfterATerminalStep_AreFlagged_WithThePosition() { // is Camel's markRollbackOnly() now (119e76d7): it stops the route, like // ; always throws. A step written after any of them never runs. var dir = ProjectWithBean("", """ after the rollback """); var warnings = RoutePackage.Check(dir, "p", "1.0.0").Warnings.ToList(); warnings.Should().Contain(w => w.Message.Contains("") && w.Message.Contains("") && w.File.StartsWith("routes/deep.route.xml("), "the first unreachable step is named, with its position"); warnings.Should().Contain(w => w.Message.Contains("") && w.Message.Contains(""), "a branch body is a step list too"); } [Fact] public void ATerminalStepAtTheEnd_IsNotFlagged() { var dir = ProjectWithBean("", """ timed out """); RoutePackage.Check(dir, "p", "1.0.0").Warnings .Should().NotContain(w => w.Message.Contains("never runs")); } // ── the packaging gate: negatives ──────────────────────────────────────── [Fact] public void BrokenMarkup_IsABuildError_WithThePosition() { var dir = NewProject("Broken"); File.WriteAllText(Path.Combine(dir, "routes", "broken.route.xml"), """ """); var result = RoutePackage.Check(dir, "broken", "1.0.0"); result.Errors.Should().Contain(e => e.File.StartsWith("routes/broken.route.xml(") && e.Message.Contains("nosuch")); RoutePackage.Build(dir, "broken", "1.0.0", Path.Combine(_root, "out2")) .Errors.Should().NotBeEmpty("errors refuse the build"); File.Exists(Path.Combine(_root, "out2", "broken-1.0.0.tpkg")).Should().BeFalse(); } [Fact] public void MissingResource_IsABuildError() { var dir = NewProject("Res"); File.WriteAllText(Path.Combine(dir, "routes", "res.route.xml"), """ """); RoutePackage.Check(dir, "res", "1.0.0").Errors .Should().Contain(e => e.Message.Contains("schemas/missing.json") && e.Message.Contains("resources")); } [Fact] public void LiteralSecretInAUri_IsAWarning_NotSilence() { var dir = NewProject("Sec"); File.WriteAllText(Path.Combine(dir, "routes", "sec.route.xml"), """ """); var result = RoutePackage.Check(dir, "sec", "1.0.0"); result.Warnings.Should().Contain(w => w.Message.Contains("literal secret")); result.Errors.Should().BeEmpty("the heuristic warns, it does not block"); } // ── deep bean checks (a type resolver = the built assemblies at hand) ─── private static Type? TestResolver(string typeName) => Type.GetType(typeName) ?? typeof(RoutePackagingTests).Assembly.GetType(typeName.Split(',')[0].Trim()); private string ProjectWithBean(string beanXml, string beanUse = "") { var dir = NewProject("Deep" + Guid.NewGuid().ToString("N")[..6]); File.WriteAllText(Path.Combine(dir, "routes", "deep.route.xml"), $""" {beanXml} {(beanUse.Length > 0 ? beanUse : "")} """); return dir; } [Fact] public void DeepChecks_ResolveEveryTypeAttribute_WithThePosition() { // exceptions= is a comma-separated LIST of types, so an assembly-qualified name splits into // two entries and the second ('redb.Route') resolves to nothing. The gate held the built // assemblies and said nothing; the worker failed at load (SerialNumbers.Xml, 2026-09-18). var dir = ProjectWithBean("", """ """); var errors = RoutePackage.Check(dir, "p", "1.0.0", TestResolver).Errors; errors.Should().Contain(e => e.Message.Contains("'redb.Route'") && e.File.StartsWith("routes/deep.route.xml("), "every entry of a type list is resolved, and the finding carries the position"); errors.Should().Contain(e => e.Message.Contains("'No.Such.Target, Nowhere'")); errors.Should().NotContain(e => e.Message.Contains("'System.TimeoutException'")); } [Fact] public void DeepChecks_AcceptTypeListsThatResolve() { var dir = ProjectWithBean("", """ """); RoutePackage.Check(dir, "p", "1.0.0", TestResolver).Errors.Should().BeEmpty(); } [Fact] public void DeepChecks_CatchARenamedType_ANonPublicType_AndABadProperty() { var missing = ProjectWithBean(""""""); RoutePackage.Check(missing, "p", "1.0.0", TestResolver).Errors .Should().Contain(e => e.Message.Contains("was not found in the built assemblies")); var badProperty = ProjectWithBean($""" """); RoutePackage.Check(badProperty, "p", "1.0.0", TestResolver).Errors .Should().Contain(e => e.Message.Contains("no writable public property 'NoSuchProperty'")); } [Fact] public void DeepChecks_CatchAMissingBeanMethod_AndPassAGoodOne() { var bad = ProjectWithBean( $"""""", """"""); RoutePackage.Check(bad, "p", "1.0.0", TestResolver).Errors .Should().Contain(e => e.Message.Contains("no public method 'NoSuchMethod'")); var good = ProjectWithBean( $"""""", """"""); RoutePackage.Check(good, "p", "1.0.0", TestResolver).Errors.Should().BeEmpty(); } [Fact] public void WithoutAResolver_TheDeepChecksStayQuiet() { var dir = ProjectWithBean(""""""); RoutePackage.Check(dir, "p", "1.0.0").Errors .Should().NotContain(e => e.Message.Contains("built assemblies"), "without the assemblies at hand the check cannot claim the type is missing"); } // ── bean lists and references ──────────────────────────────────────────── private static string Q() => $"{typeof(TType).FullName}, x"; [Fact] public void BeanReferences_FollowTheLoadOrder_AcrossFiles() { // Route files load in manifest order (by name): a.route.xml before b.route.xml. var dir = NewProject("Refs"); File.Delete(Path.Combine(dir, "routes", "main.route.xml")); File.WriteAllText(Path.Combine(dir, "routes", "a.route.xml"), $""" """); File.WriteAllText(Path.Combine(dir, "routes", "b.route.xml"), $""" """); var result = RoutePackage.Check(dir, "refs", "1.0.0"); result.Errors.Should().ContainSingle(e => e.Message.Contains("'late' points forward")) .Which.File.Should().StartWith("routes/a.route.xml(4,"); result.Warnings.Should().Contain(w => w.Message.Contains("'external' is not declared by any "), "module code may register it — the gate cannot know"); result.Errors.Should().NotContain(e => e.Message.Contains("'early'"), "a later file may look back"); } [Fact] public void BeanGrammar_IsTheLoadersGrammar_InTheGate() { var dir = ProjectWithBean($""" """); RoutePackage.Check(dir, "p", "1.0.0").Errors .Should().Contain(e => e.Message.Contains("a bean reference is the bare name")); } [Fact] public void DeepChecks_HoldListItemsAndReferences_AgainstTheirTargets() { var dir = ProjectWithBean($""" x """); var errors = RoutePackage.Check(dir, "p", "1.0.0", TestResolver).Errors.Select(e => e.Message).ToList(); errors.Should().Contain(m => m.Contains($"'{typeof(ProbeOptions).FullName}' is not assignable to ProbePartner for 'Partners[0]'"), "a referenced bean's type is known from its declaration"); errors.Should().Contain(m => m.Contains("for 'Partners[1]'"), "a nested bean inside a list is checked too"); errors.Should().Contain(m => m.Contains("'Title' is String, which a does not build into")); errors.Should().Contain(m => m.Contains($"'{typeof(ProbeRoster).FullName}' is not assignable to ProbePartner for 'Signing'"), "a factory bean is what its method returns"); errors.Should().Contain(m => m.Contains("'constructorArg 1': a passed to a constructor names its element type with of=")); errors.Should().HaveCount(5, "the factory argument is typed by the parameter and is right"); } [Fact] public void DeepChecks_PassAWellTypedNode() { var dir = ProjectWithBean($""" {"{{"}port{"}}"} """); RoutePackage.Check(dir, "p", "1.0.0", TestResolver).Errors.Should().BeEmpty(); } [Fact] public void PlaceholderSecret_DoesNotTriggerTheWarning() { var dir = NewProject("SecOk"); File.WriteAllText(Path.Combine(dir, "routes", "sec.route.xml"), """ """); RoutePackage.Check(dir, "secok", "1.0.0").Warnings .Should().NotContain(w => w.Message.Contains("literal secret")); } [Fact] public void Aggregate_ForceCompletionOnStop_IsKnownToTheGate() { // Apache Camel forceCompletionOnStop (04edaf35): the attribute is part of the format, typed bool. string Routes(string value) => $""" batch """; var good = NewProject("AggGood"); File.WriteAllText(Path.Combine(good, "routes", "main.route.xml"), Routes("true")); var bad = NewProject("AggBad"); File.WriteAllText(Path.Combine(bad, "routes", "main.route.xml"), Routes("sometimes")); RoutePackage.Check(good, "agg", "1.0.0").Errors.Should().BeEmpty(); RoutePackage.Check(bad, "agg", "1.0.0").Errors .Should().Contain(e => e.Message.Contains("forceCompletionOnStop")); } } Path: redb-route/tests/redb.Route.Tests.Xml/SpanTagXmlTests.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.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/SpanTagXmlTests.cs ---- using System.Diagnostics; using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Definitions; using redb.Route.Expressions; using redb.Route.Telemetry; using redb.Route.Xml; namespace redb.Route.Tests.Xml; /// /// <spanTag>, the markup form of .SpanTag(key, value, target). Shaped as <setHeader>: /// value is a literal and expr an expression, exactly one of them; target picks the span. The /// definition it builds and the C# it prints are checked here; what lands on which span is covered by the engine's /// own SpanTagTests. /// public class SpanTagXmlTests : IAsyncLifetime { private readonly RouteContext _context = new(); public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { await _context.DisposeAsync(); GC.SuppressFinalize(this); } private SpanTagDefinition[] TagsOf(string xml) { _context.AddXmlRoutesFromContent(xml, ""); var builder = _context.RouteBuilders.Single(); if (!builder.IsBuilt) builder.InternalBuild(_context); return builder.Definitions.Single().Outputs.OfType().ToArray(); } private static string CodeOf(string xml) => XmlCodeGenerator.Generate(System.Xml.Linq.XDocument.Parse(xml), "Tags", "Tests.Generated", sourceName: ""); [Fact] public void Value_IsALiteral_AndTheTargetDefaultsToTheEnclosingSpan() { var tag = TagsOf(""" """).Single(); tag.Key.Should().Be("flow.name"); tag.Target.Should().Be(SpanTarget.Enclosing); tag.Value.Should().BeOfType("value is a literal, as on ") .Which.Evaluate(new Exchange()).Should().Be("${not.a.template}"); } [Fact] public void Expr_IsEvaluated_AndTheTargetIsTaken() { // The schema enumerates the names as they are, as for level="Debug" or policy="...". var tag = TagsOf(""" """).Single(); tag.Target.Should().Be(SpanTarget.Inbound); var exchange = new Exchange(new Message("b")); exchange.In.Headers["orderNo"] = "A-42"; tag.Value.Evaluate(exchange)?.ToString().Should().Be("A-42"); } [Fact] public void ValueAndExprTogether_IsAPositionedError() { var act = () => _context.AddXmlRoutesFromContent(""" """, ""); act.Should().Throw(); } [Fact] public void AnUnknownTarget_ReportsTheKnownNames() { var act = () => _context.AddXmlRoutesFromContent(""" """, ""); act.Should().Throw(); } [Fact] public void AReservedKey_IsAPositionedError() { var act = () => _context.AddXmlRoutesFromContent(""" """, ""); act.Should().Throw().WithMessage("*redb.*"); } [Fact] public void Print_LiteralExprAndTarget() { var code = CodeOf(""" """); code.Should().Contain("SpanTag(\"flow.name\", \"ack\")"); code.Should().Contain("SpanTag(\"sap.order.id\", Expr(\"${header.orderNo}\"), global::redb.Route.Telemetry.SpanTarget.Inbound)"); code.Should().Contain("SpanTag(\"sap.batch\", Expr(\"${property.batch}\"))", "the default target is not printed"); } } Path: redb-route/tests/redb.Route.Tests.Xml/StrictEndpointParametersTests.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.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/StrictEndpointParametersTests.cs ---- using System.Xml.Linq; using AwesomeAssertions; using redb.Route.Components; using redb.Route.Components.Bean; using redb.Route.Core; using redb.Route.Xml; using redb.Route.Xml.Packaging; namespace redb.Route.Tests.Xml; /// /// A connector refuses a parameter it has no option for unless it is lenient /// (EndpointOptions.IsLenient). Route-XML follows the same rule everywhere it reads an /// endpoint before the route starts: the catalog carries it, the catalog schema refuses the /// unknown attribute in the editor, the package gate refuses the unknown name at check --bin /// — and a foreign-namespace attribute, which the format tolerates as metadata, is never an option. /// public sealed class StrictEndpointParametersTests : IAsyncLifetime { private readonly RouteContext _context = new(); private readonly string _root = Path.Combine(Path.GetTempPath(), "redb-xml-strict-" + Guid.NewGuid().ToString("N")); public StrictEndpointParametersTests() => Directory.CreateDirectory(_root); public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { await _context.DisposeAsync(); Directory.Delete(_root, recursive: true); GC.SuppressFinalize(this); } /// timer: is strict, bean: is lenient — both from the core, no connector package needed. private static readonly IReadOnlyList Catalog = ComponentCatalog.Build([new TimerComponent(), new BeanComponent(), new DirectComponent()]); private static Type? Resolve(string typeName) => typeof(TimerComponent).Assembly.GetType(typeName); // ── the catalog ────────────────────────────────────────────────────────── [Fact] public void Catalog_CarriesTheEnginesLenientFlag() { Catalog.Single(c => c.Scheme == "timer").Lenient.Should().BeFalse(); Catalog.Single(c => c.Scheme == "bean").Lenient.Should().BeTrue(); ComponentCatalog.ToJson(Catalog).Should().Contain("\"lenient\": false"); } // ── the catalog schema ─────────────────────────────────────────────────── private static IReadOnlyList<(int Line, int Column, string Message)> ValidateWithCatalog(string endpoint) => XmlRouteSchema.Validate(XDocument.Parse($""" {endpoint} """, LoadOptions.SetLineInfo), ElementRegistry.CreateDefault(), Catalog); /// The same with the endpoint as the target: bean is producer-only, so it is offered only there. private static IReadOnlyList<(int Line, int Column, string Message)> ValidateTargetWithCatalog(string endpoint) => XmlRouteSchema.Validate(XDocument.Parse($""" {endpoint} """, LoadOptions.SetLineInfo), ElementRegistry.CreateDefault(), Catalog); [Fact] public void Schema_RefusesAnUnknownAttribute_OnAStrictConnector() => ValidateWithCatalog("""""") .Should().ContainSingle(p => p.Message.Contains("perod")); [Fact] public void Schema_KeepsAnUnknownAttribute_OnALenientConnector_AndAForeignOneEverywhere() { ValidateTargetWithCatalog("""""").Should().BeEmpty(); ValidateWithCatalog("""""").Should().BeEmpty(); } // ── the loader ─────────────────────────────────────────────────────────── [Fact] public async Task ForeignNamespaceAttribute_OnAStructuredEndpoint_IsNotAParameter() { // An editor mark (the graph's layout, a review note) in its own namespace: tolerated by // the format, and before this fix passed to the connector as 'xy' — which a strict // connector refuses when the route starts. _context.AddXmlRoutesFromContent(""" """); var start = () => _context.Start(); await start.Should().NotThrowAsync(); } // ── the package gate ───────────────────────────────────────────────────── private string Project(string routeXml) { var dir = RouteProjectScaffold.Create(_root, "Strict" + Guid.NewGuid().ToString("N")[..6]); File.WriteAllText(Path.Combine(dir, "routes", "main.route.xml"), routeXml); return dir; } [Fact] public void Gate_RefusesAnUnknownName_InBothForms_InTheEnginesWords() { var dir = Project(""" """); var errors = RoutePackage.Check(dir, "p", "1.0.0", Resolve, catalog: Catalog).Errors.ToList(); errors.Should().Contain(e => e.File == "routes/main.route.xml(3,6)" && e.Message.Contains("'perod' is not an option of the Timer endpoint") && e.Message.Contains("Did you mean 'period'?")); errors.Should().Contain(e => e.File.StartsWith("routes/main.route.xml(7,") && e.Message.Contains("'delya' is not an option of the Timer endpoint")); } [Fact] public void Gate_PassesKnownNames_LenientConnectors_ForeignAttributes_AndRuntimeNames() { var dir = Project(""" """); RoutePackage.Check(dir, "p", "1.0.0", Resolve, catalog: Catalog).Errors .Should().NotContain(e => e.Message.Contains("is not an option")); } [Fact] public void Gate_WithoutACatalog_LeavesParametersToTheEngine() { var dir = Project(""" """); RoutePackage.Check(dir, "p", "1.0.0", Resolve).Errors .Should().NotContain(e => e.Message.Contains("is not an option")); } } Path: redb-route/tests/redb.Route.Tests.Xml/StructuredEndpointTests.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.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/StructuredEndpointTests.cs ---- using System.Xml.Linq; using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Xml; namespace redb.Route.Tests.Xml; /// /// The structured endpoint form — one generic normalization into the same /// URI string a hand-written address would be, for every scheme, with zero per-connector code. /// Exact-string assertions on the normalizer plus behavioral proof that the canon is identical /// (a structured address and a hand-written URI meet at the same endpoint). /// public class StructuredEndpointTests : IAsyncLifetime { private readonly RouteContext _context = new(); public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { await _context.DisposeAsync(); GC.SuppressFinalize(this); } // ── the normalizer, exact strings ──────────────────────────────────────── private string? Resolve(string stepXml, out List errors) { var ctx = new XmlParseContext(_context, ElementRegistry.CreateDefault(), "probe.xml"); var step = XElement.Parse(stepXml, LoadOptions.SetLineInfo); var uri = StructuredEndpoint.Resolve(step, ctx, out _); errors = [.. ctx.Errors]; return uri; } [Fact] public void Attributes_BecomeQueryOptions_PathAttributeIsThePath() { var uri = Resolve(""" """, out var errors); errors.Should().BeEmpty(); uri.Should().Be("kafka://orders?key=${header.tripId}&groupId=orders-svc"); } [Fact] public void CdataPath_ParamFamily_AndTextOption_AllNormalizeIntoOptions() { var uri = Resolve(""" """, out var errors); errors.Should().BeEmpty(); uri.Should().Be("sql://SELECT * FROM outbox WHERE sent = 0" + "?dataSource=#main-db" + "¶m.login=${header.login}" + "&onSuccess=UPDATE outbox SET sent = 1 AND flags = 2"); } [Fact] public void AmpersandAndPercent_InOptionValues_SurviveTheEngineRoundTrip() { var uri = Resolve(""" """, out var errors); errors.Should().BeEmpty(); // Only the two characters the query parse cannot survive are encoded… uri.Should().Be("sql://q?onSuccess=UPDATE t SET n = a %26 b WHERE p LIKE '%25x%25'"); // …and the engine's own parser hands the original text back. EndpointUriParser.Parse(uri!).RawParameters["onSuccess"] .Should().Be("UPDATE t SET n = a & b WHERE p LIKE '%x%'"); } [Fact] public void UriAndChild_Together_IsASchemaError() { Resolve("""""", out var errors); errors.Should().ContainSingle().Which.Should().Contain("either uri= or a structured endpoint child"); } [Fact] public void TwoEndpointChildren_IsASchemaError() { Resolve("""""", out var errors); errors.Should().ContainSingle().Which.Should().Contain("exactly one endpoint child"); } [Fact] public void NeitherUriNorChild_IsASchemaError() { Resolve("""""", out var errors); errors.Should().ContainSingle().Which.Should().Contain("requires the uri attribute or one endpoint child"); } [Fact] public void PathAttributeAndContent_Together_IsASchemaError() { Resolve("""SELECT 1""", out var errors); errors.Should().ContainSingle().Which.Should().Contain("carries its path more than once"); } [Fact] public void QuestionMarkInPath_IsASchemaError() { Resolve("""""", out var errors); errors.Should().ContainSingle().Which.Should().Contain("contains '?'"); } [Fact] public void MalformedOptionChild_NamesBothValidShapes() { Resolve("""""", out var errors); errors.Should().ContainSingle().Which .Should().Contain("family entry").And.Contain("text option"); } // ── the canon is one: structured and hand-written meet at the same endpoint ── [Fact] public async Task StructuredTo_DeliversToTheHandWrittenUriConsumer() { object? delivered = null; _context.AddRoutes(r => r.From("direct://s72-sink").Process(e => delivered = e.In.Body)); _context.AddXmlRoutesFromContent(""" """); await _context.Start(); var producer = _context.GetEndpoint("direct://s72-in").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("canon"))); delivered.Should().Be("canon"); } [Fact] public async Task StructuredFrom_IsAConsumerLikeAnyOther() { var seen = new List(); _context.AddXmlRoutesFromContent(""" """); await _context.Start(); var producer = _context.GetEndpoint("direct://s72-from-in").CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("x")); await producer.Process(exchange); seen.Add(exchange.In.Headers["via"]); seen.Should().Equal("structured"); } [Fact] public void StructuredFrom_WithPlaceholderInAnOption_IsRefusedLikeTheUriForm() { var act = () => _context.AddXmlRoutesFromContent(""" """); act.Should().Throw() .WithMessage("*consumer URI cannot carry ${*"); } [Fact] public void UnregisteredStructuredScheme_IsCaughtAtLoad_AtTheChildPosition() { var act = () => _context.AddXmlRoutesFromContent(""" """, "structured.xml"); act.Should().Throw() .WithMessage("*structured.xml(5,*scheme 'sql' is not registered*"); } } Path: redb-route/tests/redb.Route.Tests.Xml/TestKitOverXmlTests.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.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/TestKitOverXmlTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.TestKit; using redb.Route.Xml; namespace redb.Route.Tests.Xml; /// A registration-only stand-in for an external broker scheme. public sealed class KafkaStubComponent : ComponentBase { public override string Scheme => "kafka"; public override IEndpoint CreateEndpoint(EndpointUri uri) => throw new NotSupportedException("the test mocks this endpoint before anything creates it"); } /// /// An XML route is tested the same way a C# route is — the existing TestKit /// (advice, endpoint mocking, weaving, one-line send) over the XML loader, with no test host of /// our own. Includes the two guarantees the phase names explicitly: WeaveById finds /// steps by the XML id attribute, and a URI password never surfaces in mock names or reports. /// public class TestKitOverXmlTests : IAsyncLifetime { private readonly RouteContext _context = new(); public TestKitOverXmlTests() => _context.AddComponent(new KafkaStubComponent()); public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { await _context.DisposeAsync(); GC.SuppressFinalize(this); } [Fact] public async Task TheCanonicalTestKitFlow_WorksOverAnXmlRoute() { _context.AddXmlRoutesFromContent(""" """); _context.AdviceAllRoutes(a => a.MockEndpoints("kafka://*")); await _context.Start(); var mock = _context.Mock("kafka://orders").ExpectMessageCount(1).ExpectHeader("seen", "true"); await _context.SendBody("direct://tk-in", "payload"); await mock.AssertIsSatisfiedAsync(TimeSpan.FromSeconds(2)); } [Fact] public async Task WeaveById_FindsTheXmlStep_ByItsIdAttribute() { _context.AddXmlRoutesFromContent(""" """); _context.AdviceRoute("weave-me", a => { a.WeaveById("mark-step").Replace(d => d.SetHeader("mark", "woven")); a.MockEndpoints("kafka://*"); }); await _context.Start(); var mock = _context.Mock("kafka://weave").ExpectMessageCount(1).ExpectHeader("mark", "woven"); await _context.SendBody("direct://tk-weave-in", "x"); await mock.AssertIsSatisfiedAsync(TimeSpan.FromSeconds(2)); } [Fact] public async Task PasswordFromTheUri_NeverSurfaces_InMockNameOrAssertReport() { _context.AddXmlRoutesFromContent(""" """); _context.AdviceAllRoutes(a => a.MockEndpoints("kafka://*")); await _context.Start(); MockUri.For("kafka://orders?password=hush-hush").Should().NotContain("hush-hush", "the query string, where passwords live, must not become part of the mock name"); // A failing assertion writes its report into the exception message — the place it // would leak from into CI logs. var mock = _context.Mock("kafka://orders?password=hush-hush").ExpectMessageCount(2); await _context.SendBody("direct://tk-secret-in", "only-one"); var act = () => mock.AssertIsSatisfiedAsync(TimeSpan.FromMilliseconds(300)); var report = (await act.Should().ThrowAsync()).Which.ToString(); report.Should().NotContain("hush-hush"); } [Fact] public async Task TwoContexts_DoNotSeeEachOthersXmlRoutes() { _context.AddXmlRoutesFromContent(""" """); await using var other = new RouteContext(); other.AddXmlRoutesFromContent(""" """); await _context.Start(); await other.Start(); _context.Routes.Select(r => r.RouteId).Should().Contain("iso-a").And.NotContain("iso-b"); other.Routes.Select(r => r.RouteId).Should().Contain("iso-b").And.NotContain("iso-a"); } } Path: redb-route/tests/redb.Route.Tests.Xml/TypedReferenceGateTests.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.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/TypedReferenceGateTests.cs ---- using AwesomeAssertions; using redb.Route.Xml; using redb.Route.Xml.Packaging; namespace redb.Route.Tests.Xml; /// /// Row 7 part 3: with the built assemblies at hand, a name in an option marked [RegistryReference(typeof(T))], /// bare or with #, URI form or structured form, is held against T per connector: a bean the package /// declares with a type that is not a T is an error, worded as for headerFilterStrategy. An option marked /// without a type is never checked; a bean whose type does not load, or that the package does not declare, gives no /// type error; values from configuration or expressions are left alone. /// public sealed class TypedReferenceGateTests : IDisposable { private readonly string _root = Path.Combine(Path.GetTempPath(), "redb-xml-typed-" + Guid.NewGuid().ToString("N")); public TypedReferenceGateTests() => Directory.CreateDirectory(_root); public void Dispose() => Directory.Delete(_root, recursive: true); private static readonly IReadOnlyList Catalog = ComponentCatalog.Build([new ProbeRefComponent()]); private static Type? Resolve(string typeName) => Type.GetType(typeName); private static string T() => $"{typeof(TType).FullName}, {typeof(TType).Assembly.GetName().Name}"; private PackageResult Check(string step, string beans, IReadOnlyList? catalog = null) { var dir = RouteProjectScaffold.Create(_root, "Typ" + Guid.NewGuid().ToString("N")[..6]); File.WriteAllText(Path.Combine(dir, "routes", "main.route.xml"), $""" {beans} {step} """); return RoutePackage.Check(dir, "p", "1.0.0", Resolve, catalog: catalog ?? Catalog); } private static IEnumerable TypeErrors(PackageResult result) => result.Errors.Select(e => e.Message).Where(m => m.Contains("is registered as", StringComparison.Ordinal)); private static string WrongBean => $""""""; [Theory] [InlineData("""""", "")] [InlineData("""""", "")] [InlineData("""""", "")] public void ABeanOfTheWrongType_IsAnError_InEveryForm(string step, string at) { TypeErrors(Check(step, WrongBean)).Should().ContainSingle().Which.Should().Be( $"{at}: 'main' is registered as {typeof(DeepBeanTarget).FullName}, which is not an {nameof(ProbeRefFactory)}."); } [Fact] public void ABeanOfTheExpectedType_Passes() { TypeErrors(Check("""""", $"""""")) .Should().BeEmpty(); } [Fact] public void AnUntypedMark_IsNeverTypeChecked() { TypeErrors(Check("""""", WrongBean)).Should().BeEmpty(); } [Fact] public void ABeanWhoseTypeDoesNotLoad_GivesNoTypeError() { TypeErrors(Check("""""", """""")) .Should().BeEmpty(); } [Fact] public void AnUndeclaredBean_IsOnlyTheWarning() { var result = Check("""""", ""); TypeErrors(result).Should().BeEmpty(); result.Warnings.Should().Contain(w => w.Message.StartsWith("'#main' is not declared", StringComparison.Ordinal)); } [Theory] [InlineData("""""")] [InlineData("""""")] public void AValueFromConfigurationOrAnExpression_IsLeftAlone(string step) { TypeErrors(Check(step, WrongBean)).Should().BeEmpty(); } private static string WrongStrategy => $""""""; [Theory] [InlineData("""""", "")] [InlineData("""""", "")] public void AUriInAnyOtherAttribute_IsHeldAgainstTheType_AsBefore(string step, string at) { TypeErrors(Check(step, WrongStrategy)).Should().ContainSingle().Which.Should().Be( $"{at}: 'x' is registered as {typeof(DeepBeanTarget).FullName}, which is not an IHeaderFilterStrategy."); } [Fact] public void ABareNameInAnyOtherAttribute_IsAReference() { Check("""""", "").Warnings .Should().ContainSingle(w => w.Message.StartsWith("'#x' is not declared", StringComparison.Ordinal)); } [Fact] public void AnEndpointPosition_IsReadOnce() { TypeErrors(Check("""""", WrongStrategy)).Should().ContainSingle(); } [Fact] public void TheCheckIsPerConnector_AnOptionOfTheSameNameElsewhereIsNotHeldAgainstThisType() { // vm has no connectionFactory option; the name means nothing there and is not checked against ProbeRefFactory. TypeErrors(Check("""""", WrongBean)).Should().BeEmpty(); } // Row 57: ftp and sftp share RemoteFileEndpointOptions, whose connectionFactory was marked without a type, so a bean // of any class passed the gate. The mark now names the factories' common base. private static readonly IReadOnlyList RemoteFileCatalog = ComponentCatalog.Build([new redb.Route.Ftp.FtpComponent(), new redb.Route.Sftp.SftpComponent()]); [Theory] [InlineData("ftp")] [InlineData("sftp")] public void ARemoteFileConnector_HoldsItsConnectionFactoryAgainstTheFactoryType(string scheme) { TypeErrors(Check($"""""", WrongBean, RemoteFileCatalog)) .Should().ContainSingle().Which.Should().EndWith( $"'main' is registered as {typeof(DeepBeanTarget).FullName}, which is not an {nameof(redb.Route.GenericFile.RemoteFileConnectionFactory)}."); } [Theory] [InlineData("ftp", typeof(redb.Route.Ftp.FtpConnectionFactory))] [InlineData("sftp", typeof(redb.Route.Sftp.SftpConnectionFactory))] public void ARemoteFileConnector_AcceptsItsOwnFactory(string scheme, Type factory) { var bean = $""""""; TypeErrors(Check($"""""", bean, RemoteFileCatalog)).Should().BeEmpty(); } } Path: redb-route/tests/redb.Route.Tests.Xml/UnclosedPlaceholderTests.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.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/UnclosedPlaceholderTests.cs ---- using AwesomeAssertions; using redb.Route.Core; using redb.Route.Xml; using redb.Route.Xml.Packaging; namespace redb.Route.Tests.Xml; /// /// An unclosed ${ is an error (owner decision 2026-11-05): a route file fails to load at the element, and the /// package gate reports it at the attribute, in every place that holds an expression or an address. /// public sealed class UnclosedPlaceholderTests : IAsyncLifetime, IDisposable { private readonly RouteContext _context = new(); private readonly string _root = Path.Combine(Path.GetTempPath(), "redb-xml-unclosed-" + Guid.NewGuid().ToString("N")); public UnclosedPlaceholderTests() => Directory.CreateDirectory(_root); public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() => await _context.DisposeAsync(); public void Dispose() => Directory.Delete(_root, recursive: true); private static Type? Resolve(string typeName) => Type.GetType(typeName); private string Project(string steps) { var dir = RouteProjectScaffold.Create(_root, "Unclosed" + Guid.NewGuid().ToString("N")[..6]); File.WriteAllText(Path.Combine(dir, "routes", "main.route.xml"), $""" {steps} """); return dir; } [Fact] public void Load_FailsAtTheElement_WithThePosition() { var act = () => _context.AddXmlRoutesFromContent(""" """); act.Should().Throw() .WithMessage("*(4,*unclosed '${' at position 7 of \"total ${header.amount\": the placeholder has no closing '}'.*"); } [Theory] [InlineData("""""", "expr=")] [InlineData("""""", "expr=")] [InlineData("""""", "uri=")] [InlineData("""""", "message=")] public void Gate_ReportsAnError_AtTheAttribute(string step, string attribute) { var errors = RoutePackage.Check(Project(step), "p", "1.0.0", Resolve).Errors.ToList(); errors.Should().Contain(e => e.Message.StartsWith(attribute + " unclosed '${'", StringComparison.Ordinal) && e.File.Contains("main.route.xml(")); } [Fact] public void Gate_ReportsTheFromAddress() { var dir = RouteProjectScaffold.Create(_root, "UnclosedFrom"); File.WriteAllText(Path.Combine(dir, "routes", "main.route.xml"), """ """); RoutePackage.Check(dir, "p", "1.0.0", Resolve).Errors .Should().Contain(e => e.Message.StartsWith("uri= unclosed '${'", StringComparison.Ordinal)); } [Theory] [InlineData("""""")] [InlineData("""""")] [InlineData("""""")] [InlineData("""""")] public void Gate_LeavesLiteralsAndClosedPlaceholdersAlone(string step) { RoutePackage.Check(Project(step), "p", "1.0.0", Resolve).Errors .Should().NotContain(e => e.Message.Contains("unclosed '${'", StringComparison.Ordinal)); } } Path: redb-route/tests/redb.Route.Tests.Xml/ValidateXsdFileXmlTests.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.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/ValidateXsdFileXmlTests.cs ---- using System.Xml.Linq; using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Xml; namespace redb.Route.Tests.Xml; /// /// Row 37 in markup: <validateXsd file="…" schemaRoot="…"/> keeps the file, so the schema's imports and /// includes resolve relative to it; the code generator writes ValidateXsdFile(…) for it, and inline content /// stays ValidateXsd(…) with the text. /// public sealed class ValidateXsdFileXmlTests : IAsyncLifetime { private readonly string _dir = Path.Combine(Path.GetTempPath(), "xsd-xml-" + Guid.NewGuid().ToString("N")[..8]); private readonly RouteContext _context = new(); public Task InitializeAsync() { Directory.CreateDirectory(Path.Combine(_dir, "common")); Directory.CreateDirectory(Path.Combine(_dir, "order")); File.WriteAllText(Path.Combine(_dir, "common", "common.xsd"), """ """); File.WriteAllText(Path.Combine(_dir, "order", "order.xsd"), """ """); return Task.CompletedTask; } public async Task DisposeAsync() { await _context.DisposeAsync(); Directory.Delete(_dir, recursive: true); } private string Schema => Path.Combine(_dir, "order", "order.xsd").Replace('\\', '/'); private static string Routes(string step) => $""" {step} """; [Fact] public async Task FileWithSchemaRoot_ReadsTheImports() { _context.AddXmlRoutesFromContent(Routes($""""""), ""); await _context.Start(); var producer = _context.GetEndpoint("direct://xsd-file-in").CreateProducer(); await producer.Start(); var good = new Exchange(new Message("""EUR""")); await producer.Process(good); var bad = () => producer.Process(new Exchange(new Message("""euro"""))); good.Exception.Should().BeNull(); await bad.Should().ThrowAsync() .WithMessage("*'urn:common:Code'*Pattern*", "the imported type's pattern applies"); } [Fact] public async Task FileWithoutSchemaRoot_RefusesTheImportOutsideItsDirectory_WhenTheRouteStarts() { _context.AddXmlRoutesFromContent(Routes($""""""), ""); var act = () => _context.Start(); (await act.Should().ThrowAsync()) .Which.ToString().Should().Contain("validateXsd: the schema refers to").And.Contain("imports and includes stay inside the package"); } [Fact] public void InlineContentWithSchemaRoot_IsAnError() { var act = () => _context.AddXmlRoutesFromContent( Routes("""]]>"""), ""); act.Should().Throw().WithMessage("*schemaRoot=…> needs the file attribute*"); } [Fact] public void AMissingFile_IsStillAnErrorWhereTheRouteIsParsed() { var act = () => _context.AddXmlRoutesFromContent(Routes(""""""), ""); act.Should().Throw(); } [Fact] public void TheCodeGenerator_WritesTheFileForm() { var code = XmlCodeGenerator.Generate( XDocument.Parse(Routes($"""""")), "XsdFile", "Tests.Generated", sourceName: ""); code.Should().Contain($"""ValidateXsdFile("{Schema}", "urn:order", "..", false)"""); } [Fact] public void TheCodeGenerator_WritesTheFileFormWithDefaultsLeftOut() { var code = XmlCodeGenerator.Generate( XDocument.Parse(Routes($"""""")), "XsdFile", "Tests.Generated", sourceName: ""); code.Should().Contain($"""ValidateXsdFile("{Schema}", null, "..")"""); } [Fact] public void TheCodeGenerator_KeepsInlineContentAsText() { var code = XmlCodeGenerator.Generate( XDocument.Parse(Routes("""]]>""")), "XsdInline", "Tests.Generated", sourceName: ""); code.Should().Contain("ValidateXsd(null, "); code.Should().NotContain("ValidateXsdFile"); } } Path: redb-route/tests/redb.Route.Tests.Xml/XmlBeanFunctionTests.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.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/XmlBeanFunctionTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Xml; namespace redb.Route.Tests.Xml; /// A declared bean the expression function calls from markup. public class XmlLoyalty { public string Gold { get; set; } = "ann"; public bool IsGold(string? name) => name == Gold; public string Badge(string name, int points) => $"{name}:{points}"; } /// /// The bean: expression function in route markup: a bare call in a condition, a call inside a ${...} /// value, against a bean the document itself declares. /// public sealed class XmlBeanFunctionTests : IAsyncLifetime { private readonly RouteContext _context = new(); public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() => await _context.DisposeAsync(); [Fact] public async Task FilterAndSetBody_CallTheDeclaredBean() { _context.AddXmlRoutesFromContent($$""" """); await _context.Start(); var producer = _context.GetEndpoint("direct://xml-bean-fn").CreateProducer(); await producer.Start(); var mock = (redb.Route.Components.MockEndpoint)_context.GetEndpoint("mock://gold"); foreach (var name in new[] { "ann", "bob" }) { var exchange = new Exchange(new Message("in")); exchange.In.Headers["name"] = name; exchange.In.Headers["points"] = 7; await producer.Process(exchange); } mock.ReceivedExchanges.Select(e => e.In.Body).Should().Equal("ann:7"); } } Path: redb-route/tests/redb.Route.Tests.Xml/XmlBeanListAndRefTests.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.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/XmlBeanListAndRefTests.cs ---- using System.Xml.Linq; using AwesomeAssertions; using redb.Route.Core; using redb.Route.Xml; namespace redb.Route.Tests.Xml; /// One partner of a node: registered on its own, listed by the node. public class ProbePartner { public string? Id { get; set; } } /// A node holding its partners in every collection shape a list builds into. public class ProbeNode { public List Partners { get; set; } = []; public ProbePartner[]? PartnerArray { get; set; } public IReadOnlyList? ReadOnlyPartners { get; set; } public IEnumerable? Ports { get; set; } public List>? Groups { get; set; } public ProbePartner? Signing { get; set; } public string? Title { get; set; } } /// Partners through the constructor, and through a static creator taking a List. public class ProbeRoster(IReadOnlyList partners) { public IReadOnlyList Partners => partners; public static ProbeRoster Of(List partners) => new(partners); } /// /// <bean> lists and references: a node that lists partners registered on their own (the AS4 /// shape: each partner its own bean, rotation a second slot) is built from XML, into the declared /// collection type, and a reference may only look back — never forward, never at nothing. /// public class XmlBeanListAndRefTests : IAsyncLifetime { private readonly RouteContext _context = new(); public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { await _context.DisposeAsync(); GC.SuppressFinalize(this); } private static string T() => $"{typeof(TType).FullName}, {typeof(TType).Assembly.GetName().Name}"; private static string Partners => $""" """; private void LoadContext(string beans) => _context.AddXmlContextFromContent($""" {beans} """); // ── building ───────────────────────────────────────────────────────────── [Fact] public void Property_List_OfRefsAndAnInlineBean_BuildsEveryCollectionShape() { _context.SetProperty("as4.partner3.id", "initech"); _context.SetProperty("as4.port", "8443"); LoadContext(Partners + $""" {"{{"}as4.port{"}}"}8080 ab """); var node = _context.GetFromRegistry("node")!; var acme = _context.GetFromRegistry("acme"); var globex = _context.GetFromRegistry("globex"); node.Partners.Should().HaveCount(3); node.Partners[0].Should().BeSameAs(acme, "a reference is the registered instance, not a copy"); node.Partners[1].Should().BeSameAs(globex); node.Partners[2].Id.Should().Be("initech", "an inline bean resolves its placeholders like any other"); node.PartnerArray.Should().ContainSingle().Which.Should().BeSameAs(globex); node.ReadOnlyPartners.Should().Equal(acme!, globex!); node.Ports.Should().Equal(8443, 8080); node.Groups.Should().HaveCount(2); node.Groups![0].Should().Equal("a", "b"); node.Groups[1].Should().BeEmpty(); } [Fact] public void Property_RefAttribute_AssignsTheRegisteredBean() { LoadContext(Partners + $""" """); _context.GetFromRegistry("node")!.Signing .Should().BeSameAs(_context.GetFromRegistry("acme")); } [Fact] public void ConstructorArg_ListWithOf_BuildsTheArrayTheConstructorTakes() { LoadContext(Partners + $""" """); _context.GetFromRegistry("roster")!.Partners.Select(p => p.Id).Should().Equal("acme", "globex"); } [Fact] public void FactoryMethod_ListArgument_IsTypedByTheParameter() { LoadContext(Partners + $""" """); _context.GetFromRegistry("roster")!.Partners.Should().ContainSingle().Which.Id.Should().Be("globex"); } [Fact] public void ReferenceFromTheContextFile_ReachesABeanOfARoutesFile() { // The context file loads first, so a routes-file bean may point back at it. LoadContext(Partners); _context.AddXmlRoutesFromContent($""" """); _context.GetFromRegistry("node")!.Signing!.Id.Should().Be("globex"); } // ── refusals ───────────────────────────────────────────────────────────── [Fact] public void ForwardReference_IsAPositionedError_NotANull() { var act = () => LoadContext($""" """); act.Should().Throw() .WithMessage("*(3,*bean reference 'late' names nothing registered so far*"); } [Fact] public void UnknownReferenceInsideAList_IsAPositionedError() { var act = () => LoadContext($""" """); act.Should().Throw().WithMessage("*bean reference 'nobody' names nothing registered so far*"); } [Fact] public void ListItemOfTheWrongType_IsRefused_NamingTheItem() { var act = () => LoadContext($""" """); act.Should().Throw() .WithMessage($"*'{typeof(ProbeOptions).FullName}' is not assignable to ProbePartner for 'Partners[0]'*"); } [Fact] public void ListIntoAPropertyThatIsNoCollection_IsRefused() { var act = () => LoadContext($""" x """); act.Should().Throw().WithMessage("*'Title' is String, which a does not build into*"); } [Fact] public void ListOf_DifferingFromThePropertyElementType_IsRefused() { var act = () => LoadContext($""" """); act.Should().Throw().WithMessage("*differs from the element type*of 'Partners'*"); } [Fact] public void ConstructorList_WithoutOf_IsRefused() { var act = () => LoadContext(Partners + $""" """); act.Should().Throw().WithMessage("*'constructorArg 1': a passed to a constructor names its element type with of=*"); } [Fact] public void RefWithAHash_IsRefused_OneSpellingOnly() { var act = () => LoadContext(Partners + $""" """); act.Should().Throw().WithMessage("*a bean reference is the bare name: 'acme', not '#acme'*"); } [Fact] public void SlotWithTwoForms_IsRefused() { var act = () => LoadContext(Partners + $""" """); act.Should().Throw().WithMessage("* takes exactly one of: value=, ref=*"); } [Fact] public void ValueOutsideAList_IsRefused() { var act = () => LoadContext($""" x """); act.Should().Throw().WithMessage("* belongs inside a *"); } [Fact] public void Schema_AcceptsListsAndReferences_AndRejectsAForeignListItem() { var valid = XDocument.Parse($""" 1 """, LoadOptions.SetLineInfo); XmlRouteSchema.Validate(valid, ElementRegistry.CreateDefault()).Should().BeEmpty(); var invalid = XDocument.Parse(""" """, LoadOptions.SetLineInfo); XmlRouteSchema.Validate(invalid, ElementRegistry.CreateDefault()).Should().NotBeEmpty(); } // ── generated C# ───────────────────────────────────────────────────────── [Fact] public void Generator_PrintsReferencesAndLists() { var document = XDocument.Parse($""" {Partners} {"{{"}x{"}}"} """); var code = XmlCodeGenerator.Generate(document, "ListGenerated", "Tests.Generated"); code.Should().Contain("(\"Partners\", XmlBeans.List(Context!, null, [XmlBeans.Ref(Context!, \"acme\"), \"{{x}}\"]))") .And.Contain("(\"Signing\", XmlBeans.Ref(Context!, \"globex\"))") .And.Contain($"XmlBeans.List(Context!, \"{T()}\", [XmlBeans.Ref(Context!, \"acme\")])"); } [Fact] public void GeneratedCalls_BuildWhatTheXmlSectionBuilds() { // Exactly the calls the generator prints above, run against a context. _context.AddToRegistry("acme", XmlBeans.Create(_context, T(), [], [("Id", "acme")])); _context.AddToRegistry("node", XmlBeans.Create(_context, T(), [], [ ("Partners", XmlBeans.List(_context, null, [XmlBeans.Ref(_context, "acme")])), ("Signing", XmlBeans.Ref(_context, "acme")), ])); var roster = (ProbeRoster)XmlBeans.Create(_context, T(), [XmlBeans.List(_context, T(), [XmlBeans.Ref(_context, "acme")])], []); var acme = _context.GetFromRegistry("acme"); _context.GetFromRegistry("node")!.Partners.Should().ContainSingle().Which.Should().BeSameAs(acme); _context.GetFromRegistry("node")!.Signing.Should().BeSameAs(acme); roster.Partners.Should().ContainSingle().Which.Should().BeSameAs(acme); var forward = () => XmlBeans.Ref(_context, "late"); forward.Should().Throw().WithMessage("*'late' names nothing registered so far*"); } } Path: redb-route/tests/redb.Route.Tests.Xml/XmlBeanTypedArgumentsTests.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.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/XmlBeanTypedArgumentsTests.cs ---- using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Xml.Linq; using AwesomeAssertions; using redb.Route.Core; using redb.Route.Xml; using redb.Route.Xml.Packaging; namespace redb.Route.Tests.Xml; /// Two constructors the same two strings fit — the shape X509Certificate2 has. public class ProbeCredential { public ProbeCredential(string file, string password) => Chosen = $"string:{file}/{password}"; public ProbeCredential(string file, object options) => Chosen = $"object:{file}/{options}"; public string Chosen { get; } /// Two overloads of one arity: the value alone does not say which. public static ProbeCredential From(string file) => new(file, "via-string"); public static ProbeCredential From(int slot) => new($"slot-{slot}", "via-int"); } /// One constructor taking a decimal: text without type= is a string and fits no parameter. public class ProbePrice(decimal vatRate) { public decimal VatRate { get; } = vatRate; } /// /// <constructorArg type="…"> — Spring's constructor-arg type: when several /// constructors (or factory-method overloads) accept the same values, the argument types name the /// one to call, and each value is converted to its parameter's type. Without it the choice is /// the engine's (one fitting constructor, one overload of that arity), and an ambiguous one is an /// error — never a guess. X509Certificate2 from a PFX is the case that asked for it: its /// (string, string) constructor is one of several two-argument ones. /// public sealed class XmlBeanTypedArgumentsTests : IAsyncLifetime { private readonly RouteContext _context = new(); private readonly string _dir = Path.Combine(Path.GetTempPath(), "redb-xml-typed-" + Guid.NewGuid().ToString("N")); public XmlBeanTypedArgumentsTests() => Directory.CreateDirectory(_dir); public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { await _context.DisposeAsync(); Directory.Delete(_dir, recursive: true); GC.SuppressFinalize(this); } private static string T() => $"{typeof(TType).FullName}, {typeof(TType).Assembly.GetName().Name}"; private void Load(string beans) => _context.AddXmlContextFromContent($""" {beans} """); [Fact] public void Certificate_FromPfx_ThroughTheStringStringConstructor() { using var rsa = RSA.Create(2048); var request = new CertificateRequest("CN=redb-typed-args", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); using var issued = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddMinutes(-1), DateTimeOffset.UtcNow.AddDays(1)); var pfx = Path.Combine(_dir, "node.pfx"); File.WriteAllBytes(pfx, issued.Export(X509ContentType.Pkcs12, "secret")); _context.SetProperty("node.pfx", pfx); Load($""" """); using var loaded = _context.GetFromRegistry("node-cert")!; loaded.Subject.Should().Be("CN=redb-typed-args"); loaded.HasPrivateKey.Should().BeTrue(); } [Fact] public void FactoryMethod_WithOptionalTrailingParameters_IsCalledLikeCSharpCallsIt() { // The documented example: LoadPkcs12FromFile(path, password, flags = DefaultKeySet, limits = null). // Matching by the exact parameter count never found it; the optional rest takes its defaults, // and the ReadOnlySpan overload is no candidate — no markup value can be one. using var rsa = RSA.Create(2048); var request = new CertificateRequest("CN=redb-loader", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); using var issued = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddMinutes(-1), DateTimeOffset.UtcNow.AddDays(1)); var pfx = Path.Combine(_dir, "hub.pfx"); File.WriteAllBytes(pfx, issued.Export(X509ContentType.Pkcs12, "secret")); Load($""" """); using var loaded = _context.GetFromRegistry("hub-cert")!; loaded.Subject.Should().Be("CN=redb-loader"); } [Fact] public void TypedArguments_ChooseTheConstructor_AmongOnesTheValuesAllFit() { Load($""" """); _context.GetFromRegistry("as-string")!.Chosen.Should().Be("string:a.pfx/pw"); _context.GetFromRegistry("as-object")!.Chosen.Should().Be("object:a.pfx/opts"); } [Fact] public void UntypedArguments_ThatFitSeveralConstructors_AreAnError_NotAGuess() { var act = () => Load($""" """); act.Should().Throw(); } [Fact] public void FactoryMethod_Overloads_OfOneArity_AreRefused_UntilTypesNameOne() { var ambiguous = () => Load($""" """); ambiguous.Should().Throw() .WithMessage("*has 2 public static methods 'From' taking 1 argument(s)*name the parameter types with *"); Load($""" """); _context.GetFromRegistry("from")!.Chosen.Should().Be("string:slot-7/via-int", "the value is converted to the named parameter type"); } [Fact] public void ASignatureNoConstructorHas_AndTypesOnSomeArgumentsOnly_AreErrors() { var missing = () => Load($""" """); missing.Should().Throw().WithMessage("*has no public constructor (System.Int32, System.Int32)*"); var mixed = () => Load($""" """); mixed.Should().Throw().WithMessage("*name every parameter type, or none*"); } [Fact] public void Generator_PrintsTheTypes_AndTheRuntimeHalfUsesThem() { var code = XmlCodeGenerator.Generate(XDocument.Parse($""" """), "TypedGenerated", "Tests.Generated"); code.Should().Contain("argumentTypes: [\"System.String\", \"System.Object\"]"); var built = (ProbeCredential)XmlBeans.Create(_context, T(), ["a", "b"], [], argumentTypes: ["System.String", "System.Object"]); built.Chosen.Should().Be("object:a/b"); } [Fact] public void Gate_WithTheBuiltAssemblies_HoldsTheNamedSignature() { var project = RouteProjectScaffold.Create(_dir, "Typed"); File.WriteAllText(Path.Combine(project, "routes", "main.route.xml"), $""" """); var errors = RoutePackage.Check(project, "p", "1.0.0", Type.GetType).Errors.Select(e => e.Message).ToList(); errors.Should().Contain(m => m.Contains("bean 'none'") && m.Contains("has no public constructor (System.Int32, System.Int32)")); errors.Should().Contain(m => m.Contains("bean 'from'") && m.Contains("has 2 public static methods 'From'")); errors.Should().NotContain(m => m.Contains("bean 'ok'")); } [Fact] public void Untyped_text_argument_for_a_decimal_constructor_fails_the_load() { var act = () => Load($""""""); act.Should().Throw("ActivatorUtilities passes the text as a string, which no parameter takes"); } [Fact] public void Gate_WithTheBuiltAssemblies_HoldsUntypedArgumentsAgainstTheConstructors() { var project = RouteProjectScaffold.Create(_dir, "Untyped"); File.WriteAllText(Path.Combine(project, "routes", "main.route.xml"), $""" """); var errors = RoutePackage.Check(project, "p", "1.0.0", Type.GetType).Errors.Select(e => e.Message).ToList(); errors.Should().ContainSingle(m => m.Contains("bean 'untyped'")) .Which.Should().Contain("no public constructor").And.Contain("(System.String)") .And.Contain(" m.Contains("bean 'typed'") || m.Contains("bean 'strings'")); } } Path: redb-route/tests/redb.Route.Tests.Xml/XmlContainerAndLoadingTests.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.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/XmlContainerAndLoadingTests.cs ---- using System.Xml.Linq; using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Xml; namespace redb.Route.Tests.Xml; /// /// Container batch: handlers on <routes> for every route of the file, the /// extension channel exercised from outside the core, expression-escaping equivalence and /// the glob loading overload. /// public class XmlContainerAndLoadingTests : 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; } // ── container-level handlers ───────────────────────────────────────────── [Fact] public async Task ContainerOnException_AppliesToEveryRouteOfTheFile() { _context.AddXmlRoutesFromContent(""" """); await _context.Start(); var producerA = _context.GetEndpoint("direct://cont-a-in").CreateProducer(); var producerB = _context.GetEndpoint("direct://cont-b-in").CreateProducer(); await producerA.Start(); await producerB.Start(); var a = new Exchange(new Message("x")); await producerA.Process(a); var b = new Exchange(new Message("x")); await producerB.Process(b); a.In.Headers["rescued"].Should().Be("yes"); b.In.Headers["rescued"].Should().Be("yes"); } [Fact] public async Task ContainerIntercept_RunsForEveryRouteOfTheFile() { var seen = new List(); _context.AddRoutes(r => r.From("direct://cont-i-sink").Process(e => seen.Add(e.In.Headers["tapped"]))); _context.AddXmlRoutesFromContent(""" """); await _context.Start(); foreach (var uri in new[] { "direct://cont-i-1-in", "direct://cont-i-2-in" }) { var producer = _context.GetEndpoint(uri).CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("x"))); } seen.Should().Equal("yes", "yes"); } [Fact] public void SkipSendToOriginalEndpoint_OnAPlainIntercept_IsASchemaError() { // The attribute only means something on ; on the other // intercepts it is a misplaced intention, not something to apply silently. var act = () => _context.AddXmlRoutesFromContent(""" """); act.Should().Throw() .WithMessage("*skipSendToOriginalEndpoint*only*interceptSendToEndpoint*"); } // ── the extension channel from outside the core ────────────────────────── private sealed class StampContribution : IXmlElementContribution { public string Name => "stamp"; public XmlElementKind Kind => XmlElementKind.Step; // The spec is what admits the attribute past the generated schema: // an opaque contribution parses, but its attributes fail validation — by design. public ElementSpec Spec => ElementSpec.Leaf("stamp", new AttributeSpec("value", AttributeType.String)); public IRouteDefinition Apply(XElement element, IRouteDefinition current, XmlParseContext context) => current.SetHeader("stamped", context.Attr(element, "value") ?? "yes"); } private sealed class DuplicateToContribution : IXmlElementContribution { public string Name => "to"; public XmlElementKind Kind => XmlElementKind.Step; public IRouteDefinition Apply(XElement element, IRouteDefinition current, XmlParseContext context) => current; } [Fact] public async Task ExternalContribution_Registered_ParsesLikeACoreElement() { _context.AddXmlRoutesFromContent(""" """, options: new XmlRouteLoaderOptions { Extensions = [new StampContribution()] }); var producer = await StartAndProducer("direct://ext-in"); var exchange = new Exchange(new Message("x")); await producer.Process(exchange); exchange.In.Headers["stamped"].Should().Be("external"); } [Fact] public void ExternalContribution_NotRegistered_ItsElementIsRejected() { var act = () => _context.AddXmlRoutesFromContent(""" """); act.Should().Throw().WithMessage("*unknown element *"); } [Fact] public void DuplicateElementName_IsAHardRegistrationError() { var act = () => _context.AddXmlRoutesFromContent( """""", options: new XmlRouteLoaderOptions { Extensions = [new DuplicateToContribution()] }); act.Should().Throw().WithMessage("*'to' is already registered*"); } // ── expression escaping equivalence ────────────────────────────────────── [Fact] public async Task EscapedAndBareGreaterThan_AreTheSameExpression() { var passed = new List(); _context.AddRoutes(r => r.From("direct://esc-sink").Process(e => passed.Add((string)e.In.Body!))); _context.AddXmlRoutesFromContent(""" """); await _context.Start(); foreach (var (uri, tag) in new[] { ("direct://esc-bare-in", "bare"), ("direct://esc-escaped-in", "escaped") }) { var producer = _context.GetEndpoint(uri).CreateProducer(); await producer.Start(); var over = new Exchange(new Message(tag)); over.In.Headers["a"] = 20; await producer.Process(over); var under = new Exchange(new Message(tag + "-under")); under.In.Headers["a"] = 5; await producer.Process(under); } passed.Should().Equal("bare", "escaped"); } // ── glob loading ───────────────────────────────────────────────────────── [Fact] public async Task GlobPattern_LoadsEveryMatchingFile_Deterministically() { var dir = Path.Combine(Path.GetTempPath(), "redb-xml-glob-" + Guid.NewGuid().ToString("N")); Directory.CreateDirectory(dir); try { File.WriteAllText(Path.Combine(dir, "a.route.xml"), """ """); File.WriteAllText(Path.Combine(dir, "b.route.xml"), """ """); File.WriteAllText(Path.Combine(dir, "ignored.txt"), "not a route file"); _context.AddXmlRoutes(Path.Combine(dir, "*.route.xml")); await _context.Start(); _context.Routes.Select(r => r.RouteId).Should().Contain(["glob-a", "glob-b"]); } finally { Directory.Delete(dir, recursive: true); } } [Fact] public void GlobPattern_MatchingNothing_IsAnError_NamingTheSearchedPlaces() { var dir = Path.Combine(Path.GetTempPath(), "redb-xml-glob-empty-" + Guid.NewGuid().ToString("N")); Directory.CreateDirectory(dir); try { var act = () => _context.AddXmlRoutes(Path.Combine(dir, "*.route.xml")); act.Should().Throw() .WithMessage("*no route files match*Searched:*"); } finally { Directory.Delete(dir, recursive: true); } } // ── in / not in in markup conditions ───────────────────────────── [Fact] public async Task InAndNotIn_WorkInMarkupConditions_WithALiteralAndAMessageList() { _context.AddXmlRoutesFromContent(""" """); var producer = await StartAndProducer("direct://in-markup"); async Task Send(string region, string status) { var exchange = new Exchange(new Message("x")); exchange.In.Headers["region"] = region; exchange.In.Headers["status"] = status; exchange.Properties["closedStatuses"] = new[] { "closed", "void" }; await producer.Process(exchange); return exchange; } var eu = await Send("uk", "open"); var us = await Send("us", "closed"); eu.In.Headers["zone"].Should().Be("europe"); eu.In.Headers["open"].Should().Be("yes"); us.In.Headers["zone"].Should().Be("other"); us.In.Headers.ContainsKey("open").Should().BeFalse("closed is in the closed list"); } } Path: redb-route/tests/redb.Route.Tests.Xml/XmlContextLoaderTests.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.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/XmlContextLoaderTests.cs ---- using System.Xml.Linq; using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Xml; namespace redb.Route.Tests.Xml; /// A bean the onInit pipeline calls; counts the calls. public class InitProbe { public int Marked { get; private set; } public void Mark(IExchange exchange) => Marked++; } /// Options object built as a nested anonymous bean. public class ProbeOptions { public string? ConnectionString { get; set; } /// The creation path of a type that hides construction behind a static method. public static ProbeOptions FromDsn(string dsn) => new() { ConnectionString = dsn + "/via-factory" }; } /// A bean whose OPTIONS come through a property, not the constructor: the shape a /// connector factory has when it holds an object (a certificate, credentials, a serializer). public class ProbeHolder { public ProbeOptions? Options { get; set; } public string Describe(IExchange exchange) => $"holder:{Options?.ConnectionString}"; } /// A bean taking an options object through the constructor. public class ProbeFactory(ProbeOptions options) { public string Describe(IExchange exchange) => $"factory:{options.ConnectionString}"; } /// A minimal component for the <components> section test. public sealed class ProbeComponent : ComponentBase { public override string Scheme => "probe"; public override IEndpoint CreateEndpoint(EndpointUri uri) => throw new NotSupportedException("registration-only test component"); } /// /// Context batch: context.xml — the components section, context beans with /// nested constructor beans, the onInit pipeline in the fail-fast bootstrap phase, and the /// {{...}}-aware enabled= on routes. /// public class XmlContextLoaderTests : IAsyncLifetime { private readonly RouteContext _context = new(); public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { await _context.DisposeAsync(); GC.SuppressFinalize(this); } // ── onInit ─────────────────────────────────────────────────────────────── [Fact] public async Task OnInit_RunsOnce_BeforeTheRoutesStart() { var probe = new InitProbe(); _context.AddToRegistry("init-probe", probe); _context.AddXmlContextFromContent(""" """); probe.Marked.Should().Be(0, "the pipeline runs at Start(), not at load"); await _context.Start(); probe.Marked.Should().Be(1); } [Fact] public async Task OnInit_FailingStep_KeepsTheContextFromStarting() { _context.AddXmlContextFromContent(""" """, "broken-init.xml"); var act = () => _context.Start(); (await act.Should().ThrowAsync()) .WithInnerException() .WithMessage("* of 'broken-init.xml' failed*ddl failed*"); } // ── components and beans ───────────────────────────────────────────────── [Fact] public void ComponentsSection_RegistersTheScheme_ForRouteFilesToUse() { _context.AddXmlContextFromContent($$""" """); _context.GetComponentNames().Should().Contain("probe"); // The scheme check of a routes document now accepts it (endpoints stay lazy). var load = () => _context.AddXmlRoutesFromContent(""" """); load.Should().NotThrow(); } [Fact] public async Task ConstructorArg_NestedAnonymousBean_BuildsTheGraph() { _context.AddXmlContextFromContent($$""" """); _context.AddXmlRoutesFromContent(""" """); await _context.Start(); var producer = _context.GetEndpoint("direct://ctx-factory-in").CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("x")); await producer.Process(exchange); exchange.In.Body.Should().Be("factory:Host=demo"); } [Fact] public async Task Property_NestedAnonymousBean_IsAssignedAsTheObject() { // A property whose type is an OBJECT could not be set before: took a string only, // so a factory holding a certificate or a credentials object forced the C# spelling. _context.AddXmlContextFromContent($$""" """); _context.AddXmlRoutesFromContent(""" """); await _context.Start(); var producer = _context.GetEndpoint("direct://ctx-holder-in").CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("x")); await producer.Process(exchange); exchange.In.Body.Should().Be("holder:Host=demo"); } [Fact] public async Task Bean_FactoryMethod_CreatesThroughTheStaticMethod() { // Some types are created by a static method, not a public constructor (X509CertificateLoader // is the reason this exists). factoryMethod= names it; constructorArg values are its arguments. _context.AddXmlContextFromContent($$""" """); _context.AddXmlRoutesFromContent(""" """); await _context.Start(); var producer = _context.GetEndpoint("direct://ctx-static-in").CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("x")); await producer.Process(exchange); exchange.In.Body.Should().Be("factory:Host=demo/via-factory"); } [Fact] public void StructuredEndpoint_CarriesAnExplicitFalse_AndOmitsAnAbsentOption() { // transacted on a producer is tri-state now (119e76d7): absent waits for the enclosing // transaction, "false" sends at once. The structured form must keep the two apart: an // absent attribute stays absent in the URI, an explicit false reaches it verbatim. var document = XDocument.Parse(""" """); var code = XmlCodeGenerator.Generate(document, "TransactedGenerated", "Tests.Generated"); code.Should().Contain("\"kafka://orders?transacted=false\""); code.Should().Contain("\"kafka://audit\"", "an attribute that is not written is not an option"); } [Fact] public void Generator_PrintsTheObjectProperty_AndTheFactoryMethod() { // The C# spelling of the same two forms: a nested bean as the property value, and the // static creator as the last argument of XmlBeans.Create. var document = XDocument.Parse($$""" """); var code = XmlCodeGenerator.Generate(document, "BeanGenerated", "Tests.Generated"); code.Should().Contain("(\"Options\", XmlBeans.Create(") .And.Contain("\"FromDsn\")", "the factory method is the last argument"); } [Fact] public void Property_ValueAndNestedBean_Together_IsASchemaError() { var act = () => _context.AddXmlContextFromContent($$""" """); act.Should().Throw() .WithMessage("*takes exactly one of: value=, ref=, one nested anonymous , one *"); } [Fact] public void ConstructorArg_ValueAndNestedBean_Together_IsASchemaError() { var act = () => _context.AddXmlContextFromContent($$""" """); act.Should().Throw() .WithMessage("*takes exactly one of: value=, ref=, one nested anonymous , one *"); } [Fact] public void UnknownContextSection_And_SecondOnInit_AreCollectedTogether() { var act = () => _context.AddXmlContextFromContent(""" """, "bad-context.xml"); var errors = act.Should().Throw().Which.Errors; errors.Should().HaveCount(2); errors.Should().Contain(e => e.Contains("at most one ")); errors.Should().Contain(e => e.Contains("unknown section ")); } // ── {{...}}-aware enabled= ─────────────────────────────────────────────── [Fact] public async Task EnabledPlaceholder_ResolvesFromContextProperties_AndDefaults() { _context.SetProperty("features.on", "true"); _context.AddXmlRoutesFromContent(""" """); await _context.Start(); var ids = _context.Routes.Select(r => r.RouteId).ToList(); ids.Should().Contain("en-on").And.NotContain("en-default-off"); } [Fact] public void EnabledPlaceholder_WithoutValueOrDefault_IsAPositionedError() { var act = () => _context.AddXmlRoutesFromContent(""" """, "enabled.xml"); act.Should().Throw() .WithMessage("*enabled.xml(2,*Unresolved property placeholder*no.such.key*"); } [Fact] public void EnabledResolvingToNonBool_IsASchemaError() { _context.SetProperty("features.kind", "sometimes"); var act = () => _context.AddXmlRoutesFromContent(""" """); act.Should().Throw() .WithMessage("*resolved to 'sometimes', which is not a bool*"); } } Path: redb-route/tests/redb.Route.Tests.Xml/XmlHeaderFilterStrategyBeanTests.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.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/XmlHeaderFilterStrategyBeanTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Xml; namespace redb.Route.Tests.Xml; /// /// A header filter strategy declared in markup: is a plain bean whose name /// lists are filled from <list>, and an endpoint's headerFilterStrategy=#name finds it. /// public class XmlHeaderFilterStrategyBeanTests : IAsyncLifetime { private readonly RouteContext _context = new(); public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { await _context.DisposeAsync(); GC.SuppressFinalize(this); } private static string T() => $"{typeof(TType).FullName}, {typeof(TType).Assembly.GetName().Name}"; [Fact] public void AWhitelistDeclaredInMarkup_IsBuiltAndFoundByAnEndpoint() { _context.AddXmlContextFromContent($""" Correlation-IDtraceparent """); var strategy = _context.GetFromRegistry("correlationOnly")!; var exchange = new Exchange(new Message("body")); strategy.FilterOutgoing("Correlation-ID", "c-42", exchange).Should().BeFalse("a listed header goes out"); strategy.FilterOutgoing("correlation-id", "c-42", exchange).Should().BeFalse("names match case-insensitively"); strategy.FilterOutgoing("Authorization", "Bearer x", exchange).Should().BeTrue("anything else stays back"); var act = () => _context.GetEndpoint("vm://xml-strategy?headerFilterStrategy=#correlationOnly").CreateProducer(); act.Should().NotThrow("the endpoint resolves the bean declared in markup"); } [Fact] public void TheGenerator_CarriesTheBeanAndTheOptionIntoCSharp() { var document = System.Xml.Linq.XDocument.Parse($""" Correlation-ID """); var code = XmlCodeGenerator.Generate(document, "StrategyGenerated", "Tests.Generated"); code.Should().Contain($"XmlBeans.Create(Context!, \"{T()}\"") .And.Contain("(\"OutFilter\", XmlBeans.List(Context!, null, [\"Correlation-ID\"]))") .And.Contain("(\"FilterOnMatch\", \"false\")") .And.Contain("vm://out?headerFilterStrategy=#correlationOnly"); } } Path: redb-route/tests/redb.Route.Tests.Xml/XmlJsonGateTests.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.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/XmlJsonGateTests.cs ---- using AwesomeAssertions; using redb.Route.DataFormats.XmlJson; using redb.Route.Xml.Packaging; namespace redb.Route.Tests.Xml; /// /// The package gate on the xmljson format. Without --bin the gate's own checks run, recognising the format by its /// type name: the schema is a file the package ships, the arrays paths are well formed, a format with neither schema /// nor arrays is warned. With --bin the format's runs as well: the schema /// compiles with the format's reader, each arrays path leads through the schema's structure, xs:any and mixed content /// are flagged, and plural=true names the pairs it reads as lists. /// public sealed class XmlJsonGateTests : IDisposable { private const string Type = "redb.Route.DataFormats.XmlJson.XmlJsonDataFormat, redb.Route.DataFormats.XmlJson"; private readonly string _root = Path.Combine(Path.GetTempPath(), "redb-xml-xmljson-" + Guid.NewGuid().ToString("N")); public XmlJsonGateTests() => Directory.CreateDirectory(_root); public void Dispose() => Directory.Delete(_root, recursive: true); private const string OrderXsd = """ """; private PackageResult Check(string step, bool bin, params (string Path, string Content)[] resources) { var dir = RouteProjectScaffold.Create(_root, "XmlJson" + Guid.NewGuid().ToString("N")[..6]); foreach (var (path, content) in resources) { var full = Path.Combine(dir, RoutePackage.ResourcesDir, path); Directory.CreateDirectory(Path.GetDirectoryName(full)!); File.WriteAllText(full, content); } File.WriteAllText(Path.Combine(dir, "routes", "main.route.xml"), $""" {step} """); return RoutePackage.Check(dir, "p", "1.0.0", checks: bin ? [new XmlJsonPackageCheck()] : null); } // ── without --bin: the gate's own checks ──────────────────────── [Theory] [InlineData(false)] [InlineData(true)] public void AMissingSchema_IsOneError(bool bin) { Check($"""""", bin).Errors .Should().ContainSingle(e => e.Message.Contains("xmljson schema")) .Which.Message.Should().Be("xmljson schema 'schemas/none.xsd' is not under 'resources/'."); } [Theory] [InlineData("Item", "starts with '/' (from the root) or '//' (at any depth)")] [InlineData("/Order//Item", "has an empty or blank step; write it as /Order/Items/Item or //Item")] public void AMalformedArraysPath_IsAnError(string path, string problem) { Check($"""""", bin: false).Errors .Should().Contain(e => e.Message == $"xmljson arrays path '{path}' {problem}."); } [Fact] public void NeitherSchemaNorArrays_IsWarned() { Check($"""""", bin: false).Warnings .Should().Contain(w => w.Message.StartsWith("xmljson without schema= or arrays=", StringComparison.Ordinal)); Check($"""""", bin: false).Warnings .Should().NotContain(w => w.Message.StartsWith("xmljson without schema= or arrays=", StringComparison.Ordinal)); } [Fact] public void WithoutBin_TheSchemaIsNotCompiled() { var result = Check($"""""", bin: false, ("schemas/bad.xsd", """""")); result.Errors.Should().BeEmpty("compiling the schema is the format's own check, which needs --bin"); result.Warnings.Should().NotContain(w => w.Message.Contains("schema 'schemas/bad.xsd'")); } [Fact] public void TheContextLevelDataFormat_IsCheckedToo() { var dir = RouteProjectScaffold.Create(_root, "XmlJsonCtx"); File.WriteAllText(Path.Combine(dir, RoutePackage.ContextFile), $""" """); Directory.CreateDirectory(Path.Combine(dir, RoutePackage.ResourcesDir, "schemas")); File.WriteAllText(Path.Combine(dir, RoutePackage.ResourcesDir, "schemas", "order.xsd"), OrderXsd); RoutePackage.Check(dir, "p", "1.0.0", checks: [new XmlJsonPackageCheck()]).Warnings .Should().Contain(w => w.Message.Contains("'Itme' is not a child of 'Order'") && w.File.Contains("context.xml(")); } // ── with --bin: the format's own check ────────────────────────── [Theory] [InlineData("""""", "nothing")] [InlineData("""""", "not the network")] [InlineData("""""", "outside")] public void ASchemaThatDoesNotCompile_IsAnError(string xsd, string detail) { Check($"""""", bin: true, ("schemas/bad.xsd", xsd)).Errors .Should().Contain(e => e.Message.StartsWith("xmljson schema 'schemas/bad.xsd' does not compile: ", StringComparison.Ordinal) && e.Message.Contains(detail) && e.File.Contains("main.route.xml(")); } [Fact] public void ASchemaWithItsOwnDoctype_Compiles() { const string withDoctype = """ ]> """; Check($"""""", bin: true, ("schemas/d.xsd", withDoctype)).Errors.Should().BeEmpty(); } [Theory] [InlineData("/Order/Item")] [InlineData("//Item")] [InlineData("//Lines/Line")] [InlineData("/Order/Lines/Line")] [InlineData("/o:Order/o:Item")] [InlineData("/Order/Extra/Anything/Deeper")] public void APathThroughTheSchema_Passes(string path) { var result = Check($"""""", bin: true, ("schemas/order.xsd", OrderXsd)); result.Errors.Should().BeEmpty(); result.Warnings.Should().NotContain(w => w.Message.Contains("does not lead through")); } [Theory] [InlineData("/Order/Line", "'Line' is not a child of 'Order'")] [InlineData("/Item", "'Item' is not a global element of it")] [InlineData("//Itme", "'Itme' names no element of it")] [InlineData("//Item/Line", "'Line' is not a child of 'Item'")] public void APathTheSchemaHasNot_IsWarned_WithTheStepWhereItBreaks(string path, string problem) { Check($"""""", bin: true, ("schemas/order.xsd", OrderXsd)).Warnings .Should().Contain(w => w.Message == $"xmljson arrays path '{path}' does not lead through schema 'schemas/order.xsd': {problem}."); } [Fact] public void WildcardsAndMixedContent_AreFlagged() { var warnings = Check($"""""", bin: true, ("schemas/order.xsd", OrderXsd)).Warnings; warnings.Should().Contain(w => w.Message.Contains("has xs:any in 'Extra'")); warnings.Should().Contain(w => w.Message.Contains("has mixed content in 'Extra'")); } [Fact] public void ASchemaWithoutWildcards_IsNotFlagged_EvenWithAnUntypedElement() { // An element without a type is xs:anyType, a built-in with a wildcard; the author wrote no xs:any. const string xsd = """ """; var warnings = Check($"""""", bin: true, ("schemas/plain.xsd", xsd)).Warnings; warnings.Should().NotContain(w => w.Message.Contains("xs:any") || w.Message.Contains("mixed content")); } [Fact] public void PluralTrue_NamesThePairsItReadsAsLists() { const string xsd = """ """; Check($"""""", bin: true, ("schemas/r.xsd", xsd)).Warnings .Should().Contain(w => w.Message == "xmljson plural=true reads 2 parent/child pair(s) of schema 'schemas/r.xsd' as lists: 'Categories/Category', " + "'Incidents/Incident'; the schema allows one child only in 'Categories/Category'."); } [Fact] public void PluralTrue_WithNoPair_SaysTheRuleChangesNothing() { const string xsd = """ """; Check($"""""", bin: true, ("schemas/o.xsd", xsd)).Warnings .Should().Contain(w => w.Message.StartsWith("xmljson plural=true finds no parent named as the plural of its only child", StringComparison.Ordinal)); } [Fact] public void PluralOff_ListsNothing() { Check($"""""", bin: true, ("schemas/order.xsd", OrderXsd)).Warnings .Should().NotContain(w => w.Message.Contains("plural=true")); } [Fact] public void TheUblInvoiceSchema_PassesWithItsRealPaths_AndAWrongStepIsNamed() { var dir = RouteProjectScaffold.Create(_root, "Ubl"); var source = Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "..", "..", "..", "..", "redb.Route.Tests.DataFormats", "Fixtures", "xmljson", "ubl")); foreach (var file in Directory.GetFiles(source, "*.xsd", SearchOption.AllDirectories)) { var target = Path.Combine(dir, RoutePackage.ResourcesDir, "ubl", Path.GetRelativePath(source, file)); Directory.CreateDirectory(Path.GetDirectoryName(target)!); File.Copy(file, target); } File.WriteAllText(Path.Combine(dir, "routes", "main.route.xml"), $""" """); var result = RoutePackage.Check(dir, "p", "1.0.0", checks: [new XmlJsonPackageCheck()]); result.Errors.Should().BeEmpty(); result.Warnings.Where(w => w.Message.Contains("does not lead through")).Should().ContainSingle() .Which.Message.Should().EndWith(": 'cbc:Nope' is not a child of 'cac:InvoiceLine'."); } // ── the hook itself ───────────────────────────────────────────── private sealed class Throwing : IPackageCheck { public void Check(PackageCheckContext context) => throw new InvalidOperationException("boom"); } [Fact] public void ACheckThatThrows_IsAnErrorNamingIt_AndTheOthersStillRun() { var dir = RouteProjectScaffold.Create(_root, "Hook"); Directory.CreateDirectory(Path.Combine(dir, RoutePackage.ResourcesDir, "schemas")); File.WriteAllText(Path.Combine(dir, RoutePackage.ResourcesDir, "schemas", "order.xsd"), OrderXsd); File.WriteAllText(Path.Combine(dir, "routes", "main.route.xml"), $""" """); var result = RoutePackage.Check(dir, "p", "1.0.0", checks: [new Throwing(), new XmlJsonPackageCheck()]); result.Errors.Should().Contain(e => e.File.EndsWith("+Throwing", StringComparison.Ordinal) && e.Message == "the package check failed: InvalidOperationException: boom"); result.Warnings.Should().Contain(w => w.Message.Contains("'Line' is not a child of 'Order'")); } } Path: redb-route/tests/redb.Route.Tests.Xml/XmlJsonMarkupTests.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.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/XmlJsonMarkupTests.cs ---- using System.Text; using System.Text.Json.Nodes; using System.Xml.Linq; using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.DataFormats.XmlJson; using redb.Route.Xml; namespace redb.Route.Tests.Xml; /// /// The xmljson format in markup and in the DSL (step S7): the default instance under the name xmljson, a named /// instance with its options in context.xml, the per-step type= form, both directions, a schema path /// resolved through the context's resource resolver (the package root), and the content types it writes. /// public sealed class XmlJsonMarkupTests : IAsyncLifetime { private static readonly string FormatType = $"{typeof(XmlJsonDataFormat).FullName}, {typeof(XmlJsonDataFormat).Assembly.GetName().Name}"; private readonly string _package = Path.Combine(Path.GetTempPath(), "redb-xmljson-pkg-" + Guid.NewGuid().ToString("N")); private readonly RouteContext _context = new(); public Task InitializeAsync() { Directory.CreateDirectory(Path.Combine(_package, "schemas")); File.WriteAllText(Path.Combine(_package, "schemas", "order.xsd"), """ """); // The package root only the context's resolver knows, as a Tsak package has it. _context.AddService(typeof(IRouteResourceResolver), new RouteResourceResolver { ResourceRoot = _package }); return Task.CompletedTask; } public async Task DisposeAsync() { await _context.DisposeAsync(); Directory.Delete(_package, recursive: true); } private void LoadContext(string inner) => new XmlContextLoader(_context).Load(XDocument.Parse($""" {inner} """, LoadOptions.SetLineInfo), "context.xml"); private async Task Run(string step, object body) { IMessage? seen = null; _context.AddRoutes(r => r.From("direct://xj-out").Process(e => seen = e.In)); _context.AddXmlRoutesFromContent($""" {step} """); await _context.Start(); var producer = _context.GetEndpoint("direct://xj-in").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message(body))); return seen!; } private static string Text(object? body) => body is byte[] bytes ? Encoding.UTF8.GetString(bytes) : body?.ToString() ?? ""; [Fact] public async Task TheDefaultInstance_AnswersToXmljson() { _context.AddXmlJsonDataFormat(); var message = await Run("""""", "12"); Text(message.Body).Should().Be("""{"o":{"i":["1","2"]}}"""); message.ContentType.Should().Be("application/json"); } [Fact] public async Task ANamedInstanceInContextXml_ReadsItsSchemaFromThePackage() { LoadContext($""""""); var message = await Run("""""", "7a"); Text(message.Body).Should().Be("""{"Order":{"Id":7,"Tag":["a"]}}""", "the schema says Id is an int and Tag repeats"); } [Fact] public async Task ThePerStepForm_TakesItsOptions() { var message = await Run($"""""", """1t"""); Text(message.Body).Should().Be("""{"r":{"Items":{"Item":["1"]},"Tag":["t"]}}"""); } [Fact] public async Task Unmarshal_JsonToXml_WithRootAndPrefixes() { var message = await Run($"""""", """{"Id":"1","Tag":["a","b"]}"""); Text(message.Body).Should().Be("""1ab"""); message.ContentType.Should().Be("application/xml"); } [Fact] public async Task Unmarshal_XmlToTheJsonTree() { var message = await Run($"""""", "1"); message.Body.Should().BeAssignableTo().Which["o"]!["a"]!.GetValue().Should().Be("1"); } [Fact] public async Task TheDsl_BothDirections() { string? json = null, xml = null; _context.AddRoutes(r => r.From("direct://dsl").MarshalXmlJson(o => o.Arrays.Add("//i")) .Process(e => json = Text(e.In.Body)) .UnmarshalXmlJson() .Process(e => xml = Text(e.In.Body))); await _context.Start(); var producer = _context.GetEndpoint("direct://dsl").CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("1"))); json.Should().Be("""{"o":{"i":["1"]}}"""); xml.Should().Be("""1"""); } [Fact] public void AMalformedPrefixesOption_IsAnErrorOfTheDocument() { var act = () => LoadContext($""""""); act.Should().Throw().Where(e => e.ToString().Contains("is not prefix=uri")); } [Fact] public void TheSerializerOptions_RoundTripTheirStringForms() { var format = new XmlJsonDataFormat { Arrays = " //Item , /Order/Tag ", Prefixes = "o=urn:orders, x = urn:x" }; format.Options.Arrays.Should().Equal("//Item", "/Order/Tag"); format.Options.Prefixes.Should().BeEquivalentTo(new Dictionary { ["o"] = "urn:orders", ["x"] = "urn:x" }); format.Arrays.Should().Be("//Item,/Order/Tag"); } } Path: redb-route/tests/redb.Route.Tests.Xml/XmlPackageContributionsTests.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.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/XmlPackageContributionsTests.cs ---- using System.Xml.Linq; using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Cache; using redb.Route.Core; using redb.Route.JsonTransform; using redb.Route.Templates; using redb.Route.Xml; namespace redb.Route.Tests.Xml; /// /// The first REAL package contributions through the extension channel — `redb.Route.Cache`, /// `redb.Route.JsonTransform`, `redb.Route.Templates` each ship their element (parse + schema /// shape + C# printing in one class) and a host registers them via /// . This closes the last "package elements" rows /// of the element table reachable before Tsak (`<rest>` waits for the Http package to be /// free, `redb.Route.Core` waits for the owner). /// public class XmlPackageContributionsTests : IAsyncLifetime { private static readonly XmlRouteLoaderOptions Options = new() { Extensions = [new CacheXmlContribution(), new JsonTransformXmlContribution(), new PayloadXmlContribution()], }; 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; } [Fact] public async Task Cache_Element_CachesTheScopeResult() { _context.UseCache(); var inner = 0; _context.AddRoutes(r => r.From("direct://cache-inner").Process(e => { inner++; e.In.Body = $"computed-{e.In.Headers["k"]}"; })); _context.AddXmlRoutesFromContent(""" """, options: Options); var producer = await StartAndProducer("direct://pkg-cache-in"); var first = Msg("a"); await producer.Process(first); var second = Msg("a"); await producer.Process(second); var other = Msg("b"); await producer.Process(other); inner.Should().Be(2, "the second send with the same key is a cache hit"); second.In.Body.Should().Be("computed-a"); other.In.Body.Should().Be("computed-b"); } [Fact] public async Task TransformJson_Element_RunsInlineJsonata() { _context.UseJsonTransform(); _context.AddXmlRoutesFromContent(""" """, options: Options); var producer = await StartAndProducer("direct://pkg-json-in"); var exchange = new Exchange(new Message("""{"name":"bob"}""")); await producer.Process(exchange); exchange.In.Body.Should().BeOfType().Which.Should().Contain("\"who\"").And.Contain("BOB"); } [Fact] public async Task Payload_Element_RendersTheTemplate_WithArgs() { _context.UseTemplates(); _context.AddXmlRoutesFromContent(""" """, options: Options); var producer = await StartAndProducer("direct://pkg-payload-in"); var exchange = Msg("x", ("user", "rinat")); await producer.Process(exchange); exchange.In.Headers["greeting"].Should().Be("hello rinat"); } // A constant key is one entry for every message; a key over header.k is one entry per value of k. [Theory] [InlineData("orders-all", 1)] [InlineData("header.k", 2)] [InlineData("${header.k}-x", 2)] public async Task CacheKey_InMarkup_FollowsTheKeyRule(string key, int misses) { _context.UseCache(); var keys = new List(); _context.AddRoutes(r => r.From("direct://cache-key-inner").Process(e => keys.Add("miss"))); _context.AddXmlRoutesFromContent($""" """, options: Options); var producer = await StartAndProducer("direct://pkg-cache-key-in"); await producer.Process(Msg("a")); await producer.Process(Msg("b")); await producer.Process(Msg("a")); keys.Should().HaveCount(misses); } [Fact] public void CacheKey_BrokenArithmeticOverARoot_FailsTheLoad() { var act = () => _context.AddXmlRoutesFromContent(""" """, options: Options); act.Should().Throw().Where(e => e.ToString().Contains("is not a value")); } [Fact] public void PackageElements_ValidateAgainstTheSchema_ThroughTheirSpecs() { // The schema pass is ON: these load only because each contribution declares its shape. var act = () => _context.AddXmlRoutesFromContent(""" """, options: Options); act.Should().Throw().WithMessage("*[schema]*provder*", "a typo in a package element's attribute is caught by the generated schema"); } [Fact] public void PackageElements_PrintThroughTheGenerator() { var code = XmlCodeGenerator.Generate(XDocument.Parse(""" """, LoadOptions.SetLineInfo), "PkgRoutes", "Demo", options: Options); code.Should().Contain(".Cache(\"${header.k}\", TimeSpan.FromSeconds(60));") .And.Contain("Distributed()") .And.Contain("TransformJson(\"specs/normalize.jsonata\")") .And.Contain("SetBodyTemplate(TextSource.Inline("); } // ── : the container-level contribution of the Http package ───────── private static readonly XmlRouteLoaderOptions RestOptions = new() { Extensions = [new Route.Http.Rest.RestXmlContribution()], }; [Fact] public void Rest_SpawnsTheHttpRoutes_ForToAndInlineVerbs() { _context.AddComponent(new KafkaStubComponent()); // registers "kafka" for the to= check _context.AddXmlRoutesFromContent(""" """, options: RestOptions); var ids = Examples.ExampleHarness.Definitions(_context) .OfType().Select(r => r.GetRouteId()).ToList(); ids.Should().Contain("orders-get", "id= names the verb's route"); ids.Should().Contain(id => id != null && id.StartsWith("rest-POST-api-orders-") && !id.EndsWith("-handler"), "the inline verb spawns its consumer route"); ids.Should().Contain(id => id != null && id.StartsWith("rest-POST-api-orders-") && id.EndsWith("-handler"), "inline steps live in their own handler route"); } [Fact] public void Rest_VerbWithBothToAndSteps_IsASchemaError() { var act = () => _context.AddXmlRoutesFromContent(""" """, options: RestOptions); act.Should().Throw() .WithMessage("*to= or with inline steps*not both*"); } [Fact] public void Rest_InsideARoute_IsRefusedWithAClearMessage() { var act = () => _context.AddXmlRoutesFromContent(""" """, options: RestOptions); act.Should().Throw() .WithMessage("*container-level element*beside *"); } [Fact] public void Rest_PrintsThroughTheGenerator() { var code = XmlCodeGenerator.Generate(XDocument.Parse(""" """, LoadOptions.SetLineInfo), "RestRoutes", "Demo", options: RestOptions); code.Should().Contain("Rest(\"/api\", options => { options.Port = 5099; })") .And.Contain(".Get(\"/{id}\").To(\"direct://x\");") .And.Contain(".Post(\"\").Route()"); } 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 static IExchange Msg(string key) { var exchange = new Exchange(new Message("payload")); exchange.In.Headers["k"] = key; return exchange; } } Path: redb-route/tests/redb.Route.Tests.Xml/XmlRouteLoaderTests.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.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/XmlRouteLoaderTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Xml; namespace redb.Route.Tests.Xml; /// A public bean target for the <bean> + bean: tests. public class XmlGreeter { public string Prefix { get; set; } = "hi"; public string Greet(IExchange exchange) => $"{Prefix}:{exchange.In.Body}"; } /// /// First vertical slice: an XML document becomes a working route through the /// existing DSL — with every error of a document collected in one pass, positions included, /// and the load-time checks the format promises (consumer ${...}, unregistered schemes). /// public class XmlRouteLoaderTests : 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; } // ── The happy path ─────────────────────────────────────────────────────── [Fact] public async Task SimpleRoute_LoadsAndRuns_ThroughTheExistingDsl() { object? delivered = null; _context.AddRoutes(r => r.From("direct://xml-out").Process(e => delivered = e.In.Body)); _context.AddXmlRoutesFromContent(""" """); var producer = await StartAndProducer("direct://xml-in"); await producer.Process(new Exchange(new Message("payload"))); delivered.Should().Be("loaded:payload"); } [Fact] public async Task Placeholders_InStepValues_ResolveAtLoad_LikeInAUri() { IExchange? delivered = null; _context.SetProperty("demo.key", "from-config"); _context.AddRoutes(r => r.From("direct://xml-ph-out").Process(e => delivered = e)); _context.AddXmlRoutesFromContent(""" """); var producer = await StartAndProducer("direct://xml-ph-in"); await producer.Process(new Exchange(new Message("payload"))); delivered!.In.Headers["configured"].Should().Be("from-config"); delivered.In.Headers["defaulted"].Should().Be("fallback"); delivered.Properties["mixed"].Should().Be("user=from-config"); delivered.In.Body.Should().Be("from-config"); } [Fact] public async Task Placeholder_WithoutValueOrDefault_FailsTheExchange_InTheWordsOfAUri() { _context.AddXmlRoutesFromContent(""" """); var producer = await StartAndProducer("direct://xml-ph-missing"); var exchange = new Exchange(new Message("payload")); Exception? failure = null; try { await producer.Process(exchange); } catch (Exception ex) { failure = ex; } (failure ?? exchange.Exception).Should().NotBeNull() .And.Subject.As().Message.Should().Contain("'demo.missing'").And.Contain("no default"); } [Fact] public async Task TokenizeJsonArray_SplitsTheArrayAJpathSetBodyLeft() { var parts = new List(); _context.AddRoutes(r => r.From("direct://xml-line").Process(e => { lock (parts) parts.Add((string)e.In.Body!); })); _context.AddXmlRoutesFromContent(""" """); var producer = await StartAndProducer("direct://xml-order"); await producer.Process(new Exchange(new Message( """{"id":"o-1","lines":[{"sku":"A-1","qty":1},{"sku":"B-2","qty":2}]}"""))); parts.Should().Equal("""{"sku":"A-1","qty":1}""", """{"sku":"B-2","qty":2}"""); } [Fact] public async Task ChoiceAndFilter_BranchAndGuard() { var seen = new List(); _context.AddRoutes(r => { r.From("direct://xml-vip").Process(_ => seen.Add("vip")); r.From("direct://xml-std").Process(_ => seen.Add("std")); }); _context.AddXmlRoutesFromContent(""" """); var producer = await StartAndProducer("direct://xml-router"); await producer.Process(Msg(("amount", 5000))); await producer.Process(Msg(("amount", 10))); await producer.Process(Msg(("amount", -1))); // filtered out seen.Should().Equal("vip", "std"); } [Fact] public async Task BeanSection_DeclaresTheObject_AndBeanUriCallsIt() { _context.AddXmlRoutesFromContent($$""" """); var producer = await StartAndProducer("direct://xml-bean-in"); var exchange = new Exchange(new Message("bob")); await producer.Process(exchange); exchange.In.Body.Should().Be("xml:bob"); } [Fact] public async Task RouteAttributes_IdAndMessageHistoryAndStepIdentity_FlowThrough() { _context.AddXmlRoutesFromContent(""" """); var producer = await StartAndProducer("direct://xml-hist-in"); var exchange = new Exchange(new Message("x")); await producer.Process(exchange); var entry = MessageHistory.GetEntries(exchange).Should().ContainSingle().Subject; entry.RouteId.Should().Be("xml-history"); entry.NodeId.Should().Be("mark-step"); entry.Label.Should().Be("Mark the exchange"); } [Fact] public async Task EnabledFalse_DoesNotRegisterTheRoute() { _context.AddXmlRoutesFromContent(""" """); await _context.Start(); _context.Routes.Select(r => r.RouteId).Should().Contain("xml-enabled").And.NotContain("xml-disabled"); } // ── Errors: one pass, positions, refusal ───────────────────────────────── [Fact] public void UnknownElement_ReportsPositionAndDidYouMean() { var act = () => _context.AddXmlRoutesFromContent(""" """, "routes/bad.route.xml"); act.Should().Throw() .WithMessage("*routes/bad.route.xml(4,*setHeaderr*Did you mean ?*"); } [Fact] public void AllErrorsOfTheDocument_AreCollectedInOnePass() { var act = () => _context.AddXmlRoutesFromContent(""" """); var errors = act.Should().Throw().Which.Errors; errors.Should().HaveCount(3); errors.Should().Contain(e => e.Contains("'value' or 'expr', not both")); errors.Should().Contain(e => e.Contains("unknown element ")); errors.Should().Contain(e => e.Contains("scheme 'unregistered-scheme' is not registered")); } [Fact] public void ConsumerUriWithPlaceholder_IsRefusedAtLoad() { var act = () => _context.AddXmlRoutesFromContent(""" """); act.Should().Throw() .WithMessage("*consumer URI cannot carry ${*only constants and {{key}}*"); } [Fact] public void MalformedExpression_FailsAtLoad_WithThePosition() { var act = () => _context.AddXmlRoutesFromContent(""" """, "bad-expr.xml"); act.Should().Throw() .WithMessage("*bad-expr.xml(4,*"); } [Fact] public void ForeignNamespaceElement_IsRejected_NotSilentlyParsedByLocalName() { // The XSD/namespace discipline: an element from another namespace must never pass as a // core element just because the local names match. var act = () => _context.AddXmlRoutesFromContent(""" """, "alien.xml"); act.Should().Throw() .WithMessage("*alien.xml(4,**namespace 'urn:someone:else'*urn:redb:route:1.0*"); } [Fact] public void EmptyNamespaceSubtree_IsRejectedToo() { var act = () => _context.AddXmlRoutesFromContent(""" """); act.Should().Throw() .WithMessage("**namespace ''*"); } [Fact] public void WrongRootNamespace_GetsAClearError() { var act = () => _context.AddXmlRoutesFromContent( """"""); act.Should().Throw() .WithMessage("*unexpected root namespace*urn:redb:route:1.0*"); } [Fact] public void ErroredDocument_RegistersNothing() { var act = () => _context.AddXmlRoutesFromContent(""" """); act.Should().Throw(); _context.Start().GetAwaiter().GetResult(); _context.Routes.Select(r => r.RouteId).Should().NotContain("half-good", "a document with errors registers none of its routes"); } private static IExchange Msg(params (string Name, object? Value)[] headers) { var exchange = new Exchange(new Message("x")); foreach (var (name, value) in headers) exchange.In.Headers[name] = value; return exchange; } } Path: redb-route/tests/redb.Route.Tests.Xml/XmlRouteSchemaTests.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.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/XmlRouteSchemaTests.cs ---- using System.Xml.Linq; using AwesomeAssertions; using redb.Route.Xml; using redb.Route.Xml.CoreElements; namespace redb.Route.Tests.Xml; /// /// The XSD is generated from the element registry, so the parser, the schema /// and the catalog read one list and cannot drift apart — pinned by tests, not by discipline. /// public class XmlRouteSchemaTests { private static readonly ElementRegistry Registry = ElementRegistry.CreateDefault(); private static IReadOnlyList<(int Line, int Column, string Message)> Validate(string xml) => XmlRouteSchema.Validate(XDocument.Parse(xml, LoadOptions.SetLineInfo), Registry); // ── the catalog-aware schema ───────────────────────────────────────────── /// /// The shipped catalog XSD must COMPILE, or the editor binds a schema it cannot use. A /// component whose path synonym is also one of its options (seda's queue, amqp's path) /// declared that attribute twice — «the attribute 'queue' already exists», twelve times /// over the real catalog (found before 4.1.0, 2026-09-20). /// [Fact] public void CatalogSchema_WithAPathSynonymThatIsAlsoAnOption_Compiles() { var component = new CatalogComponent( "seda", [], "redb.Route", "redb.Route.Components.SedaEndpointOptions", "queue", false, [ new CatalogOption("Queue", "string", null, false, null, Role: null, ConnectionParameter: false, ConnectionFactoryReference: false), new CatalogOption("Size", "int", "1000", false, null, Role: null, ConnectionParameter: false, ConnectionFactoryReference: false), ], Lenient: false); var schema = XmlRouteSchema.Generate(Registry, [component]).ToString(); var errors = new List(); var set = new System.Xml.Schema.XmlSchemaSet(); set.ValidationEventHandler += (_, e) => errors.Add(e.Message); set.Add("urn:redb:route:1.0", System.Xml.XmlReader.Create(new StringReader(schema))); set.Compile(); errors.Should().BeEmpty("a generated schema that does not compile is no schema at all"); } // ── the one-list guarantee ─────────────────────────────────────────────── [Fact] public void AttributeType_KeepsItsNumericValues_AcrossReleases() { // Package contributions (Cache, Http, redb.Route.Core, ...) are compiled against this enum // and store the NUMBERS. Inserting a member in the middle shifts them: a released package's // Bool would read as whatever took its slot. New members go to the end, never between. ((int)AttributeType.String).Should().Be(0); ((int)AttributeType.Expression).Should().Be(1); ((int)AttributeType.Uri).Should().Be(2); ((int)AttributeType.Reference).Should().Be(3); ((int)AttributeType.TypeName).Should().Be(4); ((int)AttributeType.Bool).Should().Be(5); ((int)AttributeType.Int).Should().Be(6); ((int)AttributeType.Long).Should().Be(7); ((int)AttributeType.Double).Should().Be(8); ((int)AttributeType.Duration).Should().Be(9); ((int)AttributeType.Enum).Should().Be(10); ((int)AttributeType.TypeNameList).Should().Be(11); } [Fact] public void EveryCoreContribution_HasAPinnedSpec_WithMatchingNameAndKind() { foreach (var contribution in CoreContributions.All) { CoreContributions.Specs.Should().ContainKey(contribution.Name, $"the core element <{contribution.Name}> must declare its shape for the schema and the catalog"); var spec = contribution.Spec; spec.Name.Should().Be(contribution.Name); spec.Kind.Should().Be(contribution.Kind, $"<{contribution.Name}>: the registered kind and the spec kind must agree"); } } [Fact] public void EverySpecEntry_BelongsToARegisteredContribution() { var registered = CoreContributions.All.Select(c => c.Name).ToHashSet(StringComparer.Ordinal); CoreContributions.Specs.Keys.Should().OnlyContain(name => registered.Contains(name), "a spec without a contribution is dead weight the schema would advertise falsely"); } [Fact] public void TheSchema_Compiles_AndGenerationIsDeterministic() { XmlRouteSchema.For(Registry).Should().NotBeNull(); XmlRouteSchema.Generate(Registry).ToString() .Should().Be(XmlRouteSchema.Generate(Registry).ToString()); } [Fact] public void EnumOption_LongerThanThreeMembers_LosesTheCaseInsensitiveUnion() { // The union spells every member out as character classes, so a long enum costs thousands of // characters: at the catalog's five hundred enum sites the schema grew to 21k lines, and the // editor's language server died with an out-of-memory error on the first completion // (2026-10-08). Short lists keep the union, long ones go back to the plain member list. var component = new CatalogComponent( "seda", [], "redb.Route", "redb.Route.Components.SedaEndpointOptions", "queue", false, [ new CatalogOption("AckMode", "enum", "Manual", false, ["Manual", "Auto"], Role: null, ConnectionParameter: false, ConnectionFactoryReference: false), new CatalogOption("FileExist", "enum", "Override", false, ["Override", "Append", "Fail", "Ignore", "Move", "TryRename"], Role: null, ConnectionParameter: false, ConnectionFactoryReference: false), ], Lenient: false); var schema = XDocument.Parse(XmlRouteSchema.Generate(Registry, [component]).ToString()); var xs = schema.Root!.Name.Namespace; XElement Option(string name) => schema.Descendants(xs + "attribute") .First(a => (string?)a.Attribute("name") == name); Option("ackMode").Descendants(xs + "union").Should().HaveCount(1, "a two-member enum still gets the case-insensitive union"); Option("fileExist").Descendants(xs + "union").Should().BeEmpty(); Option("fileExist").Descendants(xs + "enumeration").Select(e => (string?)e.Attribute("value")) .Should().Equal("Override", "Append", "Fail", "Ignore", "Move", "TryRename"); } // ── validation behavior the phase promises ─────────────────────────────── [Fact] public void EveryShippedExample_IsSchemaValid() { foreach (var file in Directory.GetFiles(Examples.ExampleHarness.Dir, "*.route.xml")) { var problems = XmlRouteSchema.Validate( XDocument.Load(file, LoadOptions.SetLineInfo), Registry); problems.Should().BeEmpty($"{Path.GetFileName(file)} must validate against the generated schema"); } } [Fact] public void UnknownElement_FailsValidation() { var problems = Validate(""" """); problems.Should().NotBeEmpty(); problems.Should().Contain(p => p.Message.Contains("nosuch")); } [Fact] public void ForeignNamespaceAttribute_IsAccepted() { var problems = Validate(""" """); problems.Should().BeEmpty("a foreign-namespace attribute is tolerated (anyAttribute ##other lax)"); } [Fact] public void EnumAttribute_OffersAndEnforcesItsValues() { var problems = Validate(""" text """); problems.Should().Contain(p => p.Message.Contains("Loud"), "a log level outside the enumeration must fail, which is what powers editor value hints"); } [Fact] public void RequiredAttribute_IsEnforced() { var problems = Validate(""" """); problems.Should().Contain(p => p.Message.Contains("type")); } [Fact] public void StructuredEndpointChild_IsOpenContent_UntilTheCatalogArrives() { var problems = Validate(""" """); problems.Should().BeEmpty("a scheme element inside an address step is lax content in the base schema"); } [Fact] public void ExternalContribution_AppearsInTheSchema_Automatically() { var registry = ElementRegistry.CreateDefault([new StampSpecContribution()]); var problems = XmlRouteSchema.Validate(XDocument.Parse(""" """, LoadOptions.SetLineInfo), registry); problems.Should().BeEmpty("a registered package element validates like a core one"); XmlRouteSchema.Validate(XDocument.Parse(""" """, LoadOptions.SetLineInfo), Registry) .Should().NotBeEmpty("without the package, its element is rejected by the schema too"); } // ── the §3.4 load-time pass: schema findings join the parse, deduped ───── [Fact] public void AttributeTypo_IsCaughtAtLoad_ByTheSchemaPass() { using var context = new Route.Core.RouteContext(); var act = () => context.AddXmlRoutesFromContent(""" """, "typo.xml"); act.Should().Throw() .WithMessage("*typo.xml(4,*[schema]*bogus*", "an unqualified attribute typo is exactly what the parser leaves to the schema"); } [Fact] public void ParserAndSchema_DoNotDoubleReportTheSameLine() { using var context = new Route.Core.RouteContext(); var act = () => context.AddXmlRoutesFromContent(""" """); var errors = act.Should().Throw().Which.Errors; errors.Should().ContainSingle("the parser's did-you-mean wins the line; the schema stays quiet on it") .Which.Should().Contain("Did you mean ?").And.NotContain("[schema]"); } [Fact] public async Task TheSwitch_TurnsTheSchemaPassOff() { await using var context = new Route.Core.RouteContext(); var act = () => context.AddXmlRoutesFromContent(""" """, options: new XmlRouteLoaderOptions { ValidateAgainstSchema = false }); act.Should().NotThrow("a document carrying a newer schema's extensions may opt out"); } // ── the §3.2 version policy on the namespace ───────────────────────────── [Fact] public void NewerMinorVersion_SaysWhatToUpdate() { using var context = new Route.Core.RouteContext(); var act = () => context.AddXmlRoutesFromContent( """"""); act.Should().Throw() .WithMessage("*needs format 1.5*supports up to 1.0*update the redb.Route.Xml package*"); } [Fact] public void DifferentMajorVersion_IsADifferentFormat() { using var context = new Route.Core.RouteContext(); var act = () => context.AddXmlRoutesFromContent( """"""); act.Should().Throw() .WithMessage("*format 2.0*major version 1*different format*"); } private sealed class StampSpecContribution : IXmlElementContribution { public string Name => "stamp"; public XmlElementKind Kind => XmlElementKind.Step; public ElementSpec Spec => ElementSpec.Leaf("stamp", new AttributeSpec("value", AttributeType.String)); public Abstractions.IRouteDefinition Apply( XElement element, Abstractions.IRouteDefinition current, XmlParseContext context) => current.SetHeader("stamped", context.Attr(element, "value") ?? "yes"); } } Path: redb-route/tests/redb.Route.Tests.Xml/XsdPackageGateTests.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.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/XsdPackageGateTests.cs ---- using AwesomeAssertions; using redb.Route.Xml.Packaging; namespace redb.Route.Tests.Xml; /// /// Row 37 step f: check and pack compile the schema of <validateXsd file="…"/> as the route does when it /// starts, so an import that is missing, outside schemaRoot or on the network fails at the gate, not on the /// worker; a schemaRoot leading out of resources/ is an error, since pack ships only that tree. /// public sealed class XsdPackageGateTests : IDisposable { private const string Common = """ """; private static string Order(string importLocation) => $""" """; private readonly string _root = Path.Combine(Path.GetTempPath(), "redb-xml-xsdgate-" + Guid.NewGuid().ToString("N")); public XsdPackageGateTests() => Directory.CreateDirectory(_root); public void Dispose() => Directory.Delete(_root, recursive: true); private PackageResult Check(string step, params (string Path, string Content)[] files) { var dir = RouteProjectScaffold.Create(_root, "Xsd" + Guid.NewGuid().ToString("N")[..6]); foreach (var (path, content) in files) { var full = Path.Combine(dir, path); Directory.CreateDirectory(Path.GetDirectoryName(full)!); File.WriteAllText(full, content); } File.WriteAllText(Path.Combine(dir, "routes", "main.route.xml"), $""" {step} """); return RoutePackage.Check(dir, "p", "1.0.0"); } private static IEnumerable XsdErrors(PackageResult result) => result.Errors.Where(e => e.Message.StartsWith("validateXsd ", StringComparison.Ordinal)).Select(e => e.Message); [Fact] public void ASchemaWithItsImportsUnderResources_Passes() { var result = Check("""""", ("resources/schemas/order/order.xsd", Order("../common/common.xsd")), ("resources/schemas/common/common.xsd", Common)); XsdErrors(result).Should().BeEmpty(); } [Fact] public void AnImportOutsideSchemaRoot_FailsTheGate() { var result = Check("""""", ("resources/schemas/order/order.xsd", Order("../common/common.xsd")), ("resources/schemas/common/common.xsd", Common)); result.Errors.Should().ContainSingle(e => e.Message.StartsWith("validateXsd schema 'schemas/order/order.xsd' does not compile: validateXsd: the schema refers to ", StringComparison.Ordinal) && e.Message.EndsWith("imports and includes stay inside the package.", StringComparison.Ordinal) && e.File.Contains("main.route.xml(")); } [Fact] public void AMissingImport_FailsTheGate() { var result = Check("""""", ("resources/order.xsd", Order("common.xsd"))); XsdErrors(result).Should().ContainSingle().Which.Should().StartWith("validateXsd schema 'order.xsd' does not compile: validateXsd: schema '"); } [Fact] public void ANetworkImport_FailsTheGate() { var result = Check("""""", ("resources/order.xsd", Order("http://127.0.0.1:9/common.xsd"))); XsdErrors(result).Should().ContainSingle().Which.Should().Contain("not the network"); } [Fact] public void ASchemaRootOutOfResources_IsAnError() { var result = Check("""""", ("resources/order.xsd", Order("common.xsd")), ("resources/common.xsd", Common)); XsdErrors(result).Should().ContainSingle().Which.Should().Be( "validateXsd schemaRoot='..' of schema 'order.xsd' leads outside 'resources/': pack ships only 'resources/', so the imports there would not reach the worker. Keep the schema and its imports under 'resources/'."); } [Fact] public void ASchemaThatDoesNotCompile_FailsTheGate() { var result = Check("""""", ("resources/bad.xsd", """""")); XsdErrors(result).Should().ContainSingle().Which.Should().StartWith("validateXsd schema 'bad.xsd' does not compile: "); } [Theory] [InlineData("""""")] [InlineData("""""")] public void AValueKnownOnlyFromConfiguration_IsLeftAlone(string step) { var result = Check(step, ("resources/order.xsd", Order("common.xsd"))); XsdErrors(result).Should().BeEmpty(); } [Fact] public void InlineContent_IsNotCompiledByTheGate() { var result = Check("""]]>"""); XsdErrors(result).Should().BeEmpty(); } } Path: redb-route/tests/redb.Route.Tests.Xml/redb.Route.Tests.Xml.csproj Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.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/redb.Route.Tests.Xml.csproj ----