Path: redb-route/tests/redb.Route.Tests.DataFormats/XmlJsonRealSchemaTests.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.DataFormats/XmlJsonRealSchemaTests.cs ---- using System.Runtime.CompilerServices; using System.Text; using System.Text.Json.Nodes; using System.Xml; using System.Xml.Linq; using System.Xml.Schema; using AwesomeAssertions; using redb.Route.DataFormats.XmlJson; using redb.Route.DataFormats.XmlJson.Internal; namespace redb.Route.Tests.DataFormats; /// /// xmljson on real schemas (step S9): the schemas of this repository and public ones (OASIS ebMS 3.0 with W3C /// xmldsig and OASIS WS-Security, SOAP 1.1 and 1.2). Each sample is valid against its schema, goes XML to JSON to XML, /// and the result is valid again and equal to the sample; at a repeated place one element and several give the same /// JSON shape. The public schemas are kept under Fixtures/xmljson with their import locations made local. /// public sealed class XmlJsonRealSchemaTests { private static string Repo([CallerFilePath] string file = "") => Path.GetFullPath(Path.Combine(Path.GetDirectoryName(file)!, "..", "..")); private static string Fixture(params string[] parts) => Path.Combine([AppContext.BaseDirectory, "Fixtures", "xmljson", .. parts]); private static XmlSchemaSet Load(string path, string? root = null) => redb.Route.Validation.SchemaResolver.Load("xmljson", path, root); private static void Valid(XmlSchemaSet set, XDocument document) { var errors = new List(); document.Validate(set, (_, e) => errors.Add(e.Message)); errors.Should().BeEmpty(); } /// The sample is valid, its JSON comes back as the same valid document; returns the JSON. private static JsonNode RoundTrip(XmlSchemaSet set, string xml, Action? configure = null) { var sample = XDocument.Parse(xml); Valid(set, sample); var options = new XmlJsonOptions { SchemaSet = set }; configure?.Invoke(options); var toJson = new XmlToJson(options); var json = toJson.Convert(Encoding.UTF8.GetBytes(xml)); var back = new JsonToXml(options).Convert(Encoding.UTF8.GetBytes(json.ToJsonString())); Valid(set, back); XNode.DeepEquals(Normalize(back.Root!), Normalize(sample.Root!)).Should().BeTrue( $"the document comes back as it was:\n{back.Root}\nversus\n{sample.Root}"); return json; } /// Namespace declarations may move to the root; prefixes and layout aside, the elements must be equal. private static XElement Normalize(XElement element) => new(element.Name, element.Attributes().Where(a => !a.IsNamespaceDeclaration).OrderBy(a => a.Name.ToString()), element.Nodes().Select(n => n switch { XElement child => (object)Normalize(child), XText text when string.IsNullOrWhiteSpace(text.Value) && element.HasElements => null!, XText text => text.Value, _ => null!, }).Where(n => n is not null)); // ── This repository ───────────────────────────────────────────────────────────────────── [Fact] public void WorkerTemplate_Order() { var set = Load(Path.Combine(Repo(), "..", "redb.Templates", "templates", "redb-worker", "RedbWorker.Module", "Xml", "Order.xsd")); RoundTrip(set, "A-1Ann12.50EUR") ["Order"]!["Amount"]!.GetValue().Should().Be(12.50m); } [Fact] public void RouteXmlTemplate_OrderWithLines() { var set = Load(Path.Combine(Repo(), "..", "redb.Templates", "templates", "route-xml", "redb-route-validator-xslt", "resources", "order.xsd")); var one = RoundTrip(set, """Ann"""); var two = RoundTrip(set, """Ann"""); one["order"]!["line"].Should().BeOfType(); two["order"]!["line"]!.AsArray().Count.Should().Be(2); one["order"]!["line"]![0]!["@qty"]!.GetValue().Should().Be(1); } [Fact] public void SerialNumbersDemo_Request() { var set = Load(Path.Combine(Repo(), "demos", "SerialNumbersDemo", "SerialNumbers.Xml", "resources", "SerialNumberRequest.xsd")); RoundTrip(set, "r1046000000000013") ["SerialNumberRequest"]!["Gtin"]!.GetValue().Should().Be("04600000000001", "a pattern-restricted string keeps its leading zero"); } [Fact] public void RouteXmlSchema_ARouteFile() { var set = Load(Path.Combine(Repo(), "demos", "XmlDemo", "schema", "redb-route-1.0.xsd")); const string one = """ """; const string two = """ """; var single = RoundTrip(set, one, o => o.Namespaces = XmlJsonNamespaces.Drop); var several = RoundTrip(set, two, o => o.Namespaces = XmlJsonNamespaces.Drop); single["routes"]!["route"].Should().BeOfType("route repeats in the schema"); single["routes"]!["route"]![0]!["to"].Should().BeOfType("the steps are a repeated choice"); several["routes"]!["route"]![0]!["to"]!.AsArray().Count.Should().Be(2); } // ── Public schemas ────────────────────────────────────────────────────────────────────── private const string Messaging = """ 2026-11-05T10:00:00Z a@example.com senderhttp://example.com/sender receiverhttp://example.com/receiver http://example.com/service Submit 1 """; [Fact] public void Ebms3_Messaging() { var set = Load(Fixture("ebms", "ebms-header-3_0-200704.xsd")); var json = RoundTrip(set, Messaging); var user = json["eb:Messaging"]!["eb:UserMessage"]!; user.Should().BeOfType("UserMessage repeats in the Messaging content"); user[0]!["eb:PartyInfo"]!["eb:From"]!["eb:PartyId"].Should().BeOfType("PartyId repeats"); user[0]!["eb:PayloadInfo"]!["eb:PartInfo"].Should().BeOfType("PartInfo repeats"); } [Fact] public void WsSecurity_SecextWithXmldsigAndUtility_Loads() { // xmldsig-core-schema.xsd starts with a DOCTYPE; a schema's own DOCTYPE is skipped. var set = Load(Fixture("ebms", "oasis-200401-wss-wssecurity-secext-1.0.xsd")); const string security = """ 2026-11-05T10:00:00Z2026-11-05T10:05:00Z """; RoundTrip(set, security)["wsse:Security"]!["wsu:Timestamp"].Should().NotBeNull(); } [Theory] [InlineData("soap11-envelope.xsd", "http://schemas.xmlsoap.org/soap/envelope/")] [InlineData("soap12-envelope.xsd", "http://www.w3.org/2003/05/soap-envelope")] public void Soap_Envelopes(string file, string ns) { var set = Load(Fixture("ebms", file)); var json = RoundTrip(set, $"""1"""); json["s:Envelope"]!["s:Body"]!["Order"]![0]!["Id"]!.GetValue().Should().Be("1", "Body is an unbounded xs:any: its content is an array and falls back below"); } [Fact] public void Ubl21_TheOfficialInvoiceExample() { var watch = System.Diagnostics.Stopwatch.StartNew(); var set = Load(Fixture("ubl", "maindoc", "UBL-Invoice-2.1.xsd"), ".."); var compile = watch.Elapsed; var json = RoundTrip(set, File.ReadAllText(Fixture("ubl", "xml", "UBL-Invoice-2.1-Example.xml")), o => o.Namespaces = XmlJsonNamespaces.Keep); var invoice = json["Invoice"]!; invoice["cac:InvoiceLine"].Should().BeOfType("InvoiceLine repeats"); invoice["cbc:Note"].Should().BeOfType("Note repeats even where the example has one"); invoice["cac:AccountingSupplierParty"].Should().BeOfType("the supplier is single"); // Reported for the release notes, not asserted: the time to compile the UBL 2.1 Invoice schema set. Console.WriteLine($"UBL 2.1 Invoice schema compile: {compile.TotalMilliseconds:F0} ms"); } // ── The schema reader and DTDs ────────────────────────────────────────────────────────── [Fact] public void ASchemaWhoseContentUsesAnEntity_FailsClearly() { var dir = Path.Combine(Path.GetTempPath(), "redb-xmljson-dtd-" + Guid.NewGuid().ToString("N")); Directory.CreateDirectory(dir); try { var path = Path.Combine(dir, "entity.xsd"); File.WriteAllText(path, """ ]> """); var act = () => Load(path); act.Should().Throw().WithMessage("*ns*"); } finally { Directory.Delete(dir, recursive: true); } } [Fact] public void AMessageWithADoctype_IsStillRefused() { var set = Load(Fixture("ebms", "soap11-envelope.xsd")); var converter = new XmlToJson(new XmlJsonOptions { SchemaSet = set }); var act = () => converter.Convert(Encoding.UTF8.GetBytes("""]>&e;""")); act.Should().Throw(); } }