Path: redb-route/tests/redb.Route.Tests.Xml/XmlContextLoaderTests.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Xml/XmlContextLoaderTests.cs
----
using System.Xml.Linq;
using AwesomeAssertions;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Xml;
namespace redb.Route.Tests.Xml;
/// A bean the onInit pipeline calls; counts the calls.
public class InitProbe
{
public int Marked { get; private set; }
public void Mark(IExchange exchange) => Marked++;
}
/// Options object built as a nested anonymous bean.
public class ProbeOptions
{
public string? ConnectionString { get; set; }
/// The creation path of a type that hides construction behind a static method.
public static ProbeOptions FromDsn(string dsn) => new() { ConnectionString = dsn + "/via-factory" };
}
/// A bean whose OPTIONS come through a property, not the constructor: the shape a
/// connector factory has when it holds an object (a certificate, credentials, a serializer).
public class ProbeHolder
{
public ProbeOptions? Options { get; set; }
public string Describe(IExchange exchange) => $"holder:{Options?.ConnectionString}";
}
/// A bean taking an options object through the constructor.
public class ProbeFactory(ProbeOptions options)
{
public string Describe(IExchange exchange) => $"factory:{options.ConnectionString}";
}
/// A minimal component for the <components> section test.
public sealed class ProbeComponent : ComponentBase
{
public override string Scheme => "probe";
public override IEndpoint CreateEndpoint(EndpointUri uri)
=> throw new NotSupportedException("registration-only test component");
}
///
/// Context batch: context.xml — the components section, context beans with
/// nested constructor beans, the onInit pipeline in the fail-fast bootstrap phase, and the
/// {{...}}-aware enabled= on routes.
///
public class XmlContextLoaderTests : IAsyncLifetime
{
private readonly RouteContext _context = new();
public Task InitializeAsync() => Task.CompletedTask;
public async Task DisposeAsync()
{
await _context.DisposeAsync();
GC.SuppressFinalize(this);
}
// ── onInit ───────────────────────────────────────────────────────────────
[Fact]
public async Task OnInit_RunsOnce_BeforeTheRoutesStart()
{
var probe = new InitProbe();
_context.AddToRegistry("init-probe", probe);
_context.AddXmlContextFromContent("""
""");
probe.Marked.Should().Be(0, "the pipeline runs at Start(), not at load");
await _context.Start();
probe.Marked.Should().Be(1);
}
[Fact]
public async Task OnInit_FailingStep_KeepsTheContextFromStarting()
{
_context.AddXmlContextFromContent("""
""", "broken-init.xml");
var act = () => _context.Start();
(await act.Should().ThrowAsync())
.WithInnerException()
.WithMessage("* of 'broken-init.xml' failed*ddl failed*");
}
// ── components and beans ─────────────────────────────────────────────────
[Fact]
public void ComponentsSection_RegistersTheScheme_ForRouteFilesToUse()
{
_context.AddXmlContextFromContent($$"""
""");
_context.GetComponentNames().Should().Contain("probe");
// The scheme check of a routes document now accepts it (endpoints stay lazy).
var load = () => _context.AddXmlRoutesFromContent("""
""");
load.Should().NotThrow();
}
[Fact]
public async Task ConstructorArg_NestedAnonymousBean_BuildsTheGraph()
{
_context.AddXmlContextFromContent($$"""
""");
_context.AddXmlRoutesFromContent("""
""");
await _context.Start();
var producer = _context.GetEndpoint("direct://ctx-factory-in").CreateProducer();
await producer.Start();
var exchange = new Exchange(new Message("x"));
await producer.Process(exchange);
exchange.In.Body.Should().Be("factory:Host=demo");
}
[Fact]
public async Task Property_NestedAnonymousBean_IsAssignedAsTheObject()
{
// A property whose type is an OBJECT could not be set before: took a string only,
// so a factory holding a certificate or a credentials object forced the C# spelling.
_context.AddXmlContextFromContent($$"""
""");
_context.AddXmlRoutesFromContent("""
""");
await _context.Start();
var producer = _context.GetEndpoint("direct://ctx-holder-in").CreateProducer();
await producer.Start();
var exchange = new Exchange(new Message("x"));
await producer.Process(exchange);
exchange.In.Body.Should().Be("holder:Host=demo");
}
[Fact]
public async Task Bean_FactoryMethod_CreatesThroughTheStaticMethod()
{
// Some types are created by a static method, not a public constructor (X509CertificateLoader
// is the reason this exists). factoryMethod= names it; constructorArg values are its arguments.
_context.AddXmlContextFromContent($$"""
""");
_context.AddXmlRoutesFromContent("""
""");
await _context.Start();
var producer = _context.GetEndpoint("direct://ctx-static-in").CreateProducer();
await producer.Start();
var exchange = new Exchange(new Message("x"));
await producer.Process(exchange);
exchange.In.Body.Should().Be("factory:Host=demo/via-factory");
}
[Fact]
public void StructuredEndpoint_CarriesAnExplicitFalse_AndOmitsAnAbsentOption()
{
// transacted on a producer is tri-state now (119e76d7): absent waits for the enclosing
// transaction, "false" sends at once. The structured form must keep the two apart: an
// absent attribute stays absent in the URI, an explicit false reaches it verbatim.
var document = XDocument.Parse("""
""");
var code = XmlCodeGenerator.Generate(document, "TransactedGenerated", "Tests.Generated");
code.Should().Contain("\"kafka://orders?transacted=false\"");
code.Should().Contain("\"kafka://audit\"", "an attribute that is not written is not an option");
}
[Fact]
public void Generator_PrintsTheObjectProperty_AndTheFactoryMethod()
{
// The C# spelling of the same two forms: a nested bean as the property value, and the
// static creator as the last argument of XmlBeans.Create.
var document = XDocument.Parse($$"""
""");
var code = XmlCodeGenerator.Generate(document, "BeanGenerated", "Tests.Generated");
code.Should().Contain("(\"Options\", XmlBeans.Create(")
.And.Contain("\"FromDsn\")", "the factory method is the last argument");
}
[Fact]
public void Property_ValueAndNestedBean_Together_IsASchemaError()
{
var act = () => _context.AddXmlContextFromContent($$"""
""");
act.Should().Throw()
.WithMessage("*takes exactly one of: value=, ref=, one nested anonymous , one *");
}
[Fact]
public void ConstructorArg_ValueAndNestedBean_Together_IsASchemaError()
{
var act = () => _context.AddXmlContextFromContent($$"""
""");
act.Should().Throw()
.WithMessage("*takes exactly one of: value=, ref=, one nested anonymous , one *");
}
[Fact]
public void UnknownContextSection_And_SecondOnInit_AreCollectedTogether()
{
var act = () => _context.AddXmlContextFromContent("""
""", "bad-context.xml");
var errors = act.Should().Throw().Which.Errors;
errors.Should().HaveCount(2);
errors.Should().Contain(e => e.Contains("at most one "));
errors.Should().Contain(e => e.Contains("unknown section "));
}
// ── {{...}}-aware enabled= ───────────────────────────────────────────────
[Fact]
public async Task EnabledPlaceholder_ResolvesFromContextProperties_AndDefaults()
{
_context.SetProperty("features.on", "true");
_context.AddXmlRoutesFromContent("""
""");
await _context.Start();
var ids = _context.Routes.Select(r => r.RouteId).ToList();
ids.Should().Contain("en-on").And.NotContain("en-default-off");
}
[Fact]
public void EnabledPlaceholder_WithoutValueOrDefault_IsAPositionedError()
{
var act = () => _context.AddXmlRoutesFromContent("""
""", "enabled.xml");
act.Should().Throw()
.WithMessage("*enabled.xml(2,*Unresolved property placeholder*no.such.key*");
}
[Fact]
public void EnabledResolvingToNonBool_IsASchemaError()
{
_context.SetProperty("features.kind", "sometimes");
var act = () => _context.AddXmlRoutesFromContent("""
""");
act.Should().Throw()
.WithMessage("*resolved to 'sometimes', which is not a bool*");
}
}