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("""