Bundle: redb-route / tests/redb.Route.Tests.Controllers (tests.redb.Route.Tests.Controllers.txt), 22 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.Controllers/ActionFilterOrderTests.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.Controllers/ActionFilterOrderTests.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Controllers;
namespace redb.Route.Tests.Controllers;
///
/// is an onion: BeforeAsync ascending by Order,
/// AfterAsync descending, one shared by all of them, with the result,
/// status and elapsed time filled in before the first AfterAsync.
///
public class ActionFilterOrderTests
{
private sealed class RecordingFilter(int order, List calls) : IControllerActionFilter
{
public int Order => order;
public Task BeforeAsync(ControllerActionContext context, CancellationToken ct)
{
calls.Add($"before:{order}");
context.Items[$"seen-by-{order}"] = true;
return Task.CompletedTask;
}
public Task AfterAsync(ControllerActionContext context, CancellationToken ct)
{
calls.Add($"after:{order}:{context.StatusCode}:{context.Result}:{context.Items.Count}:{context.Elapsed >= TimeSpan.Zero}");
return Task.CompletedTask;
}
}
private static IExchange Get(string path)
{
var exchange = new Exchange();
exchange.In.setHeader(ControllerDispatcherProcessor.MethodHeader, "GET");
exchange.In.setHeader(ControllerDispatcherProcessor.PathHeader, path);
return exchange;
}
[Fact]
public async Task Before_runs_ascending_and_After_descending()
{
var calls = new List();
var registry = new ControllerRegistry();
registry.RegisterController(typeof(ModulesController));
await using var context = new RouteContext();
// Passed out of order: the dispatcher sorts them.
var dispatcher = new ControllerDispatcherProcessor(registry, context,
[new RecordingFilter(2, calls), new RecordingFilter(1, calls), new RecordingFilter(3, calls)]);
await dispatcher.Process(Get("modules/5"));
calls.Should().Equal(
"before:1", "before:2", "before:3",
"after:3:200:module-5:3:True", "after:2:200:module-5:3:True", "after:1:200:module-5:3:True");
}
[Fact]
public async Task After_sees_the_error_status_and_the_exception_of_a_failed_action()
{
var calls = new List();
Exception? seen = null;
var registry = new ControllerRegistry();
registry.RegisterController(typeof(FilterProbeController));
await using var context = new RouteContext();
var dispatcher = new ControllerDispatcherProcessor(registry, context,
[new RecordingFilter(1, calls), new ExceptionProbe(e => seen = e)]);
await dispatcher.Process(Get("filter-probe/fail"));
calls.Should().Equal("before:1", "after:1:500::2:True");
seen.Should().BeOfType().Which.Message.Should().Be("probe-failed");
}
private sealed class ExceptionProbe(Action onAfter) : IControllerActionFilter
{
public int Order => 0;
public Task BeforeAsync(ControllerActionContext context, CancellationToken ct)
{
context.Items["probe"] = true;
return Task.CompletedTask;
}
public Task AfterAsync(ControllerActionContext context, CancellationToken ct)
{
onAfter(context.Exception);
return Task.CompletedTask;
}
}
}
Path: redb-route/tests/redb.Route.Tests.Controllers/ActionReturnShapeTests.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.Controllers/ActionReturnShapeTests.cs
----
using System.Text;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Controllers;
namespace redb.Route.Tests.Controllers;
///
/// What an action returns reaches the reply the same way on every dispatcher. The README promises
/// "null or Task (void) → 204, no body"; an async Task method really returns a
/// Task<VoidTaskResult>, and a ValueTask/ValueTask<T> is a struct that is not a
/// at all, so both shapes are pinned here per dispatcher.
///
public class ActionReturnShapeTests
{
private static IExchange Generic(string method, string path)
{
var exchange = new Exchange();
exchange.In.setHeader(ControllerDispatcherProcessor.MethodHeader, method);
exchange.In.setHeader(ControllerDispatcherProcessor.PathHeader, path);
return exchange;
}
private static IExchange Http(string method, string path)
{
var exchange = new Exchange(new Message(Array.Empty()));
exchange.In.setHeader(HttpControllerDispatcher.HttpMethodHeader, method);
exchange.In.setHeader(HttpControllerDispatcher.HttpPathHeader, path);
return exchange;
}
private static IExchange ByName(string header, string name)
{
var exchange = new Exchange();
exchange.In.setHeader(header, name);
return exchange;
}
private static ControllerRegistry Registry()
{
var registry = new ControllerRegistry();
registry.RegisterController(typeof(ReturnShapesController));
return registry;
}
// ── async Task: no result ───────────────────────────
[Fact]
public async Task Generic_async_Task_is_204_without_a_body()
{
await using var context = new RouteContext();
var exchange = Generic("POST", "shapes/done");
await new ControllerDispatcherProcessor(Registry(), context).Process(exchange);
exchange.getProperty("done").Should().Be(true);
exchange.Out!.GetHeader("status.code").Should().Be(204);
exchange.Out.Body.Should().BeNull();
}
[Fact]
public async Task Http_async_Task_is_204_without_a_body()
{
await using var context = new RouteContext();
var exchange = Http("POST", "/shapes/done");
await new HttpControllerDispatcher(Registry(), context).Process(exchange);
exchange.getProperty("done").Should().Be(true);
exchange.Out!.GetHeader("status.code").Should().Be(204);
exchange.Out.GetHeader(HttpControllerDispatcher.HttpResponseCodeHeader).Should().Be(204);
exchange.Out.Body.Should().BeNull();
}
[Fact]
public async Task SignalR_async_Task_is_204_without_a_body()
{
await using var context = new RouteContext();
var exchange = ByName("redbSignalR.Method", nameof(ReturnShapesController.Done));
await new SignalRControllerDispatcher(context, typeof(ReturnShapesController)).Process(exchange);
exchange.getProperty("done").Should().Be(true);
exchange.Out!.GetHeader("status.code").Should().Be(204);
exchange.Out.Body.Should().BeNull();
}
[Fact]
public async Task Grpc_async_Task_is_204_without_a_body()
{
await using var context = new RouteContext();
var exchange = ByName(GrpcControllerDispatcher.MethodHeader, nameof(ReturnShapesController.Done));
await new GrpcControllerDispatcher(context, typeof(ReturnShapesController)).Process(exchange);
exchange.getProperty("done").Should().Be(true);
exchange.Out!.GetHeader("status.code").Should().Be(204);
exchange.Out.Body.Should().BeNull();
}
[Fact]
public async Task Soap_async_Task_answers_an_empty_body()
{
await using var context = new RouteContext();
var exchange = ByName(SoapControllerDispatcher.OperationHeader, nameof(ReturnShapesController.Done));
await new SoapControllerDispatcher(context, typeof(ReturnShapesController)).Process(exchange);
exchange.getProperty("done").Should().Be(true);
exchange.Out!.Body.Should().Be(string.Empty);
}
// -- void: the request body never comes back as the reply --------------------------------------------
[Fact]
public async Task Generic_void_does_not_echo_the_request_body()
{
await using var context = new RouteContext();
var exchange = Generic("DELETE", "modules/42");
exchange.In.Body = "request-payload";
var registry = new ControllerRegistry();
registry.RegisterController(typeof(ModulesController));
await new ControllerDispatcherProcessor(registry, context).Process(exchange);
exchange.Out!.GetHeader("status.code").Should().Be(204);
exchange.Out.Body.Should().BeNull();
}
[Fact]
public async Task Http_void_does_not_echo_the_request_body()
{
await using var context = new RouteContext();
var exchange = Http("DELETE", "/modules/42");
exchange.In.Body = "request-payload"u8.ToArray();
var registry = new ControllerRegistry();
registry.RegisterController(typeof(ModulesController));
await new HttpControllerDispatcher(registry, context).Process(exchange);
exchange.Out!.GetHeader("status.code").Should().Be(204);
exchange.Out.Body.Should().BeNull();
}
[Fact]
public async Task SignalR_void_does_not_echo_the_request_arguments()
{
await using var context = new RouteContext();
var exchange = ByName("redbSignalR.Method", nameof(EchoController.Delete));
exchange.In.Body = 42;
await new SignalRControllerDispatcher(context, typeof(EchoController)).Process(exchange);
exchange.Out!.GetHeader("status.code").Should().Be(204);
exchange.Out.Body.Should().BeNull();
}
[Fact]
public async Task Grpc_void_does_not_echo_the_request_payload()
{
await using var context = new RouteContext();
var exchange = ByName(GrpcControllerDispatcher.MethodHeader, nameof(EchoController.Delete));
exchange.In.Body = "42"u8.ToArray();
await new GrpcControllerDispatcher(context, typeof(EchoController)).Process(exchange);
exchange.Out!.GetHeader("status.code").Should().Be(204);
exchange.Out.Body.Should().BeNull();
}
// -- An action that wrote Out itself and returned null: its reply is the reply ---------------------------
private static void ShouldBeTheActionsOwnReply(IExchange exchange)
{
exchange.Out!.GetHeader("status.code").Should().Be(404);
exchange.Out.GetHeader("Content-Type").Should().Be("application/json");
exchange.Out.Body.Should().BeOfType().Which.Message.Should().Be("no such thing");
}
[Fact]
public async Task Generic_keeps_the_reply_the_action_wrote()
{
await using var context = new RouteContext();
var exchange = Generic("GET", "self-reply");
exchange.In.Body = "request-payload";
var registry = new ControllerRegistry();
registry.RegisterController(typeof(SelfReplyController));
await new ControllerDispatcherProcessor(registry, context).Process(exchange);
ShouldBeTheActionsOwnReply(exchange);
}
[Fact]
public async Task Http_keeps_the_reply_the_action_wrote()
{
await using var context = new RouteContext();
var exchange = Http("GET", "/self-reply");
var registry = new ControllerRegistry();
registry.RegisterController(typeof(SelfReplyController));
await new HttpControllerDispatcher(registry, context).Process(exchange);
ShouldBeTheActionsOwnReply(exchange);
exchange.Out!.GetHeader(HttpControllerDispatcher.HttpResponseCodeHeader).Should().Be(404);
}
[Fact]
public async Task SignalR_keeps_the_reply_the_action_wrote()
{
await using var context = new RouteContext();
var exchange = ByName("redbSignalR.Method", nameof(SelfReplyController.Missing));
await new SignalRControllerDispatcher(context, typeof(SelfReplyController)).Process(exchange);
ShouldBeTheActionsOwnReply(exchange);
}
[Fact]
public async Task Grpc_keeps_the_reply_the_action_wrote()
{
await using var context = new RouteContext();
var exchange = ByName(GrpcControllerDispatcher.MethodHeader, nameof(SelfReplyController.Missing));
await new GrpcControllerDispatcher(context, typeof(SelfReplyController)).Process(exchange);
ShouldBeTheActionsOwnReply(exchange);
}
// ── ValueTask: the result, not the struct ─────────
[Fact]
public async Task Generic_ValueTask_of_T_returns_its_result()
{
await using var context = new RouteContext();
var exchange = Generic("GET", "shapes/value");
await new ControllerDispatcherProcessor(Registry(), context).Process(exchange);
exchange.Out!.GetHeader("status.code").Should().Be(200);
exchange.Out.Body.Should().Be("value-ok");
}
[Fact]
public async Task Http_ValueTask_of_T_returns_its_result()
{
await using var context = new RouteContext();
var exchange = Http("GET", "/shapes/value");
await new HttpControllerDispatcher(Registry(), context).Process(exchange);
exchange.Out!.GetHeader("status.code").Should().Be(200);
exchange.Out.Body.Should().Be("value-ok");
}
[Fact]
public async Task SignalR_ValueTask_of_T_returns_its_result()
{
await using var context = new RouteContext();
var exchange = ByName("redbSignalR.Method", nameof(ReturnShapesController.Value));
await new SignalRControllerDispatcher(context, typeof(ReturnShapesController)).Process(exchange);
exchange.Out!.GetHeader("status.code").Should().Be(200);
exchange.Out.Body.Should().Be("value-ok");
}
[Fact]
public async Task Grpc_ValueTask_of_T_returns_its_result()
{
await using var context = new RouteContext();
var exchange = ByName(GrpcControllerDispatcher.MethodHeader, nameof(ReturnShapesController.Value));
await new GrpcControllerDispatcher(context, typeof(ReturnShapesController)).Process(exchange);
exchange.Out!.GetHeader("status.code").Should().Be(200);
exchange.Out.Body.Should().Be("value-ok");
}
// ── async ValueTask: awaited, then no result ─────────
[Fact]
public async Task Generic_async_ValueTask_is_awaited_and_is_204()
{
await using var context = new RouteContext();
var exchange = Generic("POST", "shapes/value-done");
await new ControllerDispatcherProcessor(Registry(), context).Process(exchange);
exchange.getProperty("done").Should().Be(true);
exchange.Out!.GetHeader("status.code").Should().Be(204);
exchange.Out.Body.Should().BeNull();
}
[Fact]
public async Task Http_async_ValueTask_is_awaited_and_is_204()
{
await using var context = new RouteContext();
var exchange = Http("POST", "/shapes/value-done");
await new HttpControllerDispatcher(Registry(), context).Process(exchange);
exchange.getProperty("done").Should().Be(true);
exchange.Out!.GetHeader("status.code").Should().Be(204);
exchange.Out.Body.Should().BeNull();
}
[Fact]
public async Task SignalR_async_ValueTask_is_awaited_and_is_204()
{
await using var context = new RouteContext();
var exchange = ByName("redbSignalR.Method", nameof(ReturnShapesController.ValueDone));
await new SignalRControllerDispatcher(context, typeof(ReturnShapesController)).Process(exchange);
exchange.getProperty("done").Should().Be(true);
exchange.Out!.GetHeader("status.code").Should().Be(204);
exchange.Out.Body.Should().BeNull();
}
[Fact]
public async Task Grpc_async_ValueTask_is_awaited_and_is_204()
{
await using var context = new RouteContext();
var exchange = ByName(GrpcControllerDispatcher.MethodHeader, nameof(ReturnShapesController.ValueDone));
await new GrpcControllerDispatcher(context, typeof(ReturnShapesController)).Process(exchange);
exchange.getProperty("done").Should().Be(true);
exchange.Out!.GetHeader("status.code").Should().Be(204);
exchange.Out.Body.Should().BeNull();
}
}
Path: redb-route/tests/redb.Route.Tests.Controllers/ControllerBadRequestTests.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.Controllers/ControllerBadRequestTests.cs
----
using System.Text;
using System.Text.Json;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Controllers;
using redb.Route.Controllers.Attributes;
using redb.Route.Core;
namespace redb.Route.Tests.Controllers;
///
/// A request the dispatcher cannot bind is the CALLER's error, not the server's. Every dispatcher
/// used to funnel binding failures — a JSON body missing required members, a route parameter that
/// is not a guid — into the generic catch (Exception): the caller got 500 "InternalError"
/// and the operator got an Error log with a stack for every piece of junk POSTed from outside.
///
/// The boundary is drawn around parameter RESOLUTION, not around exception types: a
/// thrown while binding is a 400, the same exception thrown inside
/// the action stays a 500 — the twin tests below pin both sides.
///
///
public sealed class ControllerBadRequestTests : IAsyncLifetime
{
// Owned by the test instance (xUnit makes one per test) and released after it: the dispatcher the factory
// below returns keeps using both.
private readonly RouteContext _httpContext = new();
private ILoggerFactory? _loggerFactory;
public Task InitializeAsync() => Task.CompletedTask;
public async Task DisposeAsync()
{
await _httpContext.DisposeAsync();
_loggerFactory?.Dispose();
}
// ── Test surface ──
public sealed class StrictOrderRequest
{
public required string ClientId { get; set; }
public required string CallbackUrl { get; set; }
}
public sealed class OrdersController : RedbController
{
[HttpPost]
public object Create([FromBody] StrictOrderRequest request) => new { request.ClientId };
[HttpGet("{id}")]
public string GetById([FromRoute("id")] Guid id) => $"order-{id}";
[HttpGet]
public string Explode() => throw new FormatException("the action itself is broken");
}
private sealed class CapturingLogs : ILoggerProvider, ILogger
{
public readonly List<(LogLevel Level, string Message)> Lines = [];
public ILogger CreateLogger(string categoryName) => this;
public IDisposable? BeginScope(TState state) where TState : notnull => null;
public bool IsEnabled(LogLevel logLevel) => true;
public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter)
{
lock (Lines) Lines.Add((logLevel, formatter(state, exception)));
}
public void Dispose() { }
}
private (HttpControllerDispatcher Dispatcher, CapturingLogs Logs) CreateHttpDispatcher()
{
var registry = new ControllerRegistry();
registry.RegisterController(typeof(OrdersController));
var logs = new CapturingLogs();
_loggerFactory = LoggerFactory.Create(b => b.AddProvider(logs).SetMinimumLevel(LogLevel.Debug));
_httpContext.AddService(typeof(ILoggerFactory), _loggerFactory);
return (new HttpControllerDispatcher(registry, _httpContext), logs);
}
private static IExchange HttpExchange(string method, string path, string? jsonBody = null,
Dictionary? routeParams = null)
{
var exchange = new Exchange(new Message());
if (jsonBody is not null)
exchange.In.Body = Encoding.UTF8.GetBytes(jsonBody);
exchange.In.setHeader("redbHttp.Method", method);
exchange.In.setHeader("redbHttp.Path", path);
if (routeParams is not null)
foreach (var (k, v) in routeParams)
exchange.In.setHeader($"redbHttp.RouteParam.{k}", v);
return exchange;
}
private static (int Status, string Error, string Message) ReadError(IExchange exchange)
{
exchange.Out.Should().NotBeNull();
// Existing per-transport shapes this test set does not take a position on: HTTP writes
// camelCase bytes, gRPC PascalCase bytes, SignalR the response object itself (its
// transport serializes later).
if (exchange.Out!.Body is ControllerErrorResponse direct)
return (direct.StatusCode, direct.Error, direct.Message);
var doc = JsonDocument.Parse((byte[])exchange.Out!.Body!);
JsonElement Prop(string name) =>
doc.RootElement.TryGetProperty(name, out var v)
? v
: doc.RootElement.GetProperty(char.ToUpperInvariant(name[0]) + name[1..]);
return (Prop("statusCode").GetInt32(), Prop("error").GetString()!, Prop("message").GetString()!);
}
// ── HTTP: the paste's exact case ──
[Fact]
public async Task A_body_missing_required_members_is_the_callers_400_not_our_500()
{
var (dispatcher, logs) = CreateHttpDispatcher();
var exchange = HttpExchange("POST", "/orders", jsonBody: "{}");
await dispatcher.Process(exchange);
var (status, error, message) = ReadError(exchange);
status.Should().Be(400, "a client that sent an unbindable body must not be told the server broke");
error.Should().Be("BadRequest");
message.Should().NotContain("unexpected error", "the caller gets told what is wrong with THEIR request");
logs.Lines.Should().Contain(l => l.Level == LogLevel.Warning,
"malformed input is an expected event class, logged as a warning");
logs.Lines.Should().NotContain(l => l.Level == LogLevel.Error,
"junk POSTed from outside must not fill the operator's log with error stacks");
}
[Fact]
public async Task A_route_param_that_is_not_a_guid_is_a_400_too()
{
var (dispatcher, _) = CreateHttpDispatcher();
var exchange = HttpExchange("GET", "/orders/abc",
routeParams: new() { ["id"] = "abc" });
await dispatcher.Process(exchange);
ReadError(exchange).Status.Should().Be(400,
"binding covers route and query parameters, not just the JSON body");
}
[Fact]
public async Task The_same_exception_inside_the_action_stays_a_500()
{
// The boundary is the resolution step, not the exception type: FormatException thrown by
// the action is the server's own failure and keeps the 500 + Error-with-stack contract.
var (dispatcher, logs) = CreateHttpDispatcher();
var exchange = HttpExchange("GET", "/orders");
await dispatcher.Process(exchange);
var (status, error, _) = ReadError(exchange);
status.Should().Be(500);
error.Should().Be("InternalError");
logs.Lines.Should().Contain(l => l.Level == LogLevel.Error);
}
// ── gRPC ──
[Fact]
public async Task Grpc_malformed_json_body_is_a_400()
{
await using var context = new RouteContext();
var dispatcher = new GrpcControllerDispatcher(context, typeof(OrdersController));
var exchange = new Exchange(new Message(Encoding.UTF8.GetBytes("{ not json")));
exchange.In.setHeader("dispatch-method", "Orders.Create");
await dispatcher.Process(exchange);
ReadError(exchange).Status.Should().Be(400);
}
// ── SOAP ──
[System.Xml.Serialization.XmlRoot("StrictOrder", Namespace = "urn:orders")]
public class StrictOrder { public string ClientId { get; set; } = ""; }
public sealed class SoapOrdersController : RedbController
{
public string Register([FromBody] StrictOrder order) => order.ClientId;
}
[Fact]
public async Task Soap_junk_xml_surfaces_as_MalformedRequestException_not_a_generic_failure()
{
// SOAP has no status codes; the dispatcher's "your request is wrong" is the typed
// exception the SOAP consumer maps to a Sender fault. An unhandled XmlSerializer
// exception became a Receiver fault with a generic text — a retry hint for bytes that
// will fail identically forever.
await using var context = new RouteContext();
var dispatcher = new SoapControllerDispatcher(context, typeof(SoapOrdersController));
var exchange = new Exchange(new Message(" dispatcher.Process(exchange);
await act.Should().ThrowAsync();
}
// -- A simple value that does not convert is a binding error (Camel: ParameterBindingException) --------
private HttpControllerDispatcher BindingDispatcher()
{
var registry = new ControllerRegistry();
registry.RegisterController(typeof(BindingController));
return new HttpControllerDispatcher(registry, _httpContext);
}
[Fact]
public async Task A_query_value_that_is_not_a_number_is_a_400_naming_the_parameter_and_the_value()
{
var exchange = HttpExchange("GET", "/binding/query");
exchange.In.setHeader("redbHttp.QueryParam.page", "abc");
await BindingDispatcher().Process(exchange);
var (status, error, message) = ReadError(exchange);
status.Should().Be(400, "page=abc is not a page number; binding it as 0 answered a different question");
error.Should().Be("BadRequest");
message.Should().Contain("page").And.Contain("abc");
}
[Fact]
public async Task A_header_value_that_is_not_a_number_is_a_400()
{
var exchange = HttpExchange("GET", "/binding/header");
exchange.In.setHeader("X-Limit", "lots");
await BindingDispatcher().Process(exchange);
var (status, _, message) = ReadError(exchange);
status.Should().Be(400);
message.Should().Contain("X-Limit").And.Contain("lots");
}
[Fact]
public async Task SignalR_an_argument_that_is_not_a_number_is_a_400()
{
await using var context = new RouteContext();
var dispatcher = new SignalRControllerDispatcher(context, typeof(EchoController));
var exchange = new Exchange(new Message("abc"));
exchange.In.setHeader("redbSignalR.Method", nameof(EchoController.GetById));
await dispatcher.Process(exchange);
var (status, _, message) = ReadError(exchange);
status.Should().Be(400);
message.Should().Contain("id").And.Contain("abc");
}
// -- Generic dispatcher: the same 400/500 boundary as the transport dispatchers --------------------------
private static IExchange GenericExchange(string method, string path)
{
var exchange = new Exchange();
exchange.In.setHeader(ControllerDispatcherProcessor.MethodHeader, method);
exchange.In.setHeader(ControllerDispatcherProcessor.PathHeader, path);
return exchange;
}
[Fact]
public async Task Generic_a_route_param_that_is_not_a_guid_is_a_400()
{
var registry = new ControllerRegistry();
registry.RegisterController(typeof(OrdersController));
var exchange = GenericExchange("GET", "orders/abc");
await new ControllerDispatcherProcessor(registry, _httpContext).Process(exchange);
var (status, error, message) = ReadError(exchange);
status.Should().Be(400);
error.Should().Be("BadRequest");
message.Should().NotContain("unexpected error");
}
[Fact]
public async Task Generic_a_query_value_that_is_not_a_number_is_a_400()
{
var registry = new ControllerRegistry();
registry.RegisterController(typeof(BindingController));
var exchange = GenericExchange("GET", "binding/query");
exchange.In.setHeader("query.page", "abc");
await new ControllerDispatcherProcessor(registry, _httpContext).Process(exchange);
var (status, _, message) = ReadError(exchange);
status.Should().Be(400);
message.Should().Contain("page").And.Contain("abc");
}
[Fact]
public async Task Generic_the_same_exception_inside_the_action_stays_a_500()
{
var registry = new ControllerRegistry();
registry.RegisterController(typeof(OrdersController));
var exchange = GenericExchange("GET", "orders");
await new ControllerDispatcherProcessor(registry, _httpContext).Process(exchange);
var (status, error, _) = ReadError(exchange);
status.Should().Be(500);
error.Should().Be("InternalError");
}
// ── SignalR ──
[Fact]
public async Task SignalR_unbindable_args_are_a_400()
{
await using var context = new RouteContext();
var dispatcher = new SignalRControllerDispatcher(context, typeof(OrdersController));
var exchange = new Exchange(new Message("{ definitely not bindable"));
exchange.In.setHeader("redbSignalR.Method", "Orders.Create");
await dispatcher.Process(exchange);
ReadError(exchange).Status.Should().Be(400);
}
}
Path: redb-route/tests/redb.Route.Tests.Controllers/ControllerDispatcherProcessorTests.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.Controllers/ControllerDispatcherProcessorTests.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Controllers;
using redb.Route.Controllers.Attributes;
namespace redb.Route.Tests.Controllers;
public class ControllerDispatcherProcessorTests
{
[Fact]
public async Task Dispatches_GET_to_controller()
{
var registry = new ControllerRegistry();
registry.RegisterController(typeof(ModulesController));
await using var context = new RouteContext();
var dispatcher = new ControllerDispatcherProcessor(registry, context);
var exchange = new Exchange();
exchange.In.setHeader(ControllerDispatcherProcessor.PathHeader, "modules");
exchange.In.setHeader(ControllerDispatcherProcessor.MethodHeader, "GET");
await dispatcher.Process(exchange);
exchange.Out.Should().NotBeNull();
exchange.Out!.Body.Should().BeEquivalentTo(new[] { "module1", "module2" });
exchange.Out.GetHeader("status.code").Should().Be(200);
}
[Fact]
public async Task Dispatches_GET_with_route_param()
{
var registry = new ControllerRegistry();
registry.RegisterController(typeof(ModulesController));
await using var context = new RouteContext();
var dispatcher = new ControllerDispatcherProcessor(registry, context);
var exchange = new Exchange();
exchange.In.setHeader(ControllerDispatcherProcessor.PathHeader, "modules/42");
exchange.In.setHeader(ControllerDispatcherProcessor.MethodHeader, "GET");
await dispatcher.Process(exchange);
exchange.Out.Should().NotBeNull();
exchange.Out!.Body.Should().Be("module-42");
}
[Fact]
public async Task Dispatches_POST_with_body()
{
var registry = new ControllerRegistry();
registry.RegisterController(typeof(ModulesController));
await using var context = new RouteContext();
var dispatcher = new ControllerDispatcherProcessor(registry, context);
var exchange = new Exchange();
exchange.In.setHeader(ControllerDispatcherProcessor.PathHeader, "modules");
exchange.In.setHeader(ControllerDispatcherProcessor.MethodHeader, "POST");
exchange.In.Body = new CreateModuleRequest { Name = "test-module" };
await dispatcher.Process(exchange);
exchange.Out.Should().NotBeNull();
exchange.Out!.GetHeader("status.code").Should().Be(200);
System.Text.Json.JsonSerializer.Serialize(exchange.Out.Body).Should().Be("{\"Name\":\"test-module\",\"Created\":true}");
}
[Fact]
public async Task Returns_404_for_unknown_path()
{
var registry = new ControllerRegistry();
registry.RegisterController(typeof(ModulesController));
await using var context = new RouteContext();
var dispatcher = new ControllerDispatcherProcessor(registry, context);
var exchange = new Exchange();
exchange.In.setHeader(ControllerDispatcherProcessor.PathHeader, "unknown");
exchange.In.setHeader(ControllerDispatcherProcessor.MethodHeader, "GET");
await dispatcher.Process(exchange);
exchange.Out.Should().NotBeNull();
exchange.Out!.GetHeader("status.code").Should().Be(404);
exchange.Out!.Body.Should().BeOfType();
}
[Fact]
public async Task Returns_400_for_missing_headers()
{
var registry = new ControllerRegistry();
registry.RegisterController(typeof(ModulesController));
await using var context = new RouteContext();
var dispatcher = new ControllerDispatcherProcessor(registry, context);
var exchange = new Exchange();
await dispatcher.Process(exchange);
exchange.Out.Should().NotBeNull();
exchange.Out!.GetHeader("status.code").Should().Be(400);
}
[Fact]
public async Task DELETE_returns_204()
{
var registry = new ControllerRegistry();
registry.RegisterController(typeof(ModulesController));
await using var context = new RouteContext();
var dispatcher = new ControllerDispatcherProcessor(registry, context);
var exchange = new Exchange();
exchange.In.setHeader(ControllerDispatcherProcessor.PathHeader, "modules/42");
exchange.In.setHeader(ControllerDispatcherProcessor.MethodHeader, "DELETE");
await dispatcher.Process(exchange);
exchange.Out.Should().NotBeNull();
exchange.Out!.GetHeader("status.code").Should().Be(204);
}
[Fact]
public async Task Resolves_query_parameter()
{
var registry = new ControllerRegistry();
registry.RegisterController(typeof(ContextsController));
await using var context = new RouteContext();
var dispatcher = new ControllerDispatcherProcessor(registry, context);
var exchange = new Exchange();
exchange.In.setHeader(ControllerDispatcherProcessor.PathHeader, "contexts/myctx/status");
exchange.In.setHeader(ControllerDispatcherProcessor.MethodHeader, "GET");
exchange.In.setHeader("query.verbose", "true");
await dispatcher.Process(exchange);
exchange.Out.Should().NotBeNull();
exchange.Out!.GetHeader("status.code").Should().Be(200);
// The value, not only the status: an unbound bool is false and still answers 200.
System.Text.Json.JsonSerializer.Serialize(exchange.Out.Body).Should().Be("{\"Name\":\"myctx\",\"Verbose\":true,\"Status\":\"running\"}");
}
}
Path: redb-route/tests/redb.Route.Tests.Controllers/ControllerErrorLeakTests.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.Controllers/ControllerErrorLeakTests.cs
----
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using redb.Route.Core;
using redb.Route.Controllers;
using redb.Route.Controllers.Attributes;
namespace redb.Route.Tests.Controllers;
///
/// An unhandled exception in an action used to
/// travel to the caller as its own text, so a path, a connection string or an internal service name
/// left the process through an HTTP response — and it was written nowhere else, so the operator could
/// not even see what the caller saw. The caller gets a generic message; the detail goes to the log.
///
public class ControllerErrorLeakTests
{
private const string Secret = "Server=db-prod;Password=hunter2;Database=payments";
[Route("leaky")]
public class LeakyController : RedbController
{
/// Sync path: MethodInfo.Invoke wraps the exception in a TargetInvocationException.
[HttpGet("sync")]
public string Sync() => throw new InvalidOperationException(Secret);
/// Async path: the faulted Task rethrows the original exception, no TIE.
[HttpGet("async")]
public async Task Async()
{
await Task.Yield();
throw new InvalidOperationException(Secret);
}
}
[Theory]
[InlineData("leaky/sync")]
[InlineData("leaky/async")]
public async Task AnUnhandledException_NeverReachesTheCaller(string path)
{
var (exchange, _) = await Dispatch(path);
exchange.Out.Should().NotBeNull();
exchange.Out!.GetHeader("status.code").Should().Be(500);
var error = exchange.Out.Body.Should().BeOfType().Subject;
error.Message.Should().NotContain("hunter2", "a caller must never receive the exception's own text");
error.Message.Should().NotContain("Password");
error.Message.Should().NotBeEmpty("the caller still needs to know the request failed");
error.Error.Should().Be("InternalError");
}
[Theory]
[InlineData("leaky/sync")]
[InlineData("leaky/async")]
public async Task TheDetailIsLogged_SoItIsNotLostAltogether(string path)
{
var (_, log) = await Dispatch(path);
log.Entries.Should().ContainSingle(e => e.Level == LogLevel.Error)
.Which.Exception!.Message.Should().Contain("hunter2", "the operator must be able to see what actually failed");
}
// The report named one dispatcher. There are five, and four run user action code the same way — each
// had its own copy of "return the exception's Message". The fifth, SOAP, rethrows instead, so its
// fault is written by SoapConsumer; that path leaked the same way and is fixed there (SoapLoopbackTests).
[Fact]
public async Task HttpDispatcher_DoesNotLeakEither()
{
var log = new RecordingLoggerProvider();
using var factory = LoggerFactory.Create(b => b.AddProvider(log));
var registry = new ControllerRegistry();
registry.RegisterController(typeof(LeakyController));
await using var context = new RouteContext(loggerFactory: factory);
var dispatcher = new HttpControllerDispatcher(registry, context);
var exchange = new Exchange();
exchange.In.setHeader("redbHttp.Method", "GET");
exchange.In.setHeader("redbHttp.Path", "/leaky/sync");
await dispatcher.Process(exchange);
var json = System.Text.Encoding.UTF8.GetString((byte[])exchange.Out!.Body!);
json.Should().NotContain("hunter2").And.NotContain("Password");
exchange.Out.GetHeader("status.code").Should().Be(500);
log.Entries.Should().Contain(e => e.Exception != null && e.Exception.Message.Contains("hunter2"));
}
[Route("grpc-leaky")]
public class GrpcLeakyController : RedbController
{
[HttpPost("boom")]
public string Boom() => throw new InvalidOperationException(Secret);
}
[Fact]
public async Task GrpcDispatcher_DoesNotLeakEither()
{
var log = new RecordingLoggerProvider();
using var factory = LoggerFactory.Create(b => b.AddProvider(log));
await using var context = new RouteContext(loggerFactory: factory);
var dispatcher = new GrpcControllerDispatcher(context, typeof(GrpcLeakyController));
var exchange = new Exchange();
exchange.In.setHeader(GrpcControllerDispatcher.MethodHeader, "Boom");
await dispatcher.Process(exchange);
var json = System.Text.Encoding.UTF8.GetString((byte[])exchange.Out!.Body!);
json.Should().NotContain("hunter2").And.NotContain("Password");
log.Entries.Should().Contain(e => e.Exception != null && e.Exception.Message.Contains("hunter2"));
}
[Fact]
public async Task SignalRDispatcher_DoesNotLeakEither()
{
var log = new RecordingLoggerProvider();
using var factory = LoggerFactory.Create(b => b.AddProvider(log));
await using var context = new RouteContext(loggerFactory: factory);
var dispatcher = new SignalRControllerDispatcher(context, typeof(GrpcLeakyController));
var exchange = new Exchange();
exchange.In.setHeader("redbSignalR.Method", "Boom");
await dispatcher.Process(exchange);
var error = exchange.Out!.Body.Should().BeOfType().Subject;
error.Message.Should().NotContain("hunter2").And.NotContain("Password");
log.Entries.Should().Contain(e => e.Exception != null && e.Exception.Message.Contains("hunter2"));
}
// Withholding the detail is only defensible because the caller can quote a reference and an operator
// can find it. That correlation is the compensating control, so it is pinned here: without it a "fix"
// returning a bare "Error." would satisfy every leak assertion above.
[Fact]
public async Task TheCallerGetsAReference_AndTheSameReferenceIsInTheLog()
{
var (exchange, log) = await Dispatch("leaky/sync");
var error = (ControllerErrorResponse)exchange.Out!.Body!;
error.Message.Should().Contain(exchange.ExchangeId, "the caller must have something to quote");
var line = log.Entries.Should().ContainSingle(e => e.Exception != null).Subject;
line.Message.Should().Contain(exchange.ExchangeId, "the operator finds the detail by the id the caller quotes");
}
[Fact]
public async Task TheLoggerIsFoundWhenLoggingComesFromDependencyInjection()
{
// IRouteContext.GetService() reads the context's own table, not the container. A host that
// does AddLogging() and `new RouteContext(serviceProvider)` must still get the detail — otherwise
// hiding it from the caller means losing it, which is worse than the disclosure it replaced.
var log = new RecordingLoggerProvider();
var services = new ServiceCollection();
services.AddLogging(b => { b.SetMinimumLevel(LogLevel.Debug); b.AddProvider(log); });
using var provider = services.BuildServiceProvider();
var registry = new ControllerRegistry();
registry.RegisterController(typeof(LeakyController));
await using var context = new RouteContext(provider);
var dispatcher = new ControllerDispatcherProcessor(registry, context);
var exchange = new Exchange();
exchange.In.setHeader(ControllerDispatcherProcessor.PathHeader, "leaky/sync");
exchange.In.setHeader(ControllerDispatcherProcessor.MethodHeader, "GET");
await dispatcher.Process(exchange);
log.Entries.Should().Contain(e => e.Exception != null && e.Exception.Message.Contains("hunter2"));
}
[Route("nested")]
public class NestedThrowController : RedbController
{
/// Async: the real failure wraps a transient one. Only TIE may be unwrapped, never this.
[HttpGet("async")]
public async Task Async()
{
await Task.Yield();
throw new InvalidOperationException("outer-real-error", new System.Net.Sockets.SocketException(10061));
}
}
[Theory]
[InlineData("grpc")]
[InlineData("signalr")]
public async Task TheLoggedExceptionIsTheOneTheActionReported_NotADeeperWrapper(string transport)
{
var log = new RecordingLoggerProvider();
using var factory = LoggerFactory.Create(b => b.AddProvider(log));
await using var context = new RouteContext(loggerFactory: factory);
var exchange = new Exchange();
if (transport == "grpc")
{
exchange.In.setHeader(GrpcControllerDispatcher.MethodHeader, "Async");
await new GrpcControllerDispatcher(context, typeof(NestedThrowController)).Process(exchange);
}
else
{
exchange.In.setHeader("redbSignalR.Method", "Async");
await new SignalRControllerDispatcher(context, typeof(NestedThrowController)).Process(exchange);
}
var logged = log.Entries.Should().ContainSingle(e => e.Exception != null).Subject.Exception!;
logged.Message.Should().Be("outer-real-error",
"`ex.InnerException ?? ex` would log the SocketException — and the log is now the only record");
}
private sealed class ThrowingFilter : IControllerActionFilter
{
public int Order => 0;
public Task BeforeAsync(ControllerActionContext context, CancellationToken ct) => throw new InvalidOperationException("filter-before-failed");
public Task AfterAsync(ControllerActionContext context, CancellationToken ct) => throw new InvalidOperationException("filter-after-failed");
}
[Route("ok")]
public class OkController : RedbController
{
[HttpGet] public string Get() => "fine";
}
[Fact]
public async Task AFilterThatThrows_IsLogged_AndDispatchStillSucceeds()
{
var log = new RecordingLoggerProvider();
using var factory = LoggerFactory.Create(b => b.AddProvider(log));
var registry = new ControllerRegistry();
registry.RegisterController(typeof(OkController));
await using var context = new RouteContext(loggerFactory: factory);
var dispatcher = new ControllerDispatcherProcessor(registry, context, [new ThrowingFilter()]);
var exchange = new Exchange();
exchange.In.setHeader(ControllerDispatcherProcessor.PathHeader, "ok");
exchange.In.setHeader(ControllerDispatcherProcessor.MethodHeader, "GET");
await dispatcher.Process(exchange);
exchange.Out!.Body.Should().Be("fine", "a filter never breaks dispatch");
// IControllerActionFilter documents "logged but does not propagate"; a bare catch made a filter
// failing on every request indistinguishable from one that works.
log.Entries.Where(e => e.Exception is not null).Select(e => e.Exception!.Message)
.Should().Contain("filter-before-failed").And.Contain("filter-after-failed");
}
// The other half of the rule: errors the framework writes itself stay descriptive. Without this the
// leak tests alone would be satisfied by genericising 400 and 404 too, which would be a usability
// regression dressed as a security fix.
[Fact]
public async Task FrameworkErrorsKeepTheirText()
{
var registry = new ControllerRegistry();
registry.RegisterController(typeof(LeakyController));
await using var context = new RouteContext();
var dispatcher = new ControllerDispatcherProcessor(registry, context);
var missingHeaders = new Exchange();
await dispatcher.Process(missingHeaders);
var bad = (ControllerErrorResponse)missingHeaders.Out!.Body!;
bad.StatusCode.Should().Be(400);
bad.Message.Should().Contain(ControllerDispatcherProcessor.PathHeader, "the caller must learn which header is missing");
var noAction = new Exchange();
noAction.In.setHeader(ControllerDispatcherProcessor.PathHeader, "nothing/here");
noAction.In.setHeader(ControllerDispatcherProcessor.MethodHeader, "GET");
await dispatcher.Process(noAction);
var notFound = (ControllerErrorResponse)noAction.Out!.Body!;
notFound.StatusCode.Should().Be(404);
notFound.Message.Should().Contain("nothing/here", "the caller must learn what did not match");
}
private static async Task<(Exchange Exchange, RecordingLoggerProvider Log)> Dispatch(string path)
{
var log = new RecordingLoggerProvider();
using var factory = LoggerFactory.Create(b => { b.SetMinimumLevel(LogLevel.Debug); b.AddProvider(log); });
var registry = new ControllerRegistry();
registry.RegisterController(typeof(LeakyController));
await using var context = new RouteContext(loggerFactory: factory);
var dispatcher = new ControllerDispatcherProcessor(registry, context);
var exchange = new Exchange();
exchange.In.setHeader(ControllerDispatcherProcessor.PathHeader, path);
exchange.In.setHeader(ControllerDispatcherProcessor.MethodHeader, "GET");
await dispatcher.Process(exchange);
return (exchange, log);
}
private sealed class RecordingLoggerProvider : ILoggerProvider
{
public List<(LogLevel Level, string Message, Exception? Exception)> Entries { get; } = [];
public ILogger CreateLogger(string categoryName) => new Recording(this);
public void Dispose() { }
private sealed class Recording(RecordingLoggerProvider owner) : ILogger
{
public IDisposable? BeginScope(TState state) where TState : notnull => null;
public bool IsEnabled(LogLevel logLevel) => true;
public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter)
{
lock (owner.Entries) owner.Entries.Add((logLevel, formatter(state, exception), exception));
}
}
}
}
Path: redb-route/tests/redb.Route.Tests.Controllers/ControllerRegistryTests.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.Controllers/ControllerRegistryTests.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Controllers;
using redb.Route.Controllers.Attributes;
namespace redb.Route.Tests.Controllers;
public class ControllerRegistryTests
{
[Fact]
public void RegisterAssembly_discovers_controllers()
{
var registry = new ControllerRegistry();
var count = registry.RegisterAssembly(typeof(ModulesController).Assembly);
// Every controller of this assembly with HTTP-attributed actions, and nothing else: a fixture that stops
// being discovered, or a method-name fixture (EchoController, BindController, ...) that starts to be,
// shows up here. Adding a fixture with [Http*] actions means adding it to this list.
registry.Actions.Select(a => a.ControllerType).Distinct().Should().BeEquivalentTo(new[]
{
typeof(ModulesController), typeof(ContextsController), typeof(NoRouteController),
typeof(ReturnShapesController), typeof(BindingController), typeof(FilterProbeController),
typeof(SessionsLiteralFirstController), typeof(SessionsParamFirstController), typeof(SoapFareController),
typeof(ControllerBadRequestTests.OrdersController), typeof(FacadeResponseMetaController),
typeof(ControllerErrorLeakTests.LeakyController), typeof(ControllerErrorLeakTests.GrpcLeakyController),
typeof(ControllerErrorLeakTests.NestedThrowController), typeof(ControllerErrorLeakTests.OkController),
typeof(InstanceProbeController), typeof(ConstructorArgumentController),
typeof(SelfReplyController),
});
count.Should().Be(39).And.Be(registry.Actions.Count);
}
[Fact]
public void RegisterController_registers_all_attributed_methods()
{
var registry = new ControllerRegistry();
var count = registry.RegisterController(typeof(ModulesController));
count.Should().Be(5); // GetAll, GetById, Create, Delete, Update
}
[Fact]
public void Resolve_matches_simple_path()
{
var registry = new ControllerRegistry();
registry.RegisterController(typeof(ModulesController));
var action = registry.Resolve(HttpMethodType.Get, "modules", out var routeParams);
action.Should().NotBeNull();
action!.Method.Name.Should().Be("GetAll");
routeParams.Should().BeEmpty();
}
[Fact]
public void Resolve_matches_path_with_parameter()
{
var registry = new ControllerRegistry();
registry.RegisterController(typeof(ModulesController));
var action = registry.Resolve(HttpMethodType.Get, "modules/123", out var routeParams);
action.Should().NotBeNull();
action!.Method.Name.Should().Be("GetById");
routeParams.Should().ContainKey("id").WhoseValue.Should().Be("123");
}
[Fact]
public void Resolve_matches_multi_segment_template()
{
var registry = new ControllerRegistry();
registry.RegisterController(typeof(ContextsController));
var action = registry.Resolve(HttpMethodType.Post, "contexts/myctx/start", out var routeParams);
action.Should().NotBeNull();
action!.Method.Name.Should().Be("Start");
routeParams.Should().ContainKey("name").WhoseValue.Should().Be("myctx");
}
[Fact]
public void Resolve_returns_null_for_no_match()
{
var registry = new ControllerRegistry();
registry.RegisterController(typeof(ModulesController));
var action = registry.Resolve(HttpMethodType.Get, "nonexistent/path", out _);
action.Should().BeNull();
}
[Fact]
public void Resolve_by_string_method()
{
var registry = new ControllerRegistry();
registry.RegisterController(typeof(ModulesController));
var action = registry.Resolve("POST", "modules", out _);
action.Should().NotBeNull();
action!.Method.Name.Should().Be("Create");
}
[Fact]
public void Controller_without_RouteAttribute_uses_name_convention()
{
var registry = new ControllerRegistry();
registry.RegisterController(typeof(NoRouteController));
var action = registry.Resolve(HttpMethodType.Get, "noroute", out _);
action.Should().NotBeNull();
action!.Method.Name.Should().Be("Health");
}
}
Path: redb-route/tests/redb.Route.Tests.Controllers/ControllerRouteDslTests.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.Controllers/ControllerRouteDslTests.cs
----
using System.Net;
using System.Text;
using System.Text.Json;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Controllers;
using redb.Route.Controllers.Attributes;
using redb.Route.Controllers.Extensions;
using redb.Route.Grpc;
using redb.Route.Http;
using redb.Route.Soap;
using redb.Route.SignalR;
using HttpDsl = redb.Route.Http.Http;
using SignalRDsl = redb.Route.SignalR.SignalR;
using SoapDsl = redb.Route.Soap.Fluent.Soap;
namespace redb.Route.Tests.Controllers;
///
/// The DSL methods of as a route uses them: From(...).RedbXController(...)
/// on a started . The generic and direct-invoke overloads run behind direct:; every
/// transport overload runs behind its real consumer and is called through its real producer.
///
public class ControllerRouteDslTests
{
private static int FreePort() => global::redb.Route.Tests.Shared.TestPorts.Next();
private static async Task Call(RouteContext ctx, string uri, IExchange exchange)
{
var producer = ctx.GetEndpoint(uri).CreateProducer();
await producer.Start();
try
{
await producer.Process(exchange);
return exchange;
}
finally
{
await producer.Stop();
}
}
private static IExchange Request(string method, string path, object? body = null)
{
var exchange = new Exchange(new Message(body));
exchange.In.setHeader(ControllerDispatcherProcessor.MethodHeader, method);
exchange.In.setHeader(ControllerDispatcherProcessor.PathHeader, path);
return exchange;
}
private static object? Reply(IExchange exchange) => (exchange.Out ?? exchange.In).Body;
// ── Generic dispatcher ──────────────────────────────
[Fact]
public async Task RedbController_registry_dispatches_by_route_headers()
{
var registry = new ControllerRegistry();
registry.RegisterController(typeof(ModulesController));
registry.RegisterController(typeof(ContextsController));
await using var ctx = new RouteContext();
ctx.AddRoutes(r => r.From("direct://api").RedbController(registry));
await ctx.Start();
var modules = await Call(ctx, "direct://api", Request("GET", "modules/7"));
var contexts = await Call(ctx, "direct://api", Request("GET", "contexts"));
Reply(modules).Should().Be("module-7");
modules.Out!.GetHeader("status.code").Should().Be(200);
Reply(contexts).Should().BeEquivalentTo(new[] { "ctx1", "ctx2" });
}
[Fact]
public async Task RedbController_of_T_only_sees_that_controller()
{
await using var ctx = new RouteContext();
ctx.AddRoutes(r => r.From("direct://api").RedbController());
await ctx.Start();
var hit = await Call(ctx, "direct://api", Request("GET", "modules"));
var foreign = await Call(ctx, "direct://api", Request("GET", "contexts"));
Reply(hit).Should().BeEquivalentTo(new[] { "module1", "module2" });
foreign.Out!.GetHeader("status.code").Should().Be(404);
}
// ── Direct invoke: RedbController(methodName) ────
[Fact]
public async Task Direct_invoke_calls_the_named_method_and_binds_the_body()
{
await using var ctx = new RouteContext();
ctx.AddRoutes(r => r.From("direct://create").RedbController(nameof(ModulesController.Create)));
await ctx.Start();
var exchange = await Call(ctx, "direct://create",
new Exchange(new Message(new CreateModuleRequest { Name = "alpha" })));
exchange.Exception.Should().BeNull();
JsonSerializer.Serialize(Reply(exchange)).Should().Be("{\"Name\":\"alpha\",\"Created\":true}");
exchange.Out!.GetHeader("status.code").Should().Be(200);
}
[Fact]
public async Task Direct_invoke_ignores_the_route_headers()
{
await using var ctx = new RouteContext();
ctx.AddRoutes(r => r.From("direct://all").RedbController(nameof(ModulesController.GetAll)));
await ctx.Start();
// The headers point at another action; the named method is what runs.
var exchange = await Call(ctx, "direct://all", Request("DELETE", "modules/1"));
Reply(exchange).Should().BeEquivalentTo(new[] { "module1", "module2" });
}
[Fact]
public async Task Direct_invoke_awaits_a_task_and_returns_its_result()
{
await using var ctx = new RouteContext();
ctx.AddRoutes(r => r.From("direct://async").RedbController(nameof(DirectInvokeController.Greet)));
await ctx.Start();
var exchange = await Call(ctx, "direct://async", new Exchange(new Message("ann")));
Reply(exchange).Should().Be("hello ann");
}
[Fact]
public async Task Direct_invoke_of_an_async_Task_method_leaves_no_result_in_the_body()
{
await using var ctx = new RouteContext();
ctx.AddRoutes(r => r.From("direct://touch").RedbController(nameof(DirectInvokeController.Touch)));
await ctx.Start();
var exchange = await Call(ctx, "direct://touch", new Exchange(new Message("payload")));
exchange.Exception.Should().BeNull();
exchange.getProperty("touched").Should().Be(true);
// A Task has no result: the body stays what the request carried, and nothing internal to the runtime
// (the Task an async method really returns) leaks into it.
Reply(exchange).Should().Be("payload");
}
[Fact]
public async Task Direct_invoke_surfaces_the_action_exception_itself()
{
await using var ctx = new RouteContext();
ctx.AddRoutes(r => r.From("direct://boom").RedbController(nameof(DirectInvokeController.Boom)));
await ctx.Start();
var exchange = new Exchange(new Message("x"));
var act = () => Call(ctx, "direct://boom", exchange);
var thrown = (await act.Should().ThrowAsync()).Which;
// The route sees what the action threw, so OnException(typeof(...)) can match it; reflection's
// TargetInvocationException wrapper is an implementation detail of the invocation.
thrown.Should().BeOfType()
.Which.Message.Should().Be("direct-boom");
}
[Fact]
public async Task Direct_invoke_of_an_unknown_method_fails_with_its_name()
{
await using var ctx = new RouteContext();
ctx.AddRoutes(r => r.From("direct://missing").RedbController("NoSuchMethod"));
await ctx.Start();
var exchange = new Exchange(new Message("x"));
var act = () => Call(ctx, "direct://missing", exchange);
var thrown = (await act.Should().ThrowAsync()).Which;
thrown.Should().BeOfType()
.Which.Message.Should().Contain("NoSuchMethod").And.Contain(nameof(DirectInvokeController));
}
// ── Direct invoke by names and by expressions ───────
[Fact]
public async Task By_names_resolves_the_controller_and_method_from_the_registry()
{
var registry = new ControllerRegistry();
registry.RegisterController(typeof(ModulesController));
registry.RegisterController(typeof(ContextsController));
await using var ctx = new RouteContext();
ctx.AddRoutes(r => r.From("direct://named").RedbController(registry, "contexts", "list"));
await ctx.Start();
var exchange = await Call(ctx, "direct://named", new Exchange(new Message(null)));
Reply(exchange).Should().BeEquivalentTo(new[] { "ctx1", "ctx2" });
exchange.Out!.GetHeader("status.code").Should().Be(200);
}
[Fact]
public async Task By_names_fails_readably_for_an_unknown_pair()
{
var registry = new ControllerRegistry();
registry.RegisterController(typeof(ModulesController));
await using var ctx = new RouteContext();
ctx.AddRoutes(r => r.From("direct://named").RedbController(registry, "modules", "nope"));
await ctx.Start();
var exchange = new Exchange(new Message(null));
var act = () => Call(ctx, "direct://named", exchange);
var thrown = (await act.Should().ThrowAsync()).Which;
thrown.Should().BeOfType()
.Which.Message.Should().Contain("'modules'").And.Contain("'nope'");
}
[Fact]
public async Task By_expressions_picks_the_action_per_exchange()
{
var registry = new ControllerRegistry();
registry.RegisterController(typeof(ModulesController));
registry.RegisterController(typeof(ContextsController));
await using var ctx = new RouteContext();
ctx.AddRoutes(r => r.From("direct://dynamic").RedbController(registry,
e => e.In.GetHeader("ctrl")!,
e => e.In.GetHeader("action")!));
await ctx.Start();
var first = new Exchange(new Message(null));
first.In.setHeader("ctrl", "Modules");
first.In.setHeader("action", "GetAll");
var second = new Exchange(new Message(null));
second.In.setHeader("ctrl", "Contexts");
second.In.setHeader("action", "List");
await Call(ctx, "direct://dynamic", first);
await Call(ctx, "direct://dynamic", second);
Reply(first).Should().BeEquivalentTo(new[] { "module1", "module2" });
Reply(second).Should().BeEquivalentTo(new[] { "ctx1", "ctx2" });
}
// ── HTTP ─────────────────────────────────────────────
[Fact]
public async Task RedbHttpController_of_T_serves_real_http_requests()
{
var port = FreePort();
await using var server = new SharedHttpServerManager();
await using var ctx = new RouteContext();
ctx.AddComponent(new HttpComponent { ServerManager = server });
ctx.AddRoutes(r => r.From(HttpDsl.Listen("/{**path}").Host("127.0.0.1").Port(port).InOut())
.RedbHttpController());
await ctx.Start();
using var client = new HttpClient { BaseAddress = new Uri($"http://127.0.0.1:{port}") };
var get = await client.GetAsync("/modules/5");
var post = await client.PostAsync("/modules",
new StringContent("{\"name\":\"beta\"}", Encoding.UTF8, "application/json"));
var foreign = await client.GetAsync("/contexts");
get.StatusCode.Should().Be(HttpStatusCode.OK);
(await get.Content.ReadAsStringAsync()).Should().Be("module-5");
post.StatusCode.Should().Be(HttpStatusCode.OK);
(await post.Content.ReadAsStringAsync()).Should().Be("{\"name\":\"beta\",\"created\":true}");
foreign.StatusCode.Should().Be(HttpStatusCode.NotFound);
}
[Fact]
public async Task RedbHttpController_registry_serves_every_registered_controller()
{
var registry = new ControllerRegistry();
registry.RegisterController(typeof(ModulesController));
registry.RegisterController(typeof(ContextsController));
var port = FreePort();
await using var server = new SharedHttpServerManager();
await using var ctx = new RouteContext();
ctx.AddComponent(new HttpComponent { ServerManager = server });
ctx.AddRoutes(r => r.From(HttpDsl.Listen("/{**path}").Host("127.0.0.1").Port(port).InOut())
.RedbHttpController(registry));
await ctx.Start();
using var client = new HttpClient { BaseAddress = new Uri($"http://127.0.0.1:{port}") };
var modules = await client.GetStringAsync("/modules");
var status = await client.GetStringAsync("/contexts/c1/status?verbose=true");
modules.Should().Be("[\"module1\",\"module2\"]");
status.Should().Be("{\"name\":\"c1\",\"verbose\":true,\"status\":\"running\"}");
}
// ── gRPC ─────────────────────────────────────────────
private static async Task GrpcCall(RouteContext ctx, int port, string method, object? arg)
{
var body = arg is null ? Array.Empty() : JsonSerializer.SerializeToUtf8Bytes(arg);
var exchange = new Exchange(new Message(body));
exchange.In.Headers[GrpcControllerDispatcher.MethodHeader] = method;
await Call(ctx, GrpcDsl.Call($"127.0.0.1:{port}").Plaintext(), exchange);
return Encoding.UTF8.GetString((byte[])exchange.Out!.Body!);
}
[Fact]
public async Task RedbGrpcController_of_T_serves_real_grpc_calls()
{
var port = FreePort();
await using var ctx = new RouteContext();
ctx.AddComponent(new GrpcComponent());
ctx.AddRoutes(r => r.From(GrpcDsl.Listen($"127.0.0.1:{port}").InOut())
.RedbGrpcController());
await ctx.Start();
(await GrpcCall(ctx, port, "Echo", "via-dsl")).Should().Be("echo:via-dsl");
(await GrpcCall(ctx, port, "AsyncMethod", "x")).Should().Be("async:x");
}
[Fact]
public async Task RedbGrpcController_types_and_registry_dispatch_qualified_names()
{
var registry = new ControllerRegistry();
registry.RegisterController(typeof(ModulesController));
registry.RegisterController(typeof(ContextsController));
var typesPort = FreePort();
var registryPort = FreePort();
await using var ctx = new RouteContext();
ctx.AddComponent(new GrpcComponent());
ctx.AddRoutes(r =>
{
r.From(GrpcDsl.Listen($"127.0.0.1:{typesPort}").InOut())
.RedbGrpcController(typeof(EchoController), typeof(StatusController));
r.From(GrpcDsl.Listen($"127.0.0.1:{registryPort}").InOut())
.RedbGrpcController(registry);
});
await ctx.Start();
(await GrpcCall(ctx, typesPort, "Status.GetAll", null)).Should().Be("status-ok");
(await GrpcCall(ctx, typesPort, "Echo.GetAll", null)).Should().Be("[\"item1\",\"item2\"]");
(await GrpcCall(ctx, registryPort, "Contexts.List", null)).Should().Be("[\"ctx1\",\"ctx2\"]");
}
// ── SignalR ──────────────────────────────────────────
private static async Task SignalRCall(RouteContext ctx, int port, string method, object? arg)
{
var exchange = new Exchange(new Message(arg));
exchange.In.setHeader(SignalRHeaders.Method, method);
await Call(ctx, SignalRDsl.Connect($"127.0.0.1:{port}/hub").InOut(), exchange);
return exchange.Out!.Body?.ToString();
}
[Fact]
public async Task RedbSignalRController_of_T_serves_real_hub_invocations()
{
var port = FreePort();
await using var ctx = new RouteContext();
ctx.AddComponent(new SignalRComponent());
ctx.AddRoutes(r => r.From(SignalRDsl.Hub($"127.0.0.1:{port}/hub").InOut())
.RedbSignalRController());
await ctx.Start();
(await SignalRCall(ctx, port, "Echo", "via-dsl")).Should().Be("echo:via-dsl");
(await SignalRCall(ctx, port, "AsyncMethod", "x")).Should().Be("async:x");
}
[Fact]
public async Task RedbSignalRController_types_and_registry_dispatch_qualified_names()
{
var registry = new ControllerRegistry();
registry.RegisterController(typeof(ModulesController));
registry.RegisterController(typeof(ContextsController));
var typesPort = FreePort();
var registryPort = FreePort();
await using var ctx = new RouteContext();
ctx.AddComponent(new SignalRComponent());
ctx.AddRoutes(r =>
{
r.From(SignalRDsl.Hub($"127.0.0.1:{typesPort}/hub").InOut())
.RedbSignalRController(typeof(EchoController), typeof(StatusController));
r.From(SignalRDsl.Hub($"127.0.0.1:{registryPort}/hub").InOut())
.RedbSignalRController(registry);
});
await ctx.Start();
(await SignalRCall(ctx, typesPort, "Status.GetAll", null)).Should().Be("status-ok");
(await SignalRCall(ctx, registryPort, "Modules.GetById", "9")).Should().Be("module-9");
}
// ── SOAP: the two overloads the SOAP suite does not reach ──
[Fact]
public async Task RedbSoapController_types_and_registry_dispatch_by_operation()
{
var registry = new ControllerRegistry();
registry.RegisterController(typeof(SoapFareController));
var typesPort = FreePort();
var registryPort = FreePort();
await using var ctx = new RouteContext();
ctx.AddComponent(new SoapComponent());
ctx.AddRoutes(r =>
{
r.From(SoapDsl.Listen("/air").Host("127.0.0.1").Port(typesPort))
.RedbSoapController(typeof(SoapControllerDispatcherTests.AirController));
r.From(SoapDsl.Listen("/fare").Host("127.0.0.1").Port(registryPort))
.RedbSoapController(registry);
r.From("direct://air").To(SoapDsl.Call($"http://127.0.0.1:{typesPort}/air"));
r.From("direct://fare").To(SoapDsl.Call($"http://127.0.0.1:{registryPort}/fare"));
});
await ctx.Start();
var air = await Call(ctx, "direct://air",
new Exchange(new Message("JFK-LHR")));
var fare = await Call(ctx, "direct://fare",
new Exchange(new Message("JFK-LHR")));
air.Out!.Body!.ToString().Should().Contain("GetFaresResponse").And.Contain("100");
fare.Out!.Body!.ToString().Should().Contain("GetFaresResponse").And.Contain("7");
}
}
Path: redb-route/tests/redb.Route.Tests.Controllers/GrpcControllerDispatcherTests.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.Controllers/GrpcControllerDispatcherTests.cs
----
using System.Text.Json;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Controllers;
using redb.Route.Controllers.Attributes;
namespace redb.Route.Tests.Controllers;
public class GrpcControllerDispatcherTests
{
private static IExchange CreateExchange(string? method, object? body = null, bool serializeAsBytes = false)
{
var exchange = new Exchange();
if (method is not null)
exchange.In.setHeader(GrpcControllerDispatcher.MethodHeader, method);
if (body is not null)
{
if (serializeAsBytes)
exchange.In.Body = JsonSerializer.SerializeToUtf8Bytes(body);
else
exchange.In.Body = body;
}
return exchange;
}
// ── Single controller dispatch ──────────────────────
[Fact]
public async Task Dispatches_by_method_name()
{
await using var context = new RouteContext();
var dispatcher = new GrpcControllerDispatcher(context, typeof(EchoController));
var exchange = CreateExchange("Echo", "hello");
await dispatcher.Process(exchange);
exchange.Out.Should().NotBeNull();
var body = DeserializeResult(exchange.Out!.Body);
body.Should().Be("echo:hello");
exchange.Out.GetHeader("status.code").Should().Be(200);
}
[Fact]
public async Task Dispatches_no_args_method()
{
await using var context = new RouteContext();
var dispatcher = new GrpcControllerDispatcher(context, typeof(EchoController));
var exchange = CreateExchange("GetAll");
await dispatcher.Process(exchange);
exchange.Out.Should().NotBeNull();
var body = DeserializeResult(exchange.Out!.Body);
body.Should().BeEquivalentTo(new[] { "item1", "item2" });
}
[Fact]
public async Task Dispatches_with_byte_body()
{
await using var context = new RouteContext();
var dispatcher = new GrpcControllerDispatcher(context, typeof(EchoController));
// Simulate real gRPC body: byte[] containing JSON
var exchange = CreateExchange("Echo", "hello", serializeAsBytes: true);
await dispatcher.Process(exchange);
exchange.Out.Should().NotBeNull();
var body = DeserializeResult(exchange.Out!.Body);
body.Should().Be("echo:hello");
}
[Fact]
public async Task Dispatches_complex_object_from_bytes()
{
await using var context = new RouteContext();
var dispatcher = new GrpcControllerDispatcher(context, typeof(EchoController));
var request = new CreateModuleRequest { Name = "TestModule" };
var exchange = CreateExchange("Create", request, serializeAsBytes: true);
await dispatcher.Process(exchange);
exchange.Out.Should().NotBeNull();
var result = DeserializeResult(exchange.Out!.Body);
result.GetProperty("Name").GetString().Should().Be("TestModule");
result.GetProperty("Created").GetBoolean().Should().BeTrue();
}
[Fact]
public async Task Dispatches_multiple_positional_args_from_bytes()
{
await using var context = new RouteContext();
var dispatcher = new GrpcControllerDispatcher(context, typeof(EchoController));
var args = new object[] { 42, new CreateModuleRequest { Name = "Updated" } };
var exchange = CreateExchange("Update", args, serializeAsBytes: true);
await dispatcher.Process(exchange);
exchange.Out.Should().NotBeNull();
var result = DeserializeResult(exchange.Out!.Body);
result.GetProperty("Id").GetInt32().Should().Be(42);
result.GetProperty("Name").GetString().Should().Be("Updated");
result.GetProperty("Updated").GetBoolean().Should().BeTrue();
}
[Fact]
public async Task Dispatches_async_method()
{
await using var context = new RouteContext();
var dispatcher = new GrpcControllerDispatcher(context, typeof(EchoController));
var exchange = CreateExchange("AsyncMethod", "test");
await dispatcher.Process(exchange);
exchange.Out.Should().NotBeNull();
var body = DeserializeResult(exchange.Out!.Body);
body.Should().Be("async:test");
}
[Fact]
public async Task Dispatches_void_method_returns_204()
{
await using var context = new RouteContext();
var dispatcher = new GrpcControllerDispatcher(context, typeof(EchoController));
var exchange = CreateExchange("Delete", 1);
await dispatcher.Process(exchange);
exchange.Out.Should().NotBeNull();
exchange.Out!.GetHeader("status.code").Should().Be(204);
}
[Fact]
public async Task Dispatches_with_default_param()
{
await using var context = new RouteContext();
var dispatcher = new GrpcControllerDispatcher(context, typeof(EchoController));
var exchange = CreateExchange("WithDefault", "hello");
await dispatcher.Process(exchange);
exchange.Out.Should().NotBeNull();
var body = DeserializeResult(exchange.Out!.Body);
body.Should().Be("hello:5");
}
// ── Multi-controller dispatch ───────────────────────
[Fact]
public async Task Qualified_name_dispatches_to_correct_controller()
{
await using var context = new RouteContext();
var dispatcher = new GrpcControllerDispatcher(context,
typeof(EchoController), typeof(StatusController));
var exchange = CreateExchange("Status.GetAll");
await dispatcher.Process(exchange);
exchange.Out.Should().NotBeNull();
var body = DeserializeResult(exchange.Out!.Body);
body.Should().Be("status-ok");
}
[Fact]
public async Task Unqualified_name_resolves_first_registered()
{
await using var context = new RouteContext();
var dispatcher = new GrpcControllerDispatcher(context,
typeof(EchoController), typeof(StatusController));
// EchoController registered first, so its GetAll wins
var exchange = CreateExchange("GetAll");
await dispatcher.Process(exchange);
exchange.Out.Should().NotBeNull();
var body = DeserializeResult(exchange.Out!.Body);
body.Should().BeEquivalentTo(new[] { "item1", "item2" });
}
// ── Error cases ─────────────────────────────────────
[Fact]
public async Task Missing_header_returns_400()
{
await using var context = new RouteContext();
var dispatcher = new GrpcControllerDispatcher(context, typeof(EchoController));
var exchange = CreateExchange(null);
await dispatcher.Process(exchange);
exchange.Out.Should().NotBeNull();
exchange.Out!.GetHeader("status.code").Should().Be(400);
}
[Fact]
public async Task Unknown_method_returns_404()
{
await using var context = new RouteContext();
var dispatcher = new GrpcControllerDispatcher(context, typeof(EchoController));
var exchange = CreateExchange("NonExistent");
await dispatcher.Process(exchange);
exchange.Out.Should().NotBeNull();
exchange.Out!.GetHeader("status.code").Should().Be(404);
}
[Fact]
public async Task Case_insensitive_dispatch()
{
await using var context = new RouteContext();
var dispatcher = new GrpcControllerDispatcher(context, typeof(EchoController));
var exchange = CreateExchange("echo", "test");
await dispatcher.Process(exchange);
exchange.Out.Should().NotBeNull();
var body = DeserializeResult(exchange.Out!.Body);
body.Should().Be("echo:test");
}
[Fact]
public async Task Empty_byte_array_body_treated_as_null()
{
await using var context = new RouteContext();
var dispatcher = new GrpcControllerDispatcher(context, typeof(EchoController));
var exchange = CreateExchange("GetAll");
exchange.In.Body = Array.Empty();
await dispatcher.Process(exchange);
exchange.Out.Should().NotBeNull();
var body = DeserializeResult(exchange.Out!.Body);
body.Should().BeEquivalentTo(new[] { "item1", "item2" });
}
[Fact]
public void Ctor_throws_for_non_controller_type()
{
using var context = new RouteContext();
var act = () => new GrpcControllerDispatcher(context, typeof(string));
act.Should().Throw();
}
[Fact]
public void Ctor_throws_for_empty_types()
{
using var context = new RouteContext();
var act = () => new GrpcControllerDispatcher(context);
act.Should().Throw();
}
// ── JSON-object body binds BY NAME (arrays/null stay positional) ─────
[Fact]
public async Task JsonObject_FromBody_param_gets_whole_object()
{
var ex = CreateExchange("CreateBody", new CreateModuleRequest { Name = "N" }, serializeAsBytes: true);
await using var context = new RouteContext();
await new GrpcControllerDispatcher(context, typeof(BindController)).Process(ex);
DeserializeResult(ex.Out!.Body).Should().Be("N");
}
[Fact]
public async Task JsonObject_lone_complex_param_gets_whole_object() // preserves today's behavior
{
var ex = CreateExchange("CreateBare", new CreateModuleRequest { Name = "N" }, serializeAsBytes: true);
await using var context = new RouteContext();
await new GrpcControllerDispatcher(context, typeof(BindController)).Process(ex);
DeserializeResult(ex.Out!.Body).Should().Be("N");
}
[Fact]
public async Task JsonObject_binds_route_and_body_by_name() // was broken: object became id, body stayed null
{
var ex = CreateExchange("Update");
ex.In.Body = JsonSerializer.SerializeToUtf8Bytes(new { id = "X", name = "N" });
await using var context = new RouteContext();
await new GrpcControllerDispatcher(context, typeof(BindController)).Process(ex);
DeserializeResult(ex.Out!.Body).Should().Be("X|N");
}
[Fact]
public async Task JsonObject_binds_simple_by_name_and_keeps_defaults() // was broken: object couldn't become int
{
var ex = CreateExchange("List");
ex.In.Body = JsonSerializer.SerializeToUtf8Bytes(new { offset = 10 });
await using var context = new RouteContext();
await new GrpcControllerDispatcher(context, typeof(BindController)).Process(ex);
DeserializeResult(ex.Out!.Body).Should().Be("10:25");
}
[Fact]
public async Task JsonArray_body_stays_positional()
{
var ex = CreateExchange("Update", new object[] { "X", new CreateModuleRequest { Name = "N" } }, serializeAsBytes: true);
await using var context = new RouteContext();
await new GrpcControllerDispatcher(context, typeof(BindController)).Process(ex);
DeserializeResult(ex.Out!.Body).Should().Be("X|N");
}
[Fact]
public async Task JsonObject_extra_keys_do_not_break_binding()
{
var ex = CreateExchange("CreateBare");
ex.In.Body = JsonSerializer.SerializeToUtf8Bytes(new { name = "N", unexpected = "ignored" });
await using var context = new RouteContext();
await new GrpcControllerDispatcher(context, typeof(BindController)).Process(ex);
DeserializeResult(ex.Out!.Body).Should().Be("N");
}
// ── Helper ──────────────────────────────────────────
///
/// GrpcControllerDispatcher serializes results to byte[] (UTF-8 JSON).
/// This helper deserializes them back for assertions.
///
private static T DeserializeResult(object? body)
{
if (body is byte[] bytes)
return JsonSerializer.Deserialize(bytes, new JsonSerializerOptions { PropertyNameCaseInsensitive = true })!;
if (body is T typed)
return typed;
throw new InvalidOperationException($"Expected byte[] or {typeof(T).Name}, got {body?.GetType().Name ?? "null"}");
}
}
Path: redb-route/tests/redb.Route.Tests.Controllers/GrpcControllerIntegrationTests.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.Controllers/GrpcControllerIntegrationTests.cs
----
using System.Net;
using System.Text;
using System.Text.Json;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Controllers;
using redb.Route.Grpc;
using Grpc.Core;
namespace redb.Route.Tests.Controllers;
///
/// Integration tests: GrpcProducer → GrpcConsumer → GrpcControllerDispatcher → Controller → gRPC response.
/// Real gRPC connections over loopback. No mocked headers — the consumer sets method/body from the real request,
/// and the dispatch-method header flows through gRPC metadata.
///
public class GrpcControllerIntegrationTests : IAsyncLifetime
{
private GrpcConsumer? _consumer;
private GrpcProducer? _producer;
private int _port;
private RouteContext? _context;
public Task InitializeAsync()
{
_port = GetFreePort();
return Task.CompletedTask;
}
public async Task DisposeAsync()
{
if (_producer is not null) await _producer.Stop();
if (_consumer is not null) await _consumer.Stop();
if (_context is not null) await _context.DisposeAsync();
}
///
/// Creates a real gRPC consumer with GrpcControllerDispatcher,
/// and a gRPC producer (client) connected to it.
///
private async Task StartPair(params Type[] controllerTypes)
{
_context = new RouteContext();
var context = _context;
var dispatcher = new GrpcControllerDispatcher(context, controllerTypes);
// Consumer (server)
var consumerComponent = new GrpcComponent();
var consumerParams = new Dictionary
{
["host"] = "127.0.0.1",
["port"] = _port.ToString(),
["inOut"] = "true"
};
var consumerUri = new EndpointUri("grpc", $"/127.0.0.1:{_port}", $"grpc:127.0.0.1:{_port}", consumerParams);
var consumerEndpoint = (GrpcEndpoint)consumerComponent.CreateEndpoint(consumerUri);
_consumer = new GrpcConsumer(consumerEndpoint, dispatcher, consumerEndpoint.EndpointOptions);
await _consumer.Start();
// Producer (client)
var producerComponent = new GrpcComponent();
var producerParams = new Dictionary { ["plaintext"] = "true" };
var producerUri = new EndpointUri("grpc", $"/127.0.0.1:{_port}", $"grpc:127.0.0.1:{_port}", producerParams);
var producerEndpoint = (GrpcEndpoint)producerComponent.CreateEndpoint(producerUri);
_producer = new GrpcProducer(producerEndpoint, producerEndpoint.EndpointOptions);
await _producer.Start();
}
private static IExchange CreateGrpcExchange(string method, object? body = null)
{
byte[]? payload = null;
if (body is not null)
payload = JsonSerializer.SerializeToUtf8Bytes(body);
var exchange = new Exchange(new Message(payload ?? Array.Empty()));
// dispatch-method header flows through gRPC metadata (no redbGrpc.* filtering)
exchange.In.Headers[GrpcControllerDispatcher.MethodHeader] = method;
return exchange;
}
// ── Basic dispatch ──────────────────────────────────
[Fact]
public async Task Echo_via_grpc_returns_response()
{
await StartPair(typeof(EchoController));
var exchange = CreateGrpcExchange("Echo", "hello-grpc");
await _producer!.Process(exchange);
exchange.Out.Should().NotBeNull();
var body = Encoding.UTF8.GetString((byte[])exchange.Out!.Body!);
body.Should().Contain("echo:hello-grpc");
}
// ── No-args method ──────────────────────────────────
[Fact]
public async Task GetAll_via_grpc_returns_items()
{
await StartPair(typeof(EchoController));
var exchange = CreateGrpcExchange("GetAll");
await _producer!.Process(exchange);
exchange.Out.Should().NotBeNull();
var body = Encoding.UTF8.GetString((byte[])exchange.Out!.Body!);
body.Should().Contain("item1");
body.Should().Contain("item2");
}
// ── Complex object argument ─────────────────────────
[Fact]
public async Task Create_with_json_body()
{
await StartPair(typeof(EchoController));
var exchange = CreateGrpcExchange("Create", new CreateModuleRequest { Name = "GrpcModule" });
await _producer!.Process(exchange);
exchange.Out.Should().NotBeNull();
var body = Encoding.UTF8.GetString((byte[])exchange.Out!.Body!);
body.Should().Contain("GrpcModule");
}
// ── Multiple positional args ────────────────────────
[Fact]
public async Task Update_with_multiple_args()
{
await StartPair(typeof(EchoController));
var exchange = CreateGrpcExchange("Update",
new object[] { 42, new CreateModuleRequest { Name = "UpdatedViaGrpc" } });
await _producer!.Process(exchange);
exchange.Out.Should().NotBeNull();
var body = Encoding.UTF8.GetString((byte[])exchange.Out!.Body!);
body.Should().Contain("UpdatedViaGrpc");
}
// ── Async method ────────────────────────────────────
[Fact]
public async Task AsyncMethod_via_grpc()
{
await StartPair(typeof(EchoController));
var exchange = CreateGrpcExchange("AsyncMethod", "async-input");
await _producer!.Process(exchange);
exchange.Out.Should().NotBeNull();
var body = Encoding.UTF8.GetString((byte[])exchange.Out!.Body!);
body.Should().Contain("async:async-input");
}
// ── Void method returns 204 ─────────────────────────
[Fact]
public async Task Delete_void_method()
{
await StartPair(typeof(EchoController));
var exchange = CreateGrpcExchange("Delete", 1);
await _producer!.Process(exchange);
// A void action answers with no body: the request payload ("1") must not come back as the reply.
exchange.Exception.Should().BeNull();
exchange.Out.Should().NotBeNull();
(exchange.Out!.Body as byte[] ?? Array.Empty()).Should().BeEmpty();
}
// ── Multi-controller qualified dispatch ─────────────
[Fact]
public async Task Qualified_name_dispatches_correctly()
{
await StartPair(typeof(EchoController), typeof(StatusController));
var exchange = CreateGrpcExchange("Status.GetAll");
await _producer!.Process(exchange);
exchange.Out.Should().NotBeNull();
var body = Encoding.UTF8.GetString((byte[])exchange.Out!.Body!);
body.Should().Contain("status-ok");
}
// ── Unknown method returns error ────────────────────
[Fact]
public async Task Unknown_method_returns_error()
{
await StartPair(typeof(EchoController));
var exchange = CreateGrpcExchange("NonExistent");
// The dispatcher writes the transport-neutral status.code=404 that every controller dispatcher
// uses; the gRPC consumer now turns that into a real NotFound status instead of answering OK with
// an error document nobody inspects. Same outcome the SOAP dispatcher has always produced (it
// throws and the consumer emits a Fault) — the two operation-style transports finally agree.
var act = async () => await _producer!.Process(exchange);
var ex = await act.Should().ThrowAsync();
ex.Which.StatusCode.Should().Be(StatusCode.NotFound);
exchange.In.Headers[GrpcHeaders.StatusCode].Should().Be((int)StatusCode.NotFound);
}
// ── Multiple sequential requests ────────────────────
[Fact]
public async Task Multiple_requests_all_processed()
{
await StartPair(typeof(EchoController));
for (var i = 0; i < 5; i++)
{
var exchange = CreateGrpcExchange("Echo", $"msg-{i}");
await _producer!.Process(exchange);
exchange.Out.Should().NotBeNull();
var body = Encoding.UTF8.GetString((byte[])exchange.Out!.Body!);
body.Should().Contain($"echo:msg-{i}");
}
}
private static int GetFreePort() => global::redb.Route.Tests.Shared.TestPorts.Next();
}
Path: redb-route/tests/redb.Route.Tests.Controllers/GrpcMethodAttributeTests.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.Controllers/GrpcMethodAttributeTests.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Controllers;
using redb.Route.Controllers.Attributes;
namespace redb.Route.Tests.Controllers;
///
/// pins the name gRPC callers dispatch on, so renaming the C# method is
/// not a breaking change for them. Mirrors what SoapOperationAttribute does for SOAP operations.
///
public class GrpcMethodAttributeTests
{
private sealed class PinnedController : RedbController
{
[GrpcMethod("ListUsers")]
public string ListUsersV2() => "listed";
public string Plain() => "plain";
}
private static async Task Dispatch(string method)
{
await using var context = new RouteContext();
var dispatcher = new GrpcControllerDispatcher(context, typeof(PinnedController));
var exchange = new Exchange(new Message(Array.Empty()));
exchange.In.Headers[GrpcControllerDispatcher.MethodHeader] = method;
await dispatcher.Process(exchange);
// The dispatcher passes string results through verbatim and JSON-encodes everything else.
return exchange.Out!.Body switch
{
byte[] bytes => System.Text.Encoding.UTF8.GetString(bytes),
var other => other?.ToString() ?? string.Empty,
};
}
[Fact]
public async Task Attribute_name_dispatches()
{
(await Dispatch("ListUsers")).Should().Contain("listed");
(await Dispatch("Pinned.ListUsers")).Should().Contain("listed");
}
[Fact]
public async Task Csharp_name_is_no_longer_the_wire_name()
{
// The point of pinning: the method can be renamed freely because callers never used its C# name.
var exchange = new Exchange(new Message(Array.Empty()));
exchange.In.Headers[GrpcControllerDispatcher.MethodHeader] = "ListUsersV2";
await using var context = new RouteContext();
await new GrpcControllerDispatcher(context, typeof(PinnedController)).Process(exchange);
exchange.Out!.GetHeader("status.code").Should().Be(404);
}
[Fact]
public async Task Methods_without_the_attribute_keep_their_name()
{
(await Dispatch("Plain")).Should().Contain("plain");
}
}
Path: redb-route/tests/redb.Route.Tests.Controllers/HttpControllerDispatcherResponseMetaTests.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.Controllers/HttpControllerDispatcherResponseMetaTests.cs
----
using Microsoft.Extensions.Logging;
using System.Text.Json;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Controllers;
using redb.Route.Controllers.Attributes;
namespace redb.Route.Tests.Controllers;
#region Test Controllers for response-meta behavior
///
/// Mimics a facade controller that forwards to an inner exchange whose Out already carries
/// a non-default HTTP status code (e.g. set by an OnException handler). The controller
/// propagates that code to exchange.Out before returning. Dispatcher must respect it.
///
[Route("facade")]
public class FacadeResponseMetaController : RedbController
{
[HttpPost("presets-503")]
public object PresetServiceUnavailable()
{
Exchange.Out ??= Exchange.In.Clone();
Exchange.Out.setHeader("redbHttp.ResponseCode", 503);
Exchange.Out.setHeader("status.code", 503);
return new { error = "server_error", error_description = "Database temporarily unavailable." };
}
[HttpPost("presets-content-type")]
public byte[] PresetContentType()
{
Exchange.Out ??= Exchange.In.Clone();
Exchange.Out.setHeader("Content-Type", "application/scim+json");
return System.Text.Encoding.UTF8.GetBytes("{\"ok\":true}");
}
[HttpPost("sync-throws")]
public string SyncThrows()
{
// MethodInfo.Invoke wraps sync throws in TargetInvocationException.
// Dispatcher must unwrap one level only and surface THIS message.
throw new InvalidOperationException("sync-level error");
}
[HttpPost("async-throws-nested")]
public async Task AsyncThrowsNested()
{
await Task.Yield();
// Async methods surface the real exception without TIE wrapping.
// The nested InnerException is a red herring — dispatcher must NOT dereference it.
throw new InvalidOperationException(
"outer-real-error",
innerException: new System.Net.Sockets.SocketException(10061));
}
}
#endregion
public class HttpControllerDispatcherResponseMetaTests
{
private static IExchange CreateHttpExchange(string method, string path)
{
var exchange = new Exchange();
exchange.In.setHeader("redbHttp.Method", method);
exchange.In.setHeader("redbHttp.Path", path);
return exchange;
}
// ── Don't-clobber: controller-set response meta wins ─────────────────
[Fact]
public async Task WriteResult_Preserves_Preset_ResponseCode_503()
{
var registry = new ControllerRegistry();
registry.RegisterController(typeof(FacadeResponseMetaController));
await using var context = new RouteContext();
var dispatcher = new HttpControllerDispatcher(registry, context);
var exchange = CreateHttpExchange("POST", "/facade/presets-503");
await dispatcher.Process(exchange);
// Dispatcher must respect the status the controller put on Out before returning.
// Regression for B2: without this, inner OnException 5xx were silently masked as 200.
exchange.Out!.GetHeader("redbHttp.ResponseCode").Should().Be(503);
exchange.Out!.GetHeader("status.code").Should().Be(503);
}
[Fact]
public async Task WriteResult_Preserves_Preset_ContentType()
{
var registry = new ControllerRegistry();
registry.RegisterController(typeof(FacadeResponseMetaController));
await using var context = new RouteContext();
var dispatcher = new HttpControllerDispatcher(registry, context);
var exchange = CreateHttpExchange("POST", "/facade/presets-content-type");
await dispatcher.Process(exchange);
// A controller that sets Content-Type to a non-default value (e.g. application/scim+json)
// must not be overridden by the dispatcher's application/json default.
exchange.Out!.Headers["Content-Type"].Should().Be("application/scim+json");
exchange.Out!.GetHeader("redbHttp.ResponseCode").Should().Be(200);
}
// ── Exception unwrap: TIE only, never blind InnerException ───────────
// Which exception the dispatcher selects is still the subject here; only the place to observe it
// moved. Since BR-4 the response carries a generic sentence, and the exception goes to the log —
// so the log is where "the right exception was picked" is now read.
[Fact]
public async Task Sync_Exception_Is_Unwrapped_From_TargetInvocationException()
{
var (exchange, logged) = await DispatchAndCapture("/facade/sync-throws");
exchange.Out!.GetHeader("redbHttp.ResponseCode").Should().Be(500);
logged!.Message.Should().Be("sync-level error");
var json = System.Text.Encoding.UTF8.GetString((byte[])exchange.Out!.Body!);
json.Should().NotContain("sync-level error", "the caller gets a generic message (BR-4)");
}
[Fact]
public async Task Async_Exception_Is_NOT_Unwrapped_Past_Its_InnerException()
{
var (exchange, logged) = await DispatchAndCapture("/facade/async-throws-nested");
exchange.Out!.GetHeader("redbHttp.ResponseCode").Should().Be(500);
// Regression: the old `ex.InnerException ?? ex` would have surfaced the SocketException
// (connection refused) instead of the real domain-level InvalidOperationException.
// Async path: real exception is ex; InnerException is NOT unwrapped.
logged!.Message.Should().Be("outer-real-error");
}
/// Dispatches a POST and returns the exchange together with the exception the dispatcher logged.
private static async Task<(IExchange Exchange, Exception? Logged)> DispatchAndCapture(string path)
{
var capture = new ExceptionCapturingProvider();
using var factory = LoggerFactory.Create(b => b.AddProvider(capture));
var registry = new ControllerRegistry();
registry.RegisterController(typeof(FacadeResponseMetaController));
await using var context = new RouteContext(loggerFactory: factory);
var dispatcher = new HttpControllerDispatcher(registry, context);
var exchange = CreateHttpExchange("POST", path);
await dispatcher.Process(exchange);
return (exchange, capture.Exceptions.SingleOrDefault());
}
private sealed class ExceptionCapturingProvider : ILoggerProvider
{
public List Exceptions { get; } = [];
public ILogger CreateLogger(string categoryName) => new Sink(this);
public void Dispose() { }
private sealed class Sink(ExceptionCapturingProvider owner) : ILogger
{
public IDisposable? BeginScope(TState state) where TState : notnull => null;
public bool IsEnabled(LogLevel logLevel) => true;
public void Log(LogLevel level, EventId id, TState state, Exception? ex, Func formatter)
{
if (ex is not null) lock (owner.Exceptions) owner.Exceptions.Add(ex);
}
}
}
}
Path: redb-route/tests/redb.Route.Tests.Controllers/HttpControllerDispatcherTests.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.Controllers/HttpControllerDispatcherTests.cs
----
using System.Text;
using System.Text.Json;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Controllers;
using redb.Route.Controllers.Attributes;
namespace redb.Route.Tests.Controllers;
public class HttpControllerDispatcherTests
{
/// Creates an exchange that mimics what HttpConsumer produces.
private static IExchange CreateHttpExchange(
string method, string path, object? body = null,
Dictionary? queryParams = null,
Dictionary? routeParams = null)
{
var exchange = new Exchange();
// HTTP consumer stores body as byte[]
if (body is byte[] bytes)
exchange.In.Body = bytes;
else if (body is not null)
exchange.In.Body = JsonSerializer.SerializeToUtf8Bytes(body);
exchange.In.setHeader("redbHttp.Method", method);
exchange.In.setHeader("redbHttp.Path", path); // with leading /
if (queryParams is not null)
{
foreach (var (key, value) in queryParams)
exchange.In.setHeader($"redbHttp.QueryParam.{key}", value);
}
if (routeParams is not null)
{
foreach (var (key, value) in routeParams)
exchange.In.setHeader($"redbHttp.RouteParam.{key}", value);
}
return exchange;
}
// ── Basic dispatch ──────────────────────────────────
[Fact]
public async Task Dispatches_GET_to_controller()
{
var registry = new ControllerRegistry();
registry.RegisterController(typeof(ModulesController));
await using var context = new RouteContext();
var dispatcher = new HttpControllerDispatcher(registry, context);
var exchange = CreateHttpExchange("GET", "/modules");
await dispatcher.Process(exchange);
exchange.Out.Should().NotBeNull();
var json = System.Text.Encoding.UTF8.GetString((byte[])exchange.Out!.Body!);
json.Should().Contain("module1").And.Contain("module2");
exchange.Out.GetHeader("status.code").Should().Be(200);
}
[Fact]
public async Task Dispatches_GET_with_route_param()
{
var registry = new ControllerRegistry();
registry.RegisterController(typeof(ModulesController));
await using var context = new RouteContext();
var dispatcher = new HttpControllerDispatcher(registry, context);
// Path with template param — registry resolves {id} from path segments
var exchange = CreateHttpExchange("GET", "/modules/42");
await dispatcher.Process(exchange);
exchange.Out.Should().NotBeNull();
exchange.Out!.Body.Should().Be("module-42");
}
[Fact]
public async Task Dispatches_POST_with_json_body()
{
var registry = new ControllerRegistry();
registry.RegisterController(typeof(ModulesController));
await using var context = new RouteContext();
var dispatcher = new HttpControllerDispatcher(registry, context);
// HTTP consumer serializes body as byte[]
var exchange = CreateHttpExchange("POST", "/modules",
new CreateModuleRequest { Name = "test-module" });
await dispatcher.Process(exchange);
exchange.Out.Should().NotBeNull();
exchange.Out!.GetHeader("status.code").Should().Be(200);
// The body was bound (the name made it into the action) and the reply is the created object.
Encoding.UTF8.GetString((byte[])exchange.Out.Body!).Should().Be("{\"name\":\"test-module\",\"created\":true}");
}
[Fact]
public async Task Dispatches_DELETE_returns_204()
{
var registry = new ControllerRegistry();
registry.RegisterController(typeof(ModulesController));
await using var context = new RouteContext();
var dispatcher = new HttpControllerDispatcher(registry, context);
var exchange = CreateHttpExchange("DELETE", "/modules/42");
await dispatcher.Process(exchange);
exchange.Out.Should().NotBeNull();
exchange.Out!.GetHeader("status.code").Should().Be(204);
}
[Fact]
public async Task Dispatches_PUT_with_route_and_body()
{
var registry = new ControllerRegistry();
registry.RegisterController(typeof(ModulesController));
await using var context = new RouteContext();
var dispatcher = new HttpControllerDispatcher(registry, context);
var exchange = CreateHttpExchange("PUT", "/modules/7",
new CreateModuleRequest { Name = "updated" });
await dispatcher.Process(exchange);
exchange.Out.Should().NotBeNull();
exchange.Out!.GetHeader("status.code").Should().Be(200);
}
// ── Query parameters ────────────────────────────────
[Fact]
public async Task Resolves_query_parameter_from_http_headers()
{
var registry = new ControllerRegistry();
registry.RegisterController(typeof(ContextsController));
await using var context = new RouteContext();
var dispatcher = new HttpControllerDispatcher(registry, context);
var exchange = CreateHttpExchange("GET", "/contexts/myctx/status",
queryParams: new Dictionary { ["verbose"] = "true" });
await dispatcher.Process(exchange);
exchange.Out.Should().NotBeNull();
exchange.Out!.GetHeader("status.code").Should().Be(200);
}
// ── Multi-segment templates ─────────────────────────
[Fact]
public async Task Dispatches_multi_segment_with_param()
{
var registry = new ControllerRegistry();
registry.RegisterController(typeof(ContextsController));
await using var context = new RouteContext();
var dispatcher = new HttpControllerDispatcher(registry, context);
var exchange = CreateHttpExchange("POST", "/contexts/myctx/start");
await dispatcher.Process(exchange);
exchange.Out.Should().NotBeNull();
exchange.Out!.GetHeader("status.code").Should().Be(200);
}
// ── Error cases ─────────────────────────────────────
[Fact]
public async Task Returns_404_for_unknown_path()
{
var registry = new ControllerRegistry();
registry.RegisterController(typeof(ModulesController));
await using var context = new RouteContext();
var dispatcher = new HttpControllerDispatcher(registry, context);
var exchange = CreateHttpExchange("GET", "/nonexistent");
await dispatcher.Process(exchange);
exchange.Out.Should().NotBeNull();
exchange.Out!.GetHeader("status.code").Should().Be(404);
exchange.Out!.Body.Should().BeOfType();
var errorJson = System.Text.Encoding.UTF8.GetString((byte[])exchange.Out!.Body!);
errorJson.Should().Contain("NotFound");
}
[Fact]
public async Task Returns_400_for_missing_http_headers()
{
var registry = new ControllerRegistry();
registry.RegisterController(typeof(ModulesController));
await using var context = new RouteContext();
var dispatcher = new HttpControllerDispatcher(registry, context);
var exchange = new Exchange(); // no redbHttp.* headers at all
await dispatcher.Process(exchange);
exchange.Out.Should().NotBeNull();
exchange.Out!.GetHeader("status.code").Should().Be(400);
}
[Fact]
public async Task Returns_404_for_wrong_method()
{
var registry = new ControllerRegistry();
registry.RegisterController(typeof(ModulesController));
await using var context = new RouteContext();
var dispatcher = new HttpControllerDispatcher(registry, context);
// PATCH /modules doesn't exist
var exchange = CreateHttpExchange("PATCH", "/modules");
await dispatcher.Process(exchange);
exchange.Out.Should().NotBeNull();
exchange.Out!.GetHeader("status.code").Should().Be(404);
}
// ── Body deserialization ────────────────────────────
[Fact]
public async Task Deserializes_json_body_from_bytes()
{
var registry = new ControllerRegistry();
registry.RegisterController(typeof(ModulesController));
await using var context = new RouteContext();
var dispatcher = new HttpControllerDispatcher(registry, context);
// Simulate raw JSON bytes as HTTP consumer would provide
var jsonBytes = Encoding.UTF8.GetBytes("""{"name":"from-bytes"}""");
var exchange = CreateHttpExchange("POST", "/modules", jsonBytes);
await dispatcher.Process(exchange);
exchange.Out.Should().NotBeNull();
exchange.Out!.GetHeader("status.code").Should().Be(200);
}
// ── Controller convention (no [Route]) ──────────────
[Fact]
public async Task Dispatches_to_controller_without_route_attribute()
{
var registry = new ControllerRegistry();
registry.RegisterController(typeof(NoRouteController));
await using var context = new RouteContext();
var dispatcher = new HttpControllerDispatcher(registry, context);
var exchange = CreateHttpExchange("GET", "/noroute");
await dispatcher.Process(exchange);
exchange.Out.Should().NotBeNull();
exchange.Out!.Body.Should().Be("ok");
}
// ── Path normalization ──────────────────────────────
[Fact]
public async Task Strips_leading_slash_from_path()
{
var registry = new ControllerRegistry();
registry.RegisterController(typeof(ModulesController));
await using var context = new RouteContext();
var dispatcher = new HttpControllerDispatcher(registry, context);
// Both /modules and modules should work
var exchange1 = CreateHttpExchange("GET", "/modules");
await dispatcher.Process(exchange1);
exchange1.Out!.GetHeader("status.code").Should().Be(200);
var exchange2 = CreateHttpExchange("GET", "modules");
await dispatcher.Process(exchange2);
exchange2.Out!.GetHeader("status.code").Should().Be(200);
}
// ── Dual-write: redbHttp.ResponseCode ───────────────
[Fact]
public async Task WriteResult_Sets_HttpResponseCode_200()
{
var registry = new ControllerRegistry();
registry.RegisterController(typeof(ModulesController));
await using var context = new RouteContext();
var dispatcher = new HttpControllerDispatcher(registry, context);
var exchange = CreateHttpExchange("GET", "/modules");
await dispatcher.Process(exchange);
exchange.Out!.GetHeader(HttpControllerDispatcher.HttpResponseCodeHeader).Should().Be(200);
}
[Fact]
public async Task WriteResult_Null_Sets_HttpResponseCode_204()
{
var registry = new ControllerRegistry();
registry.RegisterController(typeof(ModulesController));
await using var context = new RouteContext();
var dispatcher = new HttpControllerDispatcher(registry, context);
var exchange = CreateHttpExchange("DELETE", "/modules/1");
await dispatcher.Process(exchange);
exchange.Out!.GetHeader(HttpControllerDispatcher.HttpResponseCodeHeader).Should().Be(204);
}
[Fact]
public async Task WriteError_Sets_HttpResponseCode_404()
{
var registry = new ControllerRegistry();
registry.RegisterController(typeof(ModulesController));
await using var context = new RouteContext();
var dispatcher = new HttpControllerDispatcher(registry, context);
var exchange = CreateHttpExchange("GET", "/nonexistent");
await dispatcher.Process(exchange);
exchange.Out!.GetHeader(HttpControllerDispatcher.HttpResponseCodeHeader).Should().Be(404);
}
[Fact]
public async Task WriteError_MissingHeaders_Sets_HttpResponseCode_400()
{
var registry = new ControllerRegistry();
registry.RegisterController(typeof(ModulesController));
await using var context = new RouteContext();
var dispatcher = new HttpControllerDispatcher(registry, context);
var exchange = new Exchange(); // no method/path headers
await dispatcher.Process(exchange);
exchange.Out!.GetHeader(HttpControllerDispatcher.HttpResponseCodeHeader).Should().Be(400);
}
}
Path: redb-route/tests/redb.Route.Tests.Controllers/HttpControllerIntegrationTests.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.Controllers/HttpControllerIntegrationTests.cs
----
using System.Net;
using System.Net.Http.Json;
using System.Text;
using System.Text.Json;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Controllers;
using redb.Route.Controllers.Attributes;
using redb.Route.Http;
namespace redb.Route.Tests.Controllers;
///
/// Integration tests: real HTTP request → HttpConsumer → HttpControllerDispatcher → Controller → HTTP response.
/// No mocked headers — the HTTP consumer sets redbHttp.Method, redbHttp.Path, etc. from the real HTTP request.
/// Uses raw HttpClient on the producer side for full realism.
///
public class HttpControllerIntegrationTests : IAsyncLifetime
{
private HttpConsumer? _consumer;
private HttpClient? _httpClient;
private int _port;
private RouteContext? _context;
private SharedHttpServerManager? _serverManager;
private string _baseUrl = "";
public Task InitializeAsync()
{
_port = GetFreePort();
_serverManager = new SharedHttpServerManager();
return Task.CompletedTask;
}
public async Task DisposeAsync()
{
_httpClient?.Dispose();
if (_consumer is not null) await _consumer.Stop();
if (_context is not null) await _context.DisposeAsync();
if (_serverManager is not null) await _serverManager.DisposeAsync();
}
///
/// Creates a real HTTP consumer with HttpControllerDispatcher,
/// listening on a catch-all route so any path reaches the dispatcher.
///
private async Task StartConsumer(ControllerRegistry registry)
{
_context = new RouteContext();
var context = _context;
var dispatcher = new HttpControllerDispatcher(registry, context);
var component = new HttpComponent();
// Use {**path} catch-all so all incoming paths reach the dispatcher
var consumerPath = $"/127.0.0.1:{_port}/{{**path}}";
var consumerParams = new Dictionary
{
["host"] = "127.0.0.1",
["port"] = _port.ToString(),
["inOut"] = "true"
};
var consumerUri = new EndpointUri("http", consumerPath, $"http:{consumerPath}", consumerParams);
var consumerEndpoint = (HttpEndpoint)component.CreateEndpoint(consumerUri);
_consumer = new HttpConsumer(consumerEndpoint, dispatcher, consumerEndpoint.EndpointOptions, _serverManager!);
await _consumer.Start();
_baseUrl = $"http://127.0.0.1:{_port}";
_httpClient = new HttpClient { BaseAddress = new Uri(_baseUrl) };
}
// ── GET — list items ────────────────────────────────
[Fact]
public async Task GET_modules_returns_list()
{
var registry = new ControllerRegistry();
registry.RegisterController(typeof(ModulesController));
await StartConsumer(registry);
var response = await _httpClient!.GetAsync("/modules");
response.StatusCode.Should().Be(HttpStatusCode.OK);
var body = await response.Content.ReadAsStringAsync();
var items = JsonSerializer.Deserialize(body);
items.Should().BeEquivalentTo(new[] { "module1", "module2" });
}
// ── GET with route param ────────────────────────────
[Fact]
public async Task GET_modules_by_id_returns_item()
{
var registry = new ControllerRegistry();
registry.RegisterController(typeof(ModulesController));
await StartConsumer(registry);
var response = await _httpClient!.GetAsync("/modules/42");
response.StatusCode.Should().Be(HttpStatusCode.OK);
var body = await response.Content.ReadAsStringAsync();
body.Should().Contain("module-42");
}
// ── POST with JSON body ─────────────────────────────
[Fact]
public async Task POST_modules_creates_item()
{
var registry = new ControllerRegistry();
registry.RegisterController(typeof(ModulesController));
await StartConsumer(registry);
var response = await _httpClient!.PostAsJsonAsync("/modules",
new CreateModuleRequest { Name = "NewModule" });
response.StatusCode.Should().Be(HttpStatusCode.OK);
var body = await response.Content.ReadAsStringAsync();
body.Should().Contain("NewModule");
}
// ── PUT with route param and body ───────────────────
[Fact]
public async Task PUT_modules_updates_item()
{
var registry = new ControllerRegistry();
registry.RegisterController(typeof(ModulesController));
await StartConsumer(registry);
var response = await _httpClient!.PutAsJsonAsync("/modules/99",
new CreateModuleRequest { Name = "Updated" });
response.StatusCode.Should().Be(HttpStatusCode.OK);
var body = await response.Content.ReadAsStringAsync();
body.Should().Contain("Updated");
}
// ── DELETE ──────────────────────────────────────────
[Fact]
public async Task DELETE_modules_returns_success()
{
var registry = new ControllerRegistry();
registry.RegisterController(typeof(ModulesController));
await StartConsumer(registry);
var response = await _httpClient!.DeleteAsync("/modules/77");
response.StatusCode.Should().Be(HttpStatusCode.NoContent);
}
// ── Query params ────────────────────────────────────
[Fact]
public async Task GET_with_query_params()
{
var registry = new ControllerRegistry();
registry.RegisterController(typeof(ContextsController));
await StartConsumer(registry);
var response = await _httpClient!.GetAsync("/contexts/myctx/status?verbose=true");
response.StatusCode.Should().Be(HttpStatusCode.OK);
var body = await response.Content.ReadAsStringAsync();
body.Should().Contain("myctx");
// The query value reached the action, not only the path: an unbound bool is false and still answers 200.
body.Should().Contain("\"verbose\":true");
}
// ── 404 for unknown route ───────────────────────────
[Fact]
public async Task Unknown_route_returns_response_with_error()
{
var registry = new ControllerRegistry();
registry.RegisterController(typeof(ModulesController));
await StartConsumer(registry);
var response = await _httpClient!.GetAsync("/nonexistent");
response.StatusCode.Should().Be(HttpStatusCode.NotFound);
var body = await response.Content.ReadAsStringAsync();
body.Should().Contain("NotFound");
}
// ── Multiple controllers ────────────────────────────
[Fact]
public async Task Multiple_controllers_dispatch_correctly()
{
var registry = new ControllerRegistry();
registry.RegisterController(typeof(ModulesController));
registry.RegisterController(typeof(ContextsController));
await StartConsumer(registry);
var modulesResponse = await _httpClient!.GetAsync("/modules");
var contextsResponse = await _httpClient!.GetAsync("/contexts");
modulesResponse.StatusCode.Should().Be(HttpStatusCode.OK);
contextsResponse.StatusCode.Should().Be(HttpStatusCode.OK);
var modulesBody = await modulesResponse.Content.ReadAsStringAsync();
var contextsBody = await contextsResponse.Content.ReadAsStringAsync();
modulesBody.Should().Contain("module1");
contextsBody.Should().Contain("ctx1");
}
private static int GetFreePort() => global::redb.Route.Tests.Shared.TestPorts.Next();
}
Path: redb-route/tests/redb.Route.Tests.Controllers/ParameterBindingTests.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.Controllers/ParameterBindingTests.cs
----
using System.Globalization;
using System.Text;
using System.Text.Json;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Controllers;
using redb.Route.Controllers.Attributes;
namespace redb.Route.Tests.Controllers;
///
/// Every binding source the attributes declare, checked by the VALUE the action received (it echoes it back),
/// on the generic dispatcher (query.* headers) and on the HTTP dispatcher (redbHttp.QueryParam.*).
/// A status-only check passes with a broken binding: an unbound bool is simply false.
///
public class ParameterBindingTests
{
private static ControllerRegistry Registry()
{
var registry = new ControllerRegistry();
registry.RegisterController(typeof(BindingController));
return registry;
}
private static async Task