Path: redb-route/tests/redb.Route.Tests.Xml/RestXmlValidationTests.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/RestXmlValidationTests.cs
----
using System.Net;
using System.Text.Json;
using System.Xml.Linq;
using AwesomeAssertions;
using redb.Route.Core;
using redb.Route.Http;
using redb.Route.Http.Rest;
using redb.Route.Xml;
namespace redb.Route.Tests.Xml;
///
/// Client request validation of <rest> in Route-XML: clientRequestValidation and
/// errorHandler on the declaration, clientRequestValidation and <param>
/// children on a verb — parsed into the same declarations as the fluent DSL, printed as the same
/// C#, refused with a positioned error when malformed.
///
public class RestXmlValidationTests
{
private static readonly XmlRouteLoaderOptions Options = new()
{
Extensions = [new RestXmlContribution()],
};
[Fact]
public async Task Params_and_the_option_reach_the_running_route_and_the_openapi_document()
{
var port = FreePort();
await using var servers = new SharedHttpServerManager();
await using var context = new RouteContext();
context.AddComponent(new HttpComponent { ServerManager = servers });
context.AddXmlRoutesFromContent($"""
""", options: Options);
await context.Start();
using var client = new HttpClient { BaseAddress = new Uri($"http://127.0.0.1:{port}") };
(await client.GetAsync("/api/items/7?limit=5")).StatusCode.Should().Be(HttpStatusCode.OK);
var missing = await client.GetAsync("/api/items/7");
missing.StatusCode.Should().Be(HttpStatusCode.BadRequest);
(await missing.Content.ReadAsStringAsync()).Should().Contain("limit");
(await client.GetAsync("/api/items/x?limit=5")).StatusCode.Should().Be(HttpStatusCode.BadRequest);
using var wrongAccept = new HttpRequestMessage(System.Net.Http.HttpMethod.Get, "/api/free");
wrongAccept.Headers.TryAddWithoutValidation("Accept", "application/xml");
(await client.SendAsync(wrongAccept)).StatusCode.Should().Be(HttpStatusCode.OK, "the verb switched validation off");
using var doc = JsonDocument.Parse(await client.GetStringAsync("/api/openapi.json"));
var parameters = doc.RootElement.GetProperty("paths").GetProperty("/api/items/{id}").GetProperty("get")
.GetProperty("parameters").EnumerateArray().ToDictionary(p => p.GetProperty("name").GetString()!);
parameters["id"].GetProperty("schema").GetProperty("type").GetString().Should().Be("integer");
parameters["limit"].GetProperty("in").GetString().Should().Be("query");
parameters["limit"].GetProperty("description").GetString().Should().Be("Page size");
}
[Fact]
public void Params_print_as_the_fluent_calls()
{
var code = XmlCodeGenerator.Generate(XDocument.Parse("""
""", LoadOptions.SetLineInfo), "RestRoutes", "Demo", options: Options);
code.Should().Contain("options.ClientRequestValidation = true;")
.And.Contain("options.ErrorHandler = \"#errors\";")
.And.Contain(".Get(\"/{id}\").ClientRequestValidation(false).Param(\"id\", RestParamType.Path, dataType: RestParamDataType.Integer)"
+ ".Param(\"X-Tenant\", RestParamType.Header, required: true, description: \"Tenant\").To(\"direct://x\");")
.And.Contain(".Post(\"\").Param(\"dryRun\", dataType: RestParamDataType.Boolean).Route()")
.And.Contain("RemoveBody()");
}
[Theory]
[InlineData("""""", "*dataType='int'*string, integer, number, boolean*")]
[InlineData("""""", "*type='cookie'*path, query, header*")]
[InlineData("""""", "*code*not a segment*")]
[InlineData("""""", "*cannot be optional*")]
[InlineData("""""", "*limit*declared twice*")]
public async Task A_malformed_param_is_a_positioned_schema_error(string param, string message)
{
await using var context = new RouteContext();
var act = () => context.AddXmlRoutesFromContent($"""
{param}
""", options: Options);
act.Should().Throw().WithMessage(message);
}
[Fact]
public async Task Inbound_basic_auth_on_rest_protects_its_verbs()
{
var port = FreePort();
await using var servers = new SharedHttpServerManager();
await using var context = new RouteContext();
context.AddComponent(new HttpComponent { ServerManager = servers });
context.AddXmlRoutesFromContent($"""
""", options: Options);
await context.Start();
using var client = new HttpClient { BaseAddress = new Uri($"http://127.0.0.1:{port}") };
var refused = await client.GetAsync("/api/items");
refused.StatusCode.Should().Be(HttpStatusCode.Unauthorized);
refused.Headers.WwwAuthenticate.ToString().Should().Contain("realm=\"orders\"");
using var request = new HttpRequestMessage(System.Net.Http.HttpMethod.Get, "/api/items");
request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(
"Basic", Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes("admin:s3cret")));
(await client.SendAsync(request)).StatusCode.Should().Be(HttpStatusCode.OK);
}
[Fact]
public void Inbound_auth_prints_as_the_fluent_options()
{
var code = XmlCodeGenerator.Generate(XDocument.Parse("""
""", LoadOptions.SetLineInfo), "RestRoutes", "Demo", options: Options);
code.Should().Contain("using redb.Route.Http;").And.Contain("using redb.Route.Http.Rest;")
.And.Contain("options.InboundAuth = HttpAuthScheme.Bearer;")
.And.Contain("options.TokenValidator = \"#tokens\";")
.And.Contain("options.InboundRealm = \"orders\";");
}
private static int FreePort() => global::redb.Route.Tests.Shared.TestPorts.Next();
}