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"));
}
}