Path: redb-route/tests/redb.Route.Tests.Xml/XmlRouteLoaderTests.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Xml/XmlRouteLoaderTests.cs
----
using AwesomeAssertions;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Xml;
namespace redb.Route.Tests.Xml;
/// A public bean target for the <bean> + bean: tests.
public class XmlGreeter
{
public string Prefix { get; set; } = "hi";
public string Greet(IExchange exchange) => $"{Prefix}:{exchange.In.Body}";
}
///
/// First vertical slice: an XML document becomes a working route through the
/// existing DSL — with every error of a document collected in one pass, positions included,
/// and the load-time checks the format promises (consumer ${...}, unregistered schemes).
///
public class XmlRouteLoaderTests : IAsyncLifetime
{
private readonly RouteContext _context = new();
public Task InitializeAsync() => Task.CompletedTask;
public async Task DisposeAsync()
{
await _context.DisposeAsync();
GC.SuppressFinalize(this);
}
private async Task StartAndProducer(string fromUri)
{
await _context.Start();
var producer = _context.GetEndpoint(fromUri).CreateProducer();
await producer.Start();
return producer;
}
// ── The happy path ───────────────────────────────────────────────────────
[Fact]
public async Task SimpleRoute_LoadsAndRuns_ThroughTheExistingDsl()
{
object? delivered = null;
_context.AddRoutes(r => r.From("direct://xml-out").Process(e => delivered = e.In.Body));
_context.AddXmlRoutesFromContent("""
""");
var producer = await StartAndProducer("direct://xml-in");
await producer.Process(new Exchange(new Message("payload")));
delivered.Should().Be("loaded:payload");
}
[Fact]
public async Task Placeholders_InStepValues_ResolveAtLoad_LikeInAUri()
{
IExchange? delivered = null;
_context.SetProperty("demo.key", "from-config");
_context.AddRoutes(r => r.From("direct://xml-ph-out").Process(e => delivered = e));
_context.AddXmlRoutesFromContent("""
""");
var producer = await StartAndProducer("direct://xml-ph-in");
await producer.Process(new Exchange(new Message("payload")));
delivered!.In.Headers["configured"].Should().Be("from-config");
delivered.In.Headers["defaulted"].Should().Be("fallback");
delivered.Properties["mixed"].Should().Be("user=from-config");
delivered.In.Body.Should().Be("from-config");
}
[Fact]
public async Task Placeholder_WithoutValueOrDefault_FailsTheExchange_InTheWordsOfAUri()
{
_context.AddXmlRoutesFromContent("""
""");
var producer = await StartAndProducer("direct://xml-ph-missing");
var exchange = new Exchange(new Message("payload"));
Exception? failure = null;
try { await producer.Process(exchange); }
catch (Exception ex) { failure = ex; }
(failure ?? exchange.Exception).Should().NotBeNull()
.And.Subject.As().Message.Should().Contain("'demo.missing'").And.Contain("no default");
}
[Fact]
public async Task TokenizeJsonArray_SplitsTheArrayAJpathSetBodyLeft()
{
var parts = new List();
_context.AddRoutes(r => r.From("direct://xml-line").Process(e => { lock (parts) parts.Add((string)e.In.Body!); }));
_context.AddXmlRoutesFromContent("""
""");
var producer = await StartAndProducer("direct://xml-order");
await producer.Process(new Exchange(new Message(
"""{"id":"o-1","lines":[{"sku":"A-1","qty":1},{"sku":"B-2","qty":2}]}""")));
parts.Should().Equal("""{"sku":"A-1","qty":1}""", """{"sku":"B-2","qty":2}""");
}
[Fact]
public async Task ChoiceAndFilter_BranchAndGuard()
{
var seen = new List();
_context.AddRoutes(r =>
{
r.From("direct://xml-vip").Process(_ => seen.Add("vip"));
r.From("direct://xml-std").Process(_ => seen.Add("std"));
});
_context.AddXmlRoutesFromContent("""
""");
var producer = await StartAndProducer("direct://xml-router");
await producer.Process(Msg(("amount", 5000)));
await producer.Process(Msg(("amount", 10)));
await producer.Process(Msg(("amount", -1))); // filtered out
seen.Should().Equal("vip", "std");
}
[Fact]
public async Task BeanSection_DeclaresTheObject_AndBeanUriCallsIt()
{
_context.AddXmlRoutesFromContent($$"""
""");
var producer = await StartAndProducer("direct://xml-bean-in");
var exchange = new Exchange(new Message("bob"));
await producer.Process(exchange);
exchange.In.Body.Should().Be("xml:bob");
}
[Fact]
public async Task RouteAttributes_IdAndMessageHistoryAndStepIdentity_FlowThrough()
{
_context.AddXmlRoutesFromContent("""
""");
var producer = await StartAndProducer("direct://xml-hist-in");
var exchange = new Exchange(new Message("x"));
await producer.Process(exchange);
var entry = MessageHistory.GetEntries(exchange).Should().ContainSingle().Subject;
entry.RouteId.Should().Be("xml-history");
entry.NodeId.Should().Be("mark-step");
entry.Label.Should().Be("Mark the exchange");
}
[Fact]
public async Task EnabledFalse_DoesNotRegisterTheRoute()
{
_context.AddXmlRoutesFromContent("""
""");
await _context.Start();
_context.Routes.Select(r => r.RouteId).Should().Contain("xml-enabled").And.NotContain("xml-disabled");
}
// ── Errors: one pass, positions, refusal ─────────────────────────────────
[Fact]
public void UnknownElement_ReportsPositionAndDidYouMean()
{
var act = () => _context.AddXmlRoutesFromContent("""
""", "routes/bad.route.xml");
act.Should().Throw()
.WithMessage("*routes/bad.route.xml(4,*setHeaderr*Did you mean ?*");
}
[Fact]
public void AllErrorsOfTheDocument_AreCollectedInOnePass()
{
var act = () => _context.AddXmlRoutesFromContent("""
""");
var errors = act.Should().Throw().Which.Errors;
errors.Should().HaveCount(3);
errors.Should().Contain(e => e.Contains("'value' or 'expr', not both"));
errors.Should().Contain(e => e.Contains("unknown element "));
errors.Should().Contain(e => e.Contains("scheme 'unregistered-scheme' is not registered"));
}
[Fact]
public void ConsumerUriWithPlaceholder_IsRefusedAtLoad()
{
var act = () => _context.AddXmlRoutesFromContent("""
""");
act.Should().Throw()
.WithMessage("*consumer URI cannot carry ${*only constants and {{key}}*");
}
[Fact]
public void MalformedExpression_FailsAtLoad_WithThePosition()
{
var act = () => _context.AddXmlRoutesFromContent("""
""", "bad-expr.xml");
act.Should().Throw()
.WithMessage("*bad-expr.xml(4,*");
}
[Fact]
public void ForeignNamespaceElement_IsRejected_NotSilentlyParsedByLocalName()
{
// The XSD/namespace discipline: an element from another namespace must never pass as a
// core element just because the local names match.
var act = () => _context.AddXmlRoutesFromContent("""
""", "alien.xml");
act.Should().Throw()
.WithMessage("*alien.xml(4,**namespace 'urn:someone:else'*urn:redb:route:1.0*");
}
[Fact]
public void EmptyNamespaceSubtree_IsRejectedToo()
{
var act = () => _context.AddXmlRoutesFromContent("""
""");
act.Should().Throw()
.WithMessage("**namespace ''*");
}
[Fact]
public void WrongRootNamespace_GetsAClearError()
{
var act = () => _context.AddXmlRoutesFromContent(
"""""");
act.Should().Throw()
.WithMessage("*unexpected root namespace*urn:redb:route:1.0*");
}
[Fact]
public void ErroredDocument_RegistersNothing()
{
var act = () => _context.AddXmlRoutesFromContent("""
""");
act.Should().Throw();
_context.Start().GetAwaiter().GetResult();
_context.Routes.Select(r => r.RouteId).Should().NotContain("half-good", "a document with errors registers none of its routes");
}
private static IExchange Msg(params (string Name, object? Value)[] headers)
{
var exchange = new Exchange(new Message("x"));
foreach (var (name, value) in headers) exchange.In.Headers[name] = value;
return exchange;
}
}