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