Bundle: redb-route / tests/redb.Route.Tests.Templates (tests.redb.Route.Tests.Templates.txt), 7 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.Templates/BeanCallInTemplateTests.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.Templates/BeanCallInTemplateTests.cs
----
using AwesomeAssertions;
using redb.Route.Core;
using redb.Route.Expressions;
using redb.Route.Templates;
using redb.Route.TestKit;
using static redb.Route.Core.TextSource;
namespace redb.Route.Tests.Templates;
/// A bean a payload template might try to reach.
public class TemplateGoldRules
{
public static bool Called;
public bool IsGold(string? name)
{
Called = true;
return name == "ann";
}
}
///
/// Where the bean: function meets the template sandbox, as EXPRESSIONS.md section 11 states it. A template argument is
/// a compiled expression evaluated under the sandbox, so a bean: call there is refused. A payload template's
/// expr(...) reads its text as the inside of a ${...} hole (findings register rows 2 and 22, closed), so a bean: call
/// there is refused the same way. In neither case does the bean run.
///
public sealed class BeanCallInTemplateTests
{
private static async Task Render(string template, Action? args = null)
{
await using var ctx = new RouteContext();
ctx.AddToRegistry("rules", new TemplateGoldRules());
ctx.AddRoutes(b => b.From("direct://in").SetBodyTemplate(Inline(template), MediaType.Text, args));
await ctx.Start();
return await ctx.RequestBodyAndHeaders("direct://in", "ann", new Dictionary());
}
[Fact]
public async Task ATemplateArgument_IsEvaluatedUnderTheSandbox_AndTheBeanCallIsRefused()
{
TemplateGoldRules.Called = false;
var act = () => Render("{{ args.gold }}", a => a.Set("gold", "bean:rules.IsGold(body)"));
var thrown = await act.Should().ThrowAsync();
Inner(thrown.Which).Should().BeOfType();
TemplateGoldRules.Called.Should().BeFalse();
}
[Fact]
public async Task ExprInThePayload_IsEvaluatedUnderTheSandbox_AndTheBeanCallIsRefused()
{
TemplateGoldRules.Called = false;
var act = () => Render("{{ expr('bean:rules.IsGold(body)') }}");
var thrown = await act.Should().ThrowAsync();
Inner(thrown.Which).Should().BeOfType();
TemplateGoldRules.Called.Should().BeFalse();
}
private static Exception Inner(Exception exception)
{
var current = exception;
while (current is not ExpressionSandboxViolationException && current.InnerException is { } inner)
current = inner;
return current;
}
}
Path: redb-route/tests/redb.Route.Tests.Templates/PayloadTemplateTests.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.Templates/PayloadTemplateTests.cs
----
using System.Globalization;
using System.Text.Json;
using System.Xml.Linq;
using redb.Route.Core;
using redb.Route.Expressions;
using redb.Route.Templates;
using redb.Route.TestKit;
using static redb.Route.Core.TextSource;
namespace redb.Route.Tests.Templates;
/// Rendering, escaping and the data model of the payload template step.
public class PayloadTemplateTests
{
public sealed class Item { public string Sku { get; set; } = ""; public int Qty { get; set; } }
public sealed class Order
{
public int Id { get; set; }
public bool Vip { get; set; }
public List- Items { get; set; } = [];
public decimal Price { get; set; }
public DateTime When { get; set; }
public string Fragment { get; set; } = "";
public string Explode() => throw new InvalidOperationException("must never be called from a template");
}
private static Task Render(string template, MediaType mediaType, object? body,
IDictionary? headers = null, Action? args = null, Action? options = null)
=> Render(Inline(template), mediaType, body, headers, args, options);
private static async Task Render(TextSource source, MediaType mediaType, object? body,
IDictionary? headers = null, Action? args = null, Action? options = null)
{
await using var ctx = new RouteContext();
if (options is not null) ctx.UseTemplates(options);
ctx.AddRoutes(b => b.From("direct://in").SetBodyTemplate(source, mediaType, args));
await ctx.Start();
return await ctx.RequestBodyAndHeaders("direct://in", body, headers ?? new Dictionary());
}
[Fact]
public async Task Json_EscapesSubstitutedValues_TemplateLiteralsUntouched()
{
var name = "Bob \"the\" Builder\nline2 \\ end";
var json = await Render("""{"name": "{{ headers.name }}", "n": {{ headers.n }}}""", MediaType.Json, null,
new Dictionary { ["name"] = name, ["n"] = 5 });
using var doc = JsonDocument.Parse(json!);
doc.RootElement.GetProperty("name").GetString().Should().Be(name);
doc.RootElement.GetProperty("n").GetInt32().Should().Be(5);
}
[Fact]
public async Task Xml_EscapesSubstitutedValues()
{
var xml = await Render("""{{ body }}""", MediaType.Xml, "x < y & z",
new Dictionary { ["t"] = "it's \"quoted\"" });
var root = XDocument.Parse(xml!).Root!;
root.Value.Should().Be("x < y & z");
root.Attribute("t")!.Value.Should().Be("it's \"quoted\"");
}
[Fact]
public async Task Text_DoesNotEscape()
{
(await Render("{{ body }}", MediaType.Text, "<&>\"")).Should().Be("<&>\"");
}
// Code review 2026-09-01: escaping happens once, when a value is written to the result,
// whatever operators or filters produced it. Hooked into ObjectToString it ran at every conversion.
[Fact]
public async Task Json_EscapesOnce_WhateverOperatorOrFilterProducedTheValue()
{
var json = await Render(
"""{"a":"{{ headers.name }}","b":"{{ headers.name + '!' }}","c":"{{ headers.first + ' ' + headers.name }}","d":"{{ headers.tags | array.join ',' }}"}""",
MediaType.Json, null,
new Dictionary { ["name"] = "O\"Brien", ["first"] = "Sean", ["tags"] = new List { "a\"b", "c" } });
using var doc = JsonDocument.Parse(json!);
doc.RootElement.GetProperty("a").GetString().Should().Be("O\"Brien");
doc.RootElement.GetProperty("b").GetString().Should().Be("O\"Brien!", "a value that went through an operator is escaped once, not twice");
doc.RootElement.GetProperty("c").GetString().Should().Be("Sean O\"Brien");
doc.RootElement.GetProperty("d").GetString().Should().Be("a\"b,c");
}
[Fact]
public async Task Xml_EscapesOnce_WhateverOperatorProducedTheValue()
{
var xml = await Render("""""", MediaType.Xml, null,
new Dictionary { ["city"] = "A&B" });
XDocument.Parse(xml!).Root!.Attribute("a")!.Value.Should().Be("A&B!");
}
[Fact]
public async Task Xml_ReplacesCharactersIllegalInXml()
{
var xml = await Render("{{ headers.v }}", MediaType.Xml, null,
new Dictionary { ["v"] = "ACK\u0008END" });
XDocument.Parse(xml!).Root!.Value.Should().Be("ACK\uFFFDEND", "a control character has no representation in XML 1.0");
}
[Fact]
public async Task Body_ContentType_FollowsMediaType()
{
await using var ctx = new RouteContext().AddRoutes(b => b
.From("direct://ct").SetBodyTemplate(Inline("{}"), MediaType.Json).To("mock://ct"));
await ctx.Start();
await ctx.SendBody("direct://ct", "ignored");
ctx.Mock("mock://ct").ReceivedExchanges[0].In.ContentType.Should().Be("application/json");
}
[Fact]
public async Task Loop_And_Condition_OverPocoBody_WithCSharpMemberNames()
{
var order = new Order { Vip = true, Items = [new() { Sku = "a", Qty = 1 }, new() { Sku = "b", Qty = 2 }] };
var text = await Render("{{ for i in body.Items }}{{ i.Sku }}:{{ i.Qty }}{{ if !for.last }},{{ end }}{{ end }}{{ if body.Vip }} VIP{{ end }}",
MediaType.Text, order);
text.Should().Be("a:1,b:2 VIP");
}
[Fact]
public async Task JsonStringBody_IsParsed_FileTemplate_WithArgs()
{
var json = await Render(File("Templates/order-confirm.json.sbn"), MediaType.Json,
"""{"items":[{"sku":"a","qty":1},{"sku":"b","qty":2}]}""",
new Dictionary { ["orderId"] = 7, ["customerId"] = "C-42" },
a => a.Set("customer", "header.customerId"));
using var doc = JsonDocument.Parse(json!);
doc.RootElement.GetProperty("id").GetInt32().Should().Be(7);
doc.RootElement.GetProperty("customer").GetString().Should().Be("C-42");
doc.RootElement.GetProperty("items").GetArrayLength().Should().Be(2);
doc.RootElement.GetProperty("items")[1].GetProperty("sku").GetString().Should().Be("b");
}
[Fact]
public async Task XmlStringBody_IsNavigable()
{
var text = await Render("{{ body.order.id }}|{{ body.order.item[1].sku }}|{{ body.order.note }}|{{ body.order.item | array.size }}",
MediaType.Text, """
hi""");
text.Should().Be("7|b|hi|2");
}
[Fact]
public async Task Args_ExpressionAndConstant()
{
var text = await Render("{{ args.total }}/{{ args.channel }}", MediaType.Text, null,
new Dictionary { ["amount"] = 2, ["qty"] = 3 },
a => a.Set("total", "header.amount * header.qty").SetValue("channel", "email"));
text.Should().Be("6/email");
}
[Fact]
public void Args_MalformedExpression_FailsAtDslTime()
{
// A broken function call is a syntax error for the AST; "header.a +* 2" would not be — by the
// literal-name-first rule it is a header literally named "a +* 2" (dashes and spaces are legal).
var act = () => new TemplateArgs().Set("x", "max(header.a, ");
act.Should().Throw();
}
[Fact]
public async Task Expr_InsideTemplate_AgreesWithDollarTemplateOutside()
{
var headers = new Dictionary { ["amount"] = 2.5m, ["qty"] = 4, ["name"] = "kit" };
var exchange = Exchange.Create(new Message(null), null);
foreach (var (k, v) in headers) exchange.In.Headers[k] = v;
var outside = ExpressionResolver.ProcessTemplate("${header.amount * header.qty}-${header.name}", exchange);
var inside = await Render("{{ expr(\"header.amount * header.qty\") }}-{{ expr(\"header.name\") }}", MediaType.Text, null, headers);
inside.Should().Be(outside);
}
[Fact]
public async Task HeaderAndPropertyTargets_LeaveBodyAlone()
{
await using var ctx = new RouteContext().AddRoutes(b => b
.From("direct://targets")
.SetHeaderTemplate("X-Sum", Inline("{{ headers.a }}+{{ headers.b }}"), MediaType.Text)
.SetPropertyTemplate("summary", Inline("{{ body }}!"), MediaType.Text)
.To("mock://targets"));
await ctx.Start();
await ctx.SendBodyAndHeaders("direct://targets", "body", new Dictionary { ["a"] = 1, ["b"] = 2 });
var received = ctx.Mock("mock://targets").ReceivedExchanges[0];
received.In.Headers["X-Sum"].Should().Be("1+2");
received.Properties["summary"].Should().Be("body!");
received.In.Body.Should().Be("body");
}
[Fact]
public async Task NumbersAndDates_RenderInvariant_EvenUnderRuCulture()
{
var previous = CultureInfo.CurrentCulture;
CultureInfo.CurrentCulture = new CultureInfo("ru-RU");
try
{
var order = new Order { Price = 2.5m, When = new DateTime(2026, 9, 1, 10, 30, 0, DateTimeKind.Utc) };
var text = await Render("{{ body.Price }}|{{ body.When }}|{{ headers.d }}", MediaType.Text, order,
new Dictionary { ["d"] = 1234.5 });
text.Should().Be("2.5|2026-09-01T10:30:00.0000000Z|1234.5");
}
finally { CultureInfo.CurrentCulture = previous; }
}
[Fact]
public async Task Raw_SkipsEscaping_ForPreBuiltFragments()
{
var order = new Order { Fragment = """{"x":1}""" };
var withRaw = await Render("""{"inner": {{ body.Fragment | raw }}}""", MediaType.Json, order);
var withoutRaw = await Render("""{"inner": "{{ body.Fragment }}"}""", MediaType.Json, order);
JsonDocument.Parse(withRaw!).RootElement.GetProperty("inner").GetProperty("x").GetInt32().Should().Be(1);
JsonDocument.Parse(withoutRaw!).RootElement.GetProperty("inner").GetString().Should().Be("""{"x":1}""");
}
[Fact]
public async Task MethodCall_OnBodyObject_IsNotAllowed()
{
var act = () => Render("{{ body.Explode() }}", MediaType.Text, new Order());
var ex = await act.Should().ThrowAsync();
ex.Which.Message.Should().Contain("Explode");
ex.Which.Should().NotBeOfType("the method body must never run");
}
// Code review 2026-09-01: the sandbox holds through the expr() bridge and the arguments too.
private sealed class Probe
{
public static bool Executed;
public string Name => "probe";
public string Pwn() { Executed = true; return "pwned"; }
}
[Fact]
public async Task Expr_CannotCallMethods_TheSandboxHoldsThroughTheBridge()
{
Probe.Executed = false;
var act = () => Render("{{ expr('body.Pwn()') }}", MediaType.Text, new Probe());
var ex = await act.Should().ThrowAsync();
ex.Which.Message.Should().Contain("Pwn");
Probe.Executed.Should().BeFalse("a template reads members, it never runs code");
}
[Fact]
public async Task Expr_StillReadsMembers()
{
(await Render("{{ expr('body.Name') }}", MediaType.Text, new Probe())).Should().Be("probe");
}
[Fact]
public async Task Args_CannotCallMethods()
{
Probe.Executed = false;
var act = () => Render("{{ args.x }}", MediaType.Text, new Probe(), args: a => a.Set("x", "body.Pwn()"));
await act.Should().ThrowAsync();
Probe.Executed.Should().BeFalse();
}
[Fact]
public async Task Liquid_Syntax_WhenEnabled()
{
var text = await Render("{{ headers.name | upcase }}", MediaType.Text, null,
new Dictionary { ["name"] = "bob" }, options: o => o.Liquid = true);
text.Should().Be("BOB");
}
[Fact]
public async Task MissingVariable_EmptyByDefault_ErrorWhenStrict()
{
(await Render("[{{ headers.nope }}]", MediaType.Text, null)).Should().Be("[]");
var strict = () => Render("[{{ headers.nope }}]", MediaType.Text, null, options: o => o.StrictVariables = true);
await strict.Should().ThrowAsync();
}
[Fact]
public async Task Exception_IsVisible_InsideOnException()
{
await using var ctx = new RouteContext().AddRoutes(b =>
{
b.OnException().Handled()
.SetBodyTemplate(Inline("""{"error": "{{ exception.message }}", "type": "{{ exception.type }}"}"""), MediaType.Json)
.To("mock://errors");
b.From("direct://boom").ThrowException("bad \"input\"");
});
await ctx.Start();
await ctx.SendBody("direct://boom", "x");
var body = (string)ctx.Mock("mock://errors").ReceivedExchanges[0].In.Body!;
var doc = JsonDocument.Parse(body);
doc.RootElement.GetProperty("error").GetString().Should().Be("bad \"input\"");
doc.RootElement.GetProperty("type").GetString().Should().Be(nameof(InvalidOperationException));
}
}
Path: redb-route/tests/redb.Route.Tests.Templates/TemplateCacheKeyTests.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.Templates/TemplateCacheKeyTests.cs
----
using redb.Route.Core;
using redb.Route.Templates;
using redb.Route.TestKit;
namespace redb.Route.Tests.Templates;
///
/// Code review 2026-09-01: the compile cache is process-wide, so it must be keyed by the resolved
/// file, not by the relative name — two base directories are two templates, and an edited file is a
/// new template for the next context that starts.
///
public class TemplateCacheKeyTests
{
[Fact]
public async Task CompileCache_IsKeyedByTheResolvedFile_NotByTheRelativeName()
{
var a = Directory.CreateTempSubdirectory("redb-tpl-a-");
var b = Directory.CreateTempSubdirectory("redb-tpl-b-");
try
{
await System.IO.File.WriteAllTextAsync(Path.Combine(a.FullName, "t.sbn"), "FROM-A");
await System.IO.File.WriteAllTextAsync(Path.Combine(b.FullName, "t.sbn"), "FROM-B");
(await RenderFrom(a.FullName)).Should().Be("FROM-A");
(await RenderFrom(b.FullName)).Should().Be("FROM-B", "a different base directory is a different template");
await System.IO.File.WriteAllTextAsync(Path.Combine(a.FullName, "t.sbn"), "EDITED-A");
(await RenderFrom(a.FullName)).Should().Be("EDITED-A", "a new context compiles the edited file afresh");
}
finally
{
a.Delete(recursive: true);
b.Delete(recursive: true);
}
static async Task RenderFrom(string baseDirectory)
{
await using var ctx = new RouteContext();
ctx.UseTemplates(o => o.BaseDirectory = baseDirectory);
ctx.AddRoutes(r => r.From("direct://k").SetBodyTemplate("t.sbn", MediaType.Text));
await ctx.Start();
return await ctx.RequestBody("direct://k", null);
}
}
}
Path: redb-route/tests/redb.Route.Tests.Templates/TemplateModelReviewTests.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.Templates/TemplateModelReviewTests.cs
----
using redb.Route.Core;
using redb.Route.Templates;
using redb.Route.TestKit;
namespace redb.Route.Tests.Templates;
/// Code review 2026-09-01: the framework's own DI-scope properties are not part of the template model.
public class TemplateModelReviewTests
{
[Fact]
public async Task Properties_DoNotExposeServiceScopes()
{
await using var ctx = new RouteContext().AddRoutes(b => b
.From("direct://props")
.SetProperty("__redb_scope:x", "leak")
.SetProperty("visible", "yes")
.SetBodyTemplate(TextSource.Inline("{{ properties | object.has_key '__redb_scope:x' }}|{{ properties.visible }}"), MediaType.Text));
await ctx.Start();
var body = await ctx.RequestBody("direct://props", "in");
body.Should().Be("false|yes");
}
}
Path: redb-route/tests/redb.Route.Tests.Templates/TemplateResourceResolverTests.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.Templates/TemplateResourceResolverTests.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Templates;
using redb.Route.TestKit;
namespace redb.Route.Tests.Templates;
///
/// A template named by a relative path is looked up the way every other file reference in the
/// framework is: the context's first, then the package's base
/// directory. Reported by the Route-XML agent 2026-09-24 — a route inside a .tpkg keeps its
/// template in resources/, which only the resolver knows about, so the step failed at start
/// while validateXsd and xslt in the same package found their files.
///
public class TemplateResourceResolverTests
{
/// Resolver that knows exactly one root, as the package resolver does.
private sealed class RootResolver(string root) : IRouteResourceResolver
{
public string? Resolve(string reference)
{
if (Path.IsPathRooted(reference)) return System.IO.File.Exists(reference) ? reference : null;
var candidate = Path.GetFullPath(Path.Combine(root, reference));
return System.IO.File.Exists(candidate) ? candidate : null;
}
public string DescribeSearch(string reference) => Path.Combine(root, reference);
}
private static async Task Render(string root, string relativePath)
{
await using var ctx = new RouteContext();
ctx.AddService(typeof(IRouteResourceResolver), new RootResolver(root));
ctx.AddRoutes(r => r.From("direct://res").SetBodyTemplate(relativePath, MediaType.Text));
await ctx.Start();
return await ctx.RequestBody("direct://res", null);
}
[Fact]
public async Task A_template_the_resolver_knows_is_found_although_the_base_directory_does_not_hold_it()
{
var pkg = Directory.CreateTempSubdirectory("redb-tpl-pkg-");
try
{
Directory.CreateDirectory(Path.Combine(pkg.FullName, "templates"));
await System.IO.File.WriteAllTextAsync(Path.Combine(pkg.FullName, "templates", "order.sbn"), "FROM-PACKAGE");
// BaseDirectory stays the worker's directory, exactly as in a .tpkg: nobody repoints it.
(await Render(pkg.FullName, "templates/order.sbn")).Should().Be("FROM-PACKAGE");
}
finally
{
pkg.Delete(recursive: true);
}
}
[Fact]
public async Task Two_resolvers_with_one_relative_name_are_two_templates()
{
var a = Directory.CreateTempSubdirectory("redb-tpl-ra-");
var b = Directory.CreateTempSubdirectory("redb-tpl-rb-");
try
{
await System.IO.File.WriteAllTextAsync(Path.Combine(a.FullName, "t.sbn"), "FROM-A");
await System.IO.File.WriteAllTextAsync(Path.Combine(b.FullName, "t.sbn"), "FROM-B");
// The compile cache is process-wide: keyed by the name alone, a hot-reloaded module would
// render the previous version's text.
(await Render(a.FullName, "t.sbn")).Should().Be("FROM-A");
(await Render(b.FullName, "t.sbn")).Should().Be("FROM-B");
}
finally
{
a.Delete(recursive: true);
b.Delete(recursive: true);
}
}
[Fact]
public async Task A_template_in_the_base_directory_is_still_found_when_the_resolver_has_none()
{
var baseDir = Directory.CreateTempSubdirectory("redb-tpl-base-");
var empty = Directory.CreateTempSubdirectory("redb-tpl-empty-");
try
{
await System.IO.File.WriteAllTextAsync(Path.Combine(baseDir.FullName, "t.sbn"), "FROM-BASE");
await using var ctx = new RouteContext();
ctx.AddService(typeof(IRouteResourceResolver), new RootResolver(empty.FullName));
ctx.UseTemplates(o => o.BaseDirectory = baseDir.FullName);
ctx.AddRoutes(r => r.From("direct://fallback").SetBodyTemplate("t.sbn", MediaType.Text));
await ctx.Start();
(await ctx.RequestBody("direct://fallback", null)).Should().Be("FROM-BASE");
}
finally
{
baseDir.Delete(recursive: true);
empty.Delete(recursive: true);
}
}
[Fact]
public async Task A_template_in_neither_place_names_both_of_them()
{
var resolverRoot = Directory.CreateTempSubdirectory("redb-tpl-nr-");
var baseDir = Directory.CreateTempSubdirectory("redb-tpl-nb-");
try
{
await using var ctx = new RouteContext();
ctx.AddService(typeof(IRouteResourceResolver), new RootResolver(resolverRoot.FullName));
ctx.UseTemplates(o => o.BaseDirectory = baseDir.FullName);
ctx.AddRoutes(r => r.From("direct://missing").SetBodyTemplate("nowhere.sbn", MediaType.Text));
var act = () => ctx.Start();
// Whoever reads the failure has to know where it looked — both places, as the validator
// and the XSLT step report them.
(await act.Should().ThrowAsync()).Which.ToString()
.Should().Contain(resolverRoot.FullName).And.Contain(baseDir.FullName);
}
finally
{
resolverRoot.Delete(recursive: true);
baseDir.Delete(recursive: true);
}
}
}
Path: redb-route/tests/redb.Route.Tests.Templates/TemplateSourceTests.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.Templates/TemplateSourceTests.cs
----
using System.Xml.Linq;
using redb.Route.Core;
using redb.Route.Templates;
using redb.Route.TestKit;
using static redb.Route.Core.TextSource;
namespace redb.Route.Tests.Templates;
/// Locators, files, embedded resources, compile errors and the compile cache.
public class TemplateSourceTests
{
[Fact]
public async Task MissingFile_FailsStart_WithTheLocator()
{
await using var ctx = new RouteContext().AddRoutes(b => b
.From("direct://nf").SetBodyTemplate("Templates/nope.sbn", MediaType.Text));
var act = () => ctx.Start();
var ex = await act.Should().ThrowAsync();
ex.Which.TemplateName.Should().Be("Templates/nope.sbn");
ex.Which.Message.Should().Contain("Templates/nope.sbn").And.Contain("not found");
}
[Fact]
public async Task SyntaxError_FailsStart_WithLineAndColumn()
{
await using var ctx = new RouteContext().AddRoutes(b => b
.From("direct://se").SetBodyTemplate("Templates/broken.sbn", MediaType.Text));
var act = () => ctx.Start();
var ex = await act.Should().ThrowAsync();
ex.Which.Line.Should().Be(2);
ex.Which.Message.Should().StartWith("Template 'Templates/broken.sbn' (2,");
}
[Fact]
public async Task InlineSyntaxError_FailsStart_WithInlineName()
{
await using var ctx = new RouteContext().AddRoutes(b => b
.From("direct://ise").SetBodyTemplate(Inline("{{ if }}"), MediaType.Text));
var act = () => ctx.Start();
(await act.Should().ThrowAsync()).Which.TemplateName.Should().Be("");
}
[Fact]
public void Cache_SameSource_CompilesOnce()
{
var options = new RouteTemplateOptions();
var first = TemplateEngine.Compile(File("Templates/order-confirm.json.sbn"), options);
var second = TemplateEngine.Compile(File("Templates/order-confirm.json.sbn"), options);
second.Should().BeSameAs(first, "the cache is keyed by source identity");
// Same text, both syntaxes (the file above uses {{~ ~}} which Liquid does not have).
var scriban = TemplateEngine.Compile(Inline("{{ headers.x }}"), options);
var liquid = TemplateEngine.Compile(Inline("{{ headers.x }}"), new RouteTemplateOptions { Liquid = true });
liquid.Should().NotBeSameAs(scriban, "syntax is part of the key");
}
[Fact]
public async Task Cache_TwoRoutesOneFile_BothStartAndRender()
{
await using var ctx = new RouteContext().AddRoutes(b =>
{
b.From("direct://one").SetBodyTemplate("Templates/order-confirm.json.sbn", MediaType.Json, a => a.SetValue("customer", "1"));
b.From("direct://two").SetBodyTemplate("Templates/order-confirm.json.sbn", MediaType.Json, a => a.SetValue("customer", "2"));
});
await ctx.Start();
var body = """{"items":[]}""";
var headers = new Dictionary { ["orderId"] = 1 };
(await ctx.RequestBodyAndHeaders("direct://one", body, headers)).Should().Contain("\"customer\": \"1\"");
(await ctx.RequestBodyAndHeaders("direct://two", body, headers)).Should().Contain("\"customer\": \"2\"");
}
[Fact]
public async Task EmbeddedLocator_Resolves()
{
await using var ctx = new RouteContext().AddRoutes(b => b
.From("direct://emb")
.SetBodyTemplate("assembly:redb.Route.Tests.Templates/Templates/notify.xml.sbn", MediaType.Xml, a => a
.Set("customer", "header.customerId")
.SetValue("channel", "email")));
await ctx.Start();
var xml = await ctx.RequestBodyAndHeaders("direct://emb", null,
new Dictionary { ["customerId"] = "C&Co", ["note"] = "" });
var root = XDocument.Parse(xml!).Root!;
root.Attribute("channel")!.Value.Should().Be("email");
root.Element("customer")!.Value.Should().Be("C&Co");
root.Element("note")!.Value.Should().Be("");
}
[Fact]
public void EmbeddedFactory_WithAssembly_Resolves()
{
var source = Embedded(typeof(TemplateSourceTests).Assembly, "Templates/notify.xml.sbn");
source.Read(AppContext.BaseDirectory).Should().Contain(" b
.From("direct://loc").SetBodyTemplate("{{ headers.x }}", MediaType.Text));
var act = () => ctx.Start();
(await act.Should().ThrowAsync()).Which.Message.Should().Contain("not found");
}
[Fact]
public async Task AbsolutePath_And_BaseDirectoryOption()
{
var dir = Directory.CreateTempSubdirectory("redb-templates-");
try
{
var path = Path.Combine(dir.FullName, "t.sbn");
await System.IO.File.WriteAllTextAsync(path, "hello {{ headers.who }}");
await using var byAbsolute = new RouteContext().AddRoutes(b => b.From("direct://abs").SetBodyTemplate(path, MediaType.Text));
await byAbsolute.Start();
(await byAbsolute.RequestBodyAndHeaders("direct://abs", null, new Dictionary { ["who"] = "abs" }))
.Should().Be("hello abs");
await using var byBase = new RouteContext();
byBase.UseTemplates(o => o.BaseDirectory = dir.FullName);
byBase.AddRoutes(b => b.From("direct://rel").SetBodyTemplate("t.sbn", MediaType.Text));
await byBase.Start();
(await byBase.RequestBodyAndHeaders("direct://rel", null, new Dictionary { ["who"] = "rel" }))
.Should().Be("hello rel");
}
finally { dir.Delete(recursive: true); }
}
[Theory]
[InlineData("assembly:OnlyName")]
[InlineData("assembly:/no-name")]
[InlineData("assembly:Name/")]
public void FromLocator_MalformedAssemblyForm_Throws(string locator)
{
var act = () => FromLocator(locator);
act.Should().Throw();
}
[Fact]
public void FromLocator_FileForm()
{
FromLocator("Templates/x.sbn").Name.Should().Be("Templates/x.sbn");
FromLocator("Templates/x.sbn").CacheKey.Should().Be("file:Templates/x.sbn");
Inline("abc").Name.Should().Be("");
}
}
Path: redb-route/tests/redb.Route.Tests.Templates/redb.Route.Tests.Templates.csproj
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Templates/redb.Route.Tests.Templates.csproj
----