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 Generic(IExchange exchange, string method, string path) { exchange.In.setHeader(ControllerDispatcherProcessor.MethodHeader, method); exchange.In.setHeader(ControllerDispatcherProcessor.PathHeader, path); await using var context = new RouteContext(); await new ControllerDispatcherProcessor(Registry(), context).Process(exchange); exchange.Out!.GetHeader("status.code").Should().Be(200); return exchange.Out.Body; } private static async Task Http(IExchange exchange, string method, string path, System.Text.Json.JsonSerializerOptions? jsonOptions = null) { exchange.In.setHeader(HttpControllerDispatcher.HttpMethodHeader, method); exchange.In.setHeader(HttpControllerDispatcher.HttpPathHeader, path); exchange.In.Body ??= Array.Empty(); await using var context = new RouteContext(); await new HttpControllerDispatcher(Registry(), context, jsonOptions).Process(exchange); exchange.Out!.GetHeader("status.code").Should().Be(200); return exchange.Out.Body is byte[] bytes ? Encoding.UTF8.GetString(bytes) : exchange.Out.Body!.ToString()!; } // ── [FromHeader] ──────────────────────────────────── [Fact] public async Task FromHeader_binds_the_named_header_and_converts_it() { IExchange exchange = new Exchange(); exchange.In.setHeader("X-Tenant", "acme"); exchange.In.setHeader("X-Limit", "25"); (await Generic(exchange, "GET", "binding/header")).Should().Be("acme:25"); } [Fact] public async Task FromHeader_missing_takes_the_parameter_default_or_the_type_default() { IExchange exchange = new Exchange(); // tenant has no default (string → null), limit declares 10. (await Generic(exchange, "GET", "binding/header")).Should().Be(":10"); } [Fact] public async Task FromHeader_binds_on_the_http_dispatcher_too() { IExchange exchange = new Exchange(); exchange.In.setHeader("X-Tenant", "acme"); (await Http(exchange, "GET", "/binding/header")).Should().Be("acme:10"); } // ── [FromProperty] ────────────────────────────────── [Fact] public async Task FromProperty_binds_the_exchange_property_and_converts_it() { IExchange exchange = new Exchange(); exchange.setProperty("user", "alice"); exchange.setProperty("attempt", "3"); (await Generic(exchange, "GET", "binding/property")).Should().Be("alice:3"); } [Fact] public async Task FromProperty_missing_is_the_type_default() { (await Generic(new Exchange(), "GET", "binding/property")).Should().Be(":0"); } [Fact] public async Task FromProperty_binds_on_the_http_dispatcher_too() { IExchange exchange = new Exchange(); exchange.setProperty("user", "bob"); exchange.setProperty("attempt", 7); (await Http(exchange, "GET", "/binding/property")).Should().Be("bob:7"); } // ── [FromQuery] values ────────────────────────────── [Fact] public async Task FromQuery_binds_the_value_on_the_generic_dispatcher() { IExchange exchange = new Exchange(); exchange.In.setHeader("query.verbose", "true"); exchange.In.setHeader("query.page", "4"); (await Generic(exchange, "GET", "binding/query")).Should().Be("True:4"); } [Fact] public async Task FromQuery_binds_the_value_on_the_http_dispatcher() { IExchange exchange = new Exchange(); exchange.In.setHeader($"{HttpControllerDispatcher.QueryParamPrefix}verbose", "true"); (await Http(exchange, "GET", "/binding/query")).Should().Be("True:1"); } // ── Simple types other than int/bool/Guid ─────────── public static IEnumerable Cultures() => [["en-US"], ["ru-RU"], ["de-DE"]]; [Theory] [MemberData(nameof(Cultures))] public async Task Simple_types_bind_invariantly_whatever_the_thread_culture(string culture) { var previous = CultureInfo.CurrentCulture; CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo(culture); try { var id = Guid.NewGuid(); var exchange = new Exchange(); exchange.In.setHeader($"{HttpControllerDispatcher.QueryParamPrefix}at", "2026-09-30T10:15:00"); exchange.In.setHeader($"{HttpControllerDispatcher.QueryParamPrefix}offset", "2026-09-30T10:15:00+03:00"); exchange.In.setHeader($"{HttpControllerDispatcher.QueryParamPrefix}amount", "12.5"); exchange.In.setHeader($"{HttpControllerDispatcher.QueryParamPrefix}priority", "high"); exchange.In.setHeader($"{HttpControllerDispatcher.QueryParamPrefix}id", id.ToString()); var json = await Http(exchange, "GET", "/binding/types"); var bound = JsonSerializer.Deserialize(json, new JsonSerializerOptions(JsonSerializerDefaults.Web))!; using var scope = new AwesomeAssertions.Execution.AssertionScope(); bound.At.Should().Be(new DateTime(2026, 9, 30, 10, 15, 0)); bound.Offset.Should().Be(new DateTimeOffset(2026, 9, 30, 10, 15, 0, TimeSpan.FromHours(3))); bound.Amount.Should().Be(12.5m); bound.Priority.Should().Be(BindingPriority.High); bound.Id.Should().Be(id); } finally { CultureInfo.CurrentCulture = previous; } } // ── [HttpPatch] ───────────────────────────────────── [Fact] public async Task Patch_resolves_and_binds_route_and_body() { Registry().Resolve(HttpMethodType.Patch, "binding/9", out var routeParams)! .Method.Name.Should().Be(nameof(BindingController.Patch)); routeParams["id"].Should().Be("9"); IExchange exchange = new Exchange(new Message(JsonSerializer.SerializeToUtf8Bytes(new { name = "renamed" }))); (await Http(exchange, "PATCH", "/binding/9")).Should().Be("patched 9:renamed"); } // ── HttpControllerDispatcher(jsonOptions) ─────────── [Fact] public async Task Custom_json_options_shape_both_the_request_and_the_reply() { var snake = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower }; IExchange exchange = new Exchange(new Message(Encoding.UTF8.GetBytes("{\"module_name\":\"core\"}"))); (await Http(exchange, "POST", "/binding/options", snake)) .Should().Be("{\"module_name\":\"core\",\"is_created\":true}"); } [Fact] public async Task Default_json_options_are_camel_case() { IExchange exchange = new Exchange(new Message(Encoding.UTF8.GetBytes("{\"moduleName\":\"core\"}"))); (await Http(exchange, "POST", "/binding/options")) .Should().Be("{\"moduleName\":\"core\",\"isCreated\":true}"); } } Path: redb-route/tests/redb.Route.Tests.Controllers/ParameterResolverTests.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/ParameterResolverTests.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 ParameterResolverTests { [Fact] public void ConvertValue_handles_guid() { var guid = Guid.NewGuid(); var result = ParameterResolver.ConvertValue(guid.ToString(), typeof(Guid)); result.Should().Be(guid); } [Fact] public void ConvertValue_handles_int() { var result = ParameterResolver.ConvertValue("42", typeof(int)); result.Should().Be(42); } [Fact] public void ConvertValue_handles_bool() { var result = ParameterResolver.ConvertValue("true", typeof(bool)); result.Should().Be(true); } [Fact] public void ConvertValue_handles_null_for_reference_type() { var result = ParameterResolver.ConvertValue(null, typeof(string)); result.Should().BeNull(); } [Fact] public void ConvertValue_handles_null_for_value_type() { var result = ParameterResolver.ConvertValue(null, typeof(int)); result.Should().Be(0); } } public class PositionalParameterResolverTests { private static System.Reflection.MethodInfo GetMethod(string name) => typeof(T).GetMethod(name, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance)!; [Fact] public void Resolves_no_params_with_null_body() { var method = GetMethod("GetAll"); var result = ParameterResolver.ResolvePositional(method, null); result.Should().BeEmpty(); } [Fact] public void Resolves_single_string_arg() { var method = GetMethod("Echo"); var result = ParameterResolver.ResolvePositional(method, "hello"); result.Should().HaveCount(1); result[0].Should().Be("hello"); } [Fact] public void Resolves_single_int_arg_with_type_conversion() { var method = GetMethod("GetById"); // SignalR may send int as long (JSON protocol) var result = ParameterResolver.ResolvePositional(method, 42L); result.Should().HaveCount(1); result[0].Should().Be(42); } [Fact] public void Resolves_multiple_positional_args() { var method = GetMethod("Update"); var body = new object[] { 7, new CreateModuleRequest { Name = "test" } }; var result = ParameterResolver.ResolvePositional(method, body); result.Should().HaveCount(2); result[0].Should().Be(7); result[1].Should().BeOfType(); } [Fact] public void Uses_default_value_for_missing_args() { var method = GetMethod("WithDefault"); var result = ParameterResolver.ResolvePositional(method, "hello"); result.Should().HaveCount(2); result[0].Should().Be("hello"); result[1].Should().Be(5); // default value } [Fact] public void Injects_CancellationToken() { var method = GetMethod("WithCancellation"); using var cts = new CancellationTokenSource(); var result = ParameterResolver.ResolvePositional(method, "test", cts.Token); result.Should().HaveCount(2); result[0].Should().Be("test"); result[1].Should().Be(cts.Token); } [Fact] public void Handles_all_null_args_for_reference_params() { var method = GetMethod("Echo"); var result = ParameterResolver.ResolvePositional(method, null); result.Should().HaveCount(1); result[0].Should().BeNull(); // string param, no value } } public class ConvertValueFailureTests { [Theory] [InlineData("abc", typeof(int))] [InlineData("12,5x", typeof(decimal))] [InlineData("yes-please", typeof(bool))] [InlineData("not-a-guid", typeof(Guid))] [InlineData("medium", typeof(BindingPriority))] [InlineData("soon", typeof(DateTimeOffset))] public void A_value_that_does_not_convert_is_an_error_naming_it(string value, Type target) { var act = () => ParameterResolver.ConvertValue(value, target, "p"); act.Should().Throw() .Which.Message.Should().Contain("'p'").And.Contain(value).And.Contain(target.Name); } [Fact] public void A_missing_value_is_still_the_type_default_not_an_error() { ParameterResolver.ConvertValue(null, typeof(int), "p").Should().Be(0); } } Path: redb-route/tests/redb.Route.Tests.Controllers/ReadmePromiseTests.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/ReadmePromiseTests.cs ---- using System.Text; using System.Text.Json; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Controllers; using redb.Route.Controllers.Extensions; using redb.Route.Grpc; using redb.Route.Http; using HttpDsl = redb.Route.Http.Http; namespace redb.Route.Tests.Controllers; /// /// What the package README promises about controllers themselves: an instance per request created by /// Activator.CreateInstance() with no constructor injection, and one controller class serving any transport. /// public class ReadmePromiseTests { 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 Every_request_gets_its_own_controller_instance_bound_to_its_own_exchange() { var registry = new ControllerRegistry(); registry.RegisterController(typeof(InstanceProbeController)); await using var context = new RouteContext(); var dispatcher = new ControllerDispatcherProcessor(registry, context); var first = Get("instance"); var second = Get("instance"); await dispatcher.Process(first); await dispatcher.Process(second); var (firstInstance, firstExchange) = Split(first.Out!.Body); var (secondInstance, secondExchange) = Split(second.Out!.Body); firstInstance.Should().NotBe(secondInstance, "the same dispatcher must not reuse a controller"); firstExchange.Should().Be(first.ExchangeId); secondExchange.Should().Be(second.ExchangeId); static (string Instance, string Exchange) Split(object? body) { var parts = ((string)body!).Split('|'); return (parts[0], parts[1]); } } [Fact] public async Task A_controller_with_constructor_parameters_is_not_injected_and_fails_as_a_500() { var registry = new ControllerRegistry(); registry.RegisterController(typeof(ConstructorArgumentController)); await using var context = new RouteContext(); var exchange = Get("ctor-arg"); await new ControllerDispatcherProcessor(registry, context).Process(exchange); // No DI: Activator.CreateInstance needs a parameterless constructor. The failure is the dispatcher's // generic 500, not a half-built controller. exchange.Out!.GetHeader("status.code").Should().Be(500); exchange.Out.Body.Should().BeOfType(); } [Fact] public async Task One_controller_class_serves_http_and_grpc_in_one_context() { var httpPort = global::redb.Route.Tests.Shared.TestPorts.Next(); var grpcPort = global::redb.Route.Tests.Shared.TestPorts.Next(); await using var server = new SharedHttpServerManager(); await using var ctx = new RouteContext(); ctx.AddComponent(new HttpComponent { ServerManager = server }); ctx.AddComponent(new GrpcComponent()); ctx.AddRoutes(r => { r.From(HttpDsl.Listen("/{**path}").Host("127.0.0.1").Port(httpPort).InOut()) .RedbHttpController(); r.From(GrpcDsl.Listen($"127.0.0.1:{grpcPort}").InOut()) .RedbGrpcController(); }); await ctx.Start(); using var client = new HttpClient { BaseAddress = new Uri($"http://127.0.0.1:{httpPort}") }; var viaHttp = await client.GetStringAsync("/modules/7"); var grpc = new Exchange(new Message(JsonSerializer.SerializeToUtf8Bytes("7"))); grpc.In.Headers[GrpcControllerDispatcher.MethodHeader] = nameof(ModulesController.GetById); var producer = ctx.GetEndpoint(GrpcDsl.Call($"127.0.0.1:{grpcPort}").Plaintext()).CreateProducer(); await producer.Start(); try { await producer.Process(grpc); } finally { await producer.Stop(); } var viaGrpc = Encoding.UTF8.GetString((byte[])grpc.Out!.Body!); // The same action, the same answer; only the transport differs. viaHttp.Should().Be("module-7"); viaGrpc.Should().Be("module-7"); } } Path: redb-route/tests/redb.Route.Tests.Controllers/RouteRankingTests.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/RouteRankingTests.cs ---- using redb.Route.Controllers; using redb.Route.Controllers.Attributes; namespace redb.Route.Tests.Controllers; /// /// ranks a literal /// segment above a {param} at the same depth. The table is a ConcurrentBag with no defined order, so /// both declaration orders are pinned: without the ranking one of them resolves the literal to the placeholder. /// public class RouteRankingTests { public static IEnumerable Controllers() => [ [typeof(SessionsLiteralFirstController), "sessions-literal-first"], [typeof(SessionsParamFirstController), "sessions-param-first"], ]; [Theory] [MemberData(nameof(Controllers))] public void A_literal_segment_wins_over_a_placeholder(Type controller, string basePath) { var registry = new ControllerRegistry(); registry.RegisterController(controller); var action = registry.Resolve(HttpMethodType.Delete, $"{basePath}/current", out var routeParams); action!.Method.Name.Should().Be("DeleteCurrent"); routeParams.Should().BeEmpty(); } [Theory] [MemberData(nameof(Controllers))] public void Any_other_value_goes_to_the_placeholder(Type controller, string basePath) { var registry = new ControllerRegistry(); registry.RegisterController(controller); var action = registry.Resolve(HttpMethodType.Delete, $"{basePath}/abc", out var routeParams); action!.Method.Name.Should().Be("DeleteById"); routeParams.Should().ContainKey("sessionId").WhoseValue.Should().Be("abc"); } [Fact] public void The_literal_wins_whichever_controller_was_registered_first() { // Registration order is what fills the bag; both orders must agree. foreach (var order in new[] { new[] { 0, 1 }, new[] { 1, 0 } }) { var registry = new ControllerRegistry(); foreach (var i in order) registry.RegisterController(i == 0 ? typeof(SessionsLiteralFirstController) : typeof(SessionsParamFirstController)); registry.Resolve(HttpMethodType.Delete, "sessions-literal-first/current", out _)!.Method.Name.Should().Be("DeleteCurrent"); registry.Resolve(HttpMethodType.Delete, "sessions-param-first/current", out _)!.Method.Name.Should().Be("DeleteCurrent"); } } } Path: redb-route/tests/redb.Route.Tests.Controllers/SignalRControllerDispatcherTests.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/SignalRControllerDispatcherTests.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Controllers; namespace redb.Route.Tests.Controllers; public class SignalRControllerDispatcherTests { private static IExchange CreateExchange(string? method, object? body = null) { var exchange = new Exchange(); if (method is not null) exchange.In.setHeader("redbSignalR.Method", method); if (body is not null) 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 SignalRControllerDispatcher(context, typeof(EchoController)); var exchange = CreateExchange("Echo", "hello"); await dispatcher.Process(exchange); exchange.Out.Should().NotBeNull(); exchange.Out!.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 SignalRControllerDispatcher(context, typeof(EchoController)); var exchange = CreateExchange("GetAll"); await dispatcher.Process(exchange); exchange.Out.Should().NotBeNull(); exchange.Out!.Body.Should().BeEquivalentTo(new[] { "item1", "item2" }); } [Fact] public async Task Dispatches_single_primitive_arg() { await using var context = new RouteContext(); var dispatcher = new SignalRControllerDispatcher(context, typeof(EchoController)); var exchange = CreateExchange("GetById", 42); await dispatcher.Process(exchange); exchange.Out.Should().NotBeNull(); exchange.Out!.Body.Should().BeEquivalentTo(new { Id = 42, Name = "item-42" }); } [Fact] public async Task Dispatches_complex_body_arg() { await using var context = new RouteContext(); var dispatcher = new SignalRControllerDispatcher(context, typeof(EchoController)); var exchange = CreateExchange("Create", new CreateModuleRequest { Name = "test" }); await dispatcher.Process(exchange); exchange.Out.Should().NotBeNull(); exchange.Out!.Body.Should().BeEquivalentTo(new { Name = "test", Created = true }); } [Fact] public async Task Dispatches_multiple_positional_args() { await using var context = new RouteContext(); var dispatcher = new SignalRControllerDispatcher(context, typeof(EchoController)); // Multiple args come as object[] from RedbBridgeHub var exchange = CreateExchange("Update", new object[] { 7, new CreateModuleRequest { Name = "updated" } }); await dispatcher.Process(exchange); exchange.Out.Should().NotBeNull(); exchange.Out!.Body.Should().BeEquivalentTo(new { Id = 7, Name = "updated", Updated = true }); } [Fact] public async Task Dispatches_void_method_returns_204() { await using var context = new RouteContext(); var dispatcher = new SignalRControllerDispatcher(context, typeof(EchoController)); var exchange = CreateExchange("Delete", 42); await dispatcher.Process(exchange); exchange.Out.Should().NotBeNull(); exchange.Out!.GetHeader("status.code").Should().Be(204); } [Fact] public async Task Dispatches_async_method() { await using var context = new RouteContext(); var dispatcher = new SignalRControllerDispatcher(context, typeof(EchoController)); var exchange = CreateExchange("AsyncMethod", "test"); await dispatcher.Process(exchange); exchange.Out.Should().NotBeNull(); exchange.Out!.Body.Should().Be("async:test"); } [Fact] public async Task Resolves_default_parameter_when_not_provided() { await using var context = new RouteContext(); var dispatcher = new SignalRControllerDispatcher(context, typeof(EchoController)); // Only provide first arg — second should use default value (5) var exchange = CreateExchange("WithDefault", "hello"); await dispatcher.Process(exchange); exchange.Out.Should().NotBeNull(); exchange.Out!.Body.Should().Be("hello:5"); } [Fact] public async Task Skips_CancellationToken_in_positional_binding() { await using var context = new RouteContext(); var dispatcher = new SignalRControllerDispatcher(context, typeof(EchoController)); // CancellationToken is not the caller's concern — only "value" is provided var exchange = CreateExchange("WithCancellation", "test"); await dispatcher.Process(exchange); exchange.Out.Should().NotBeNull(); exchange.Out!.Body.Should().Be("ok:test"); } [Fact] public async Task Method_name_is_case_insensitive() { await using var context = new RouteContext(); var dispatcher = new SignalRControllerDispatcher(context, typeof(EchoController)); var exchange = CreateExchange("getall"); await dispatcher.Process(exchange); exchange.Out.Should().NotBeNull(); exchange.Out!.Body.Should().BeEquivalentTo(new[] { "item1", "item2" }); } // ── Error cases ───────────────────────────────────── [Fact] public async Task Returns_400_when_method_header_missing() { await using var context = new RouteContext(); var dispatcher = new SignalRControllerDispatcher(context, typeof(EchoController)); var exchange = CreateExchange(null); // no redbSignalR.Method header await dispatcher.Process(exchange); exchange.Out.Should().NotBeNull(); exchange.Out!.GetHeader("status.code").Should().Be(400); exchange.Out!.Body.Should().BeOfType(); } [Fact] public async Task Returns_404_when_method_not_found() { await using var context = new RouteContext(); var dispatcher = new SignalRControllerDispatcher(context, typeof(EchoController)); var exchange = CreateExchange("NonExistentMethod"); await dispatcher.Process(exchange); exchange.Out.Should().NotBeNull(); exchange.Out!.GetHeader("status.code").Should().Be(404); exchange.Out!.Body.Should().BeOfType(); } [Fact] public void Rejects_non_controller_type() { using var context = new RouteContext(); var act = () => new SignalRControllerDispatcher(context, typeof(string)); act.Should().Throw() .WithMessage("*does not inherit from RedbController*"); } [Fact] public void Requires_at_least_one_controller() { using var context = new RouteContext(); var act = () => new SignalRControllerDispatcher(context); act.Should().Throw() .WithMessage("*At least one controller*"); } // ── Multi-controller dispatch ─────────────────────── [Fact] public async Task Multi_qualified_name_dispatches_correctly() { await using var context = new RouteContext(); var dispatcher = new SignalRControllerDispatcher(context, typeof(EchoController), typeof(StatusController)); // Qualified: "Status.Health" var exchange = CreateExchange("Status.Health"); await dispatcher.Process(exchange); exchange.Out.Should().NotBeNull(); exchange.Out!.Body.Should().BeEquivalentTo(new { Status = "healthy", Uptime = 12345 }); } [Fact] public async Task Multi_unqualified_unique_method_resolves() { await using var context = new RouteContext(); var dispatcher = new SignalRControllerDispatcher(context, typeof(EchoController), typeof(StatusController)); // "Health" is unique to StatusController var exchange = CreateExchange("Health"); await dispatcher.Process(exchange); exchange.Out.Should().NotBeNull(); exchange.Out!.Body.Should().BeEquivalentTo(new { Status = "healthy", Uptime = 12345 }); } [Fact] public async Task Multi_ambiguous_unqualified_resolves_first_registered() { await using var context = new RouteContext(); var dispatcher = new SignalRControllerDispatcher(context, typeof(EchoController), typeof(StatusController)); // "GetAll" exists on both — resolves to EchoController (registered first, TryAdd) var exchange = CreateExchange("GetAll"); await dispatcher.Process(exchange); exchange.Out.Should().NotBeNull(); // EchoController.GetAll returns string[] {"item1","item2"} exchange.Out!.Body.Should().BeEquivalentTo(new[] { "item1", "item2" }); } [Fact] public async Task Multi_qualified_disambiguates_collision() { await using var context = new RouteContext(); var dispatcher = new SignalRControllerDispatcher(context, typeof(EchoController), typeof(StatusController)); // "Status.GetAll" resolves to StatusController despite collision var exchange = CreateExchange("Status.GetAll"); await dispatcher.Process(exchange); exchange.Out.Should().NotBeNull(); exchange.Out!.Body.Should().Be("status-ok"); } // ── Controller context injection ──────────────────── [Fact] public async Task Controller_has_context_and_exchange_injected() { await using var context = new RouteContext(); var dispatcher = new SignalRControllerDispatcher(context, typeof(ContextCheckController)); var exchange = CreateExchange("Check"); await dispatcher.Process(exchange); exchange.Out.Should().NotBeNull(); exchange.Out!.Body.Should().Be("ok"); } } Path: redb-route/tests/redb.Route.Tests.Controllers/SignalRControllerIntegrationTests.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/SignalRControllerIntegrationTests.cs ---- using System.Net; using System.Net.Sockets; using System.Text.Json; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Controllers; using redb.Route.SignalR; namespace redb.Route.Tests.Controllers; /// /// Integration tests: SignalR client → SignalRConsumer → SignalRControllerDispatcher → Controller → response. /// Real SignalR connections over loopback. No mocked headers — the hub bridge sets redbSignalR.Method natively. /// public class SignalRControllerIntegrationTests : IAsyncLifetime { private int _port; private RouteContext? _context; private SignalRConsumer? _consumer; private SignalRProducer? _producer; private static int GetFreePort() => global::redb.Route.Tests.Shared.TestPorts.Next(); 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 SignalR consumer with SignalRControllerDispatcher, /// and a SignalR producer (client mode) connected to it. /// private async Task StartPair(params Type[] controllerTypes) { _context = new RouteContext(); var context = _context; var dispatcher = new SignalRControllerDispatcher(context, controllerTypes); var component = new SignalRComponent(); // Consumer (hub server) var consumerParams = new Dictionary { ["inOut"] = "true" }; var cPath = $"/127.0.0.1:{_port}/hub"; var cUri = new EndpointUri("signalr", cPath, $"signalr:{cPath}", consumerParams); var cEndpoint = (SignalREndpoint)component.CreateEndpoint(cUri); _consumer = new SignalRConsumer(cEndpoint, dispatcher, cEndpoint.EndpointOptions); await _consumer.Start(); // Producer (client mode, InOut for request-response) var producerParams = new Dictionary { ["mode"] = "Client", ["inOut"] = "true" }; var pPath = $"/127.0.0.1:{_port}/hub"; var pUri = new EndpointUri("signalr", pPath, $"signalr:{pPath}", producerParams); var pEndpoint = (SignalREndpoint)component.CreateEndpoint(pUri); _producer = (SignalRProducer)pEndpoint.CreateProducer(); await _producer.Start(); // No wait after this: Start() returns once HubConnection.StartAsync has reached Connected, and a call on a // connection that is not connected fails instead of queueing. } // ── Basic method dispatch ────────────────────────── [Fact] public async Task Echo_method_returns_echo_response() { await StartPair(typeof(EchoController)); var exchange = new Exchange(new Message("hello-world")); exchange.In.setHeader(SignalRHeaders.Method, "Echo"); await _producer!.Process(exchange); exchange.Out.Should().NotBeNull(); exchange.Out!.Body.Should().NotBeNull(); exchange.Out!.Body!.ToString().Should().Be("echo:hello-world"); } // ── No-args method ────────────────────────────────── [Fact] public async Task GetAll_method_returns_items() { await StartPair(typeof(EchoController)); var exchange = new Exchange(new Message(null)); exchange.In.setHeader(SignalRHeaders.Method, "GetAll"); await _producer!.Process(exchange); exchange.Out.Should().NotBeNull(); exchange.Out!.Body.Should().NotBeNull(); // SignalR returns the serialized result var body = exchange.Out!.Body!.ToString(); body.Should().Contain("item1"); body.Should().Contain("item2"); } // ── Method with complex argument ──────────────────── [Fact] public async Task Create_method_with_object_arg() { await StartPair(typeof(EchoController)); var request = new CreateModuleRequest { Name = "TestModule" }; var exchange = new Exchange(new Message(request)); exchange.In.setHeader(SignalRHeaders.Method, "Create"); await _producer!.Process(exchange); exchange.Out.Should().NotBeNull(); exchange.Out!.Body.Should().NotBeNull(); var body = exchange.Out!.Body!.ToString(); body.Should().Contain("TestModule"); } // ── Async method ──────────────────────────────────── [Fact] public async Task AsyncMethod_returns_async_result() { await StartPair(typeof(EchoController)); var exchange = new Exchange(new Message("test-input")); exchange.In.setHeader(SignalRHeaders.Method, "AsyncMethod"); await _producer!.Process(exchange); exchange.Out.Should().NotBeNull(); exchange.Out!.Body!.ToString().Should().Be("async:test-input"); } // ── Multi-controller dispatch ─────────────────────── [Fact] public async Task Qualified_name_reaches_correct_controller() { await StartPair(typeof(EchoController), typeof(StatusController)); // Use qualified name to reach StatusController.GetAll var exchange = new Exchange(new Message(null)); exchange.In.setHeader(SignalRHeaders.Method, "Status.GetAll"); await _producer!.Process(exchange); exchange.Out.Should().NotBeNull(); exchange.Out!.Body!.ToString().Should().Be("status-ok"); } // ── Multiple sequential requests ──────────────────── [Fact] public async Task Multiple_requests_all_processed() { await StartPair(typeof(EchoController)); for (var i = 0; i < 5; i++) { var exchange = new Exchange(new Message($"msg-{i}")); exchange.In.setHeader(SignalRHeaders.Method, "Echo"); await _producer!.Process(exchange); exchange.Out.Should().NotBeNull(); exchange.Out!.Body!.ToString().Should().Be($"echo:msg-{i}"); } } } Path: redb-route/tests/redb.Route.Tests.Controllers/SoapControllerDispatcherTests.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/SoapControllerDispatcherTests.cs ---- using System.Net; using System.Net.Sockets; using System.Xml.Serialization; using AwesomeAssertions; 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.Soap; using SoapDsl = redb.Route.Soap.Fluent.Soap; namespace redb.Route.Tests.Controllers; /// /// SOAP as a controller transport: maps redbSoap.operation to a /// method, binds the XML body, and serializes the result back — unit tests plus a full end-to-end run through /// the real SOAP consumer. /// public class SoapControllerDispatcherTests { [XmlRoot("GetFares", Namespace = "urn:air")] public class GetFares { public string Route { get; set; } = ""; } [XmlRoot("GetFaresResponse", Namespace = "urn:air")] public class GetFaresResponse { public int Price { get; set; } } public class AirController : RedbController { public Task GetFares([FromBody] GetFares req) => Task.FromResult(new GetFaresResponse { Price = req.Route == "JFK-LHR" ? 100 : 0 }); [SoapOperation("Ping")] public string Health() => "pong"; // Returns already-serialized XML as bytes: must reach the client as XML, not "System.Byte[]". public byte[] Raw() => System.Text.Encoding.UTF8.GetBytes("ok"); // A required simple parameter with no binding attribute and no default: must fault readably. public string Bad(int n) => n.ToString(); // ValueTask must be awaited and its result serialized (not the struct itself). public ValueTask Quote([FromBody] GetFares req) => ValueTask.FromResult(new GetFaresResponse { Price = 42 }); } // A second controller that reuses the "GetFares" operation name — an unresolvable ambiguity. public class ClashController : RedbController { public string GetFares() => "clash"; } private static IExchange Exchange(string? operation, string? bodyXml) { var ex = new Exchange(); if (operation is not null) ex.In.setHeader(SoapControllerDispatcher.OperationHeader, operation); if (bodyXml is not null) ex.In.Body = bodyXml; return ex; } [Fact] public async Task Dispatches_By_Operation_And_Binds_Xml_Body() { await using var context = new RouteContext(); var dispatcher = new SoapControllerDispatcher(context, typeof(AirController)); var ex = Exchange("GetFares", "JFK-LHR"); await dispatcher.Process(ex); ex.Out.Should().NotBeNull(); ex.Out!.Body!.ToString().Should().Contain("GetFaresResponse").And.Contain("100"); } [Fact] public async Task SoapOperation_Attribute_Maps_The_Method() { await using var context = new RouteContext(); var dispatcher = new SoapControllerDispatcher(context, typeof(AirController)); var ex = Exchange("Ping", null); // method is Health(), mapped via [SoapOperation("Ping")] await dispatcher.Process(ex); ex.Out!.Body!.ToString().Should().Be("pong"); } [Fact] public async Task Unknown_Operation_Throws() { await using var context = new RouteContext(); var dispatcher = new SoapControllerDispatcher(context, typeof(AirController)); var act = async () => await dispatcher.Process(Exchange("DoesNotExist", null)); await act.Should().ThrowAsync().Where(e => e.Message.Contains("DoesNotExist")); } [Fact] public async Task Missing_Operation_Header_Throws() { await using var context = new RouteContext(); var dispatcher = new SoapControllerDispatcher(context, typeof(AirController)); var act = async () => await dispatcher.Process(Exchange(null, null)); await act.Should().ThrowAsync(); } [Fact] public async Task Unbindable_Simple_Param_Throws_Readable_Error() { await using var context = new RouteContext(); var dispatcher = new SoapControllerDispatcher(context, typeof(AirController)); var act = async () => await dispatcher.Process(Exchange("Bad", "")); // A clear message naming the parameter, not a cryptic reflection ArgumentException. (await act.Should().ThrowAsync()).Which.Message.Should().Contain("'n'"); } [Fact] public void Ctor_Throws_On_Ambiguous_Operation_Across_Controllers() { using var context = new RouteContext(); var act = () => new SoapControllerDispatcher(context, typeof(AirController), typeof(ClashController)); act.Should().Throw() .Which.Message.Should().Contain("Ambiguous").And.Contain("GetFares"); } [Fact] public async Task Dispatches_ValueTask_Return() { await using var context = new RouteContext(); var dispatcher = new SoapControllerDispatcher(context, typeof(AirController)); var ex = Exchange("Quote", "X"); await dispatcher.Process(ex); // The ValueTask must be awaited and its result serialized, not the struct itself. ex.Out!.Body!.ToString().Should().Contain("GetFaresResponse").And.Contain("42"); } [Fact] public async Task Controller_ByteArray_Reply_Is_Decoded_Not_Stringified() { var port = 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(port)) .RedbSoapController(); r.From("direct://call") .To(SoapDsl.Call($"http://127.0.0.1:{port}/air")); }); await ctx.Start(); var producer = ctx.GetEndpoint("direct://call").CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("")); try { await producer.Process(exchange); } finally { await producer.Stop(); } var body = exchange.Out!.Body!.ToString()!; body.Should().Contain("Raw").And.Contain("ok"); body.Should().NotContain("System.Byte"); } [Fact] public async Task EndToEnd_Through_The_Real_Soap_Consumer() { var port = FreePort(); await using var ctx = new RouteContext(); ctx.AddComponent(new SoapComponent()); ctx.AddRoutes(r => { // A SOAP endpoint served by a controller — dispatch by operation, no fluent route logic. r.From(SoapDsl.Listen("/air").Host("127.0.0.1").Port(port)) .RedbSoapController(); r.From("direct://call") .To(SoapDsl.Call($"http://127.0.0.1:{port}/air")); }); await ctx.Start(); var producer = ctx.GetEndpoint("direct://call").CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("JFK-LHR")); try { await producer.Process(exchange); } finally { await producer.Stop(); } // The controller ran behind the SOAP consumer and its typed reply came back as the response body. exchange.Out!.Body!.ToString().Should().Contain("GetFaresResponse").And.Contain("100"); } private static int FreePort() => global::redb.Route.Tests.Shared.TestPorts.Next(); } Path: redb-route/tests/redb.Route.Tests.Controllers/TestControllers.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/TestControllers.cs ---- using redb.Route.Controllers; using redb.Route.Controllers.Attributes; namespace redb.Route.Tests.Controllers; /// Direct-invoke target of RedbController<T>(methodName): no HTTP attributes, reached by name. public class DirectInvokeController : RedbController { public async Task Greet([FromBody] string name) { await Task.Yield(); return $"hello {name}"; } // async Task with no result: the Task an async method returns is a Task at run time. public async Task Touch() { await Task.Yield(); Exchange.setProperty("touched", true); } public string Boom() => throw new InvalidOperationException("direct-boom"); } /// /// The asynchronous return shapes, each reachable by path (generic, HTTP) and by name (SignalR, gRPC, SOAP). /// Every method yields first, so a dispatcher that does not await it finds the side effect missing. /// [Route("shapes")] public class ReturnShapesController : RedbController { [HttpPost("done")] public async Task Done() { await Task.Yield(); Exchange.setProperty("done", true); } [HttpGet("value")] public async ValueTask Value() { await Task.Yield(); return "value-ok"; } [HttpPost("value-done")] public async ValueTask ValueDone() { await Task.Yield(); Exchange.setProperty("done", true); } } /// /// A SOAP operation that is also an HTTP action, so a (which registers attributed /// actions only) can carry it into RedbSoapController(registry). /// public class SoapFareController : RedbController { [HttpPost] public SoapControllerDispatcherTests.GetFaresResponse GetFares([FromBody] SoapControllerDispatcherTests.GetFares request) => new() { Price = 7 }; } public enum BindingPriority { Low, High } public sealed record BoundTypes(DateTime At, DateTimeOffset Offset, decimal Amount, BindingPriority Priority, Guid Id); public class OptionsRequest { public string? ModuleName { get; set; } } /// One action per binding source, each returning what it bound so a test reads values, not a status. [Route("binding")] public class BindingController : RedbController { [HttpGet("header")] public string Header([FromHeader("X-Tenant")] string tenant, [FromHeader("X-Limit")] int limit = 10) => $"{tenant}:{limit}"; [HttpGet("property")] public string Property([FromProperty("user")] string user, [FromProperty("attempt")] int attempt) => $"{user}:{attempt}"; [HttpGet("query")] public string Query([FromQuery("verbose")] bool verbose, [FromQuery("page")] int page = 1) => $"{verbose}:{page}"; [HttpGet("types")] public BoundTypes Types( [FromQuery("at")] DateTime at, [FromQuery("offset")] DateTimeOffset offset, [FromQuery("amount")] decimal amount, [FromQuery("priority")] BindingPriority priority, [FromQuery("id")] Guid id) => new(at, offset, amount, priority, id); [HttpPatch("{id}")] public string Patch([FromRoute("id")] int id, [FromBody] CreateModuleRequest request) => $"patched {id}:{request.Name}"; [HttpPost("options")] public object Options([FromBody] OptionsRequest request) => new { request.ModuleName, IsCreated = true }; } /// A literal segment and a placeholder at the same depth, the literal action declared first. [Route("sessions-literal-first")] public class SessionsLiteralFirstController : RedbController { [HttpDelete("current")] public string DeleteCurrent() => "current"; [HttpDelete("{sessionId}")] public string DeleteById([FromRoute("sessionId")] string sessionId) => $"by-id:{sessionId}"; } /// The same pair declared the other way round, so the winner cannot depend on declaration order. [Route("sessions-param-first")] public class SessionsParamFirstController : RedbController { [HttpDelete("{sessionId}")] public string DeleteById([FromRoute("sessionId")] string sessionId) => $"by-id:{sessionId}"; [HttpDelete("current")] public string DeleteCurrent() => "current"; } /// An action that fails, so filters can be checked on the error path. [Route("filter-probe")] public class FilterProbeController : RedbController { [HttpGet("fail")] public string Fail() => throw new InvalidOperationException("probe-failed"); } // -- Shared by the registry, generic, HTTP, SignalR and gRPC suites -------------------------------------- [Route("modules")] public class ModulesController : RedbController { [HttpGet] public string[] GetAll() => ["module1", "module2"]; [HttpGet("{id}")] public string GetById([FromRoute("id")] string id) => $"module-{id}"; [HttpPost] public object Create([FromBody] CreateModuleRequest request) => new { Name = request.Name, Created = true }; [HttpDelete("{id}")] public void Delete([FromRoute("id")] string id) { } [HttpPut("{id}")] public object Update([FromRoute("id")] string id, [FromBody] CreateModuleRequest request) => new { Id = id, Name = request.Name, Updated = true }; } [Route("contexts")] public class ContextsController : RedbController { [HttpGet] public string[] List() => ["ctx1", "ctx2"]; [HttpPost("{name}/start")] public object Start([FromRoute("name")] string name) => new { Name = name, Started = true }; [HttpGet("{name}/status")] public object Status([FromRoute("name")] string name, [FromQuery("verbose")] bool verbose) => new { Name = name, Verbose = verbose, Status = "running" }; } public class NoRouteController : RedbController { [HttpGet] public string Health() => "ok"; } public class CreateModuleRequest { public string Name { get; set; } = ""; } /// /// Method-name dispatch fixtures (SignalR, gRPC, positional binding). No [Route] and no HTTP attributes on purpose: /// those transports dispatch by method name, so every public method is reachable, and a ControllerRegistry /// (which registers attributed actions only) never sees them. /// public class EchoController : RedbController { public string Echo(string message) => $"echo:{message}"; public string[] GetAll() => ["item1", "item2"]; public object GetById(int id) => new { Id = id, Name = $"item-{id}" }; public object Create(CreateModuleRequest request) => new { Name = request.Name, Created = true }; public object Update(int id, CreateModuleRequest request) => new { Id = id, Name = request.Name, Updated = true }; public void Delete(int id) { } public async Task AsyncMethod(string input) { await Task.Yield(); return $"async:{input}"; } public string WithDefault(string value, int count = 5) => $"{value}:{count}"; public string WithCancellation(string value, CancellationToken ct) => $"ok:{value}"; } /// Second controller for multi-controller dispatch tests. public class StatusController : RedbController { public string GetAll() => "status-ok"; public object Health() => new { Status = "healthy", Uptime = 12345 }; } /// Controller that verifies Context and Exchange are injected. public class ContextCheckController : RedbController { public string Check() { if (Context is null) throw new InvalidOperationException("Context is null"); if (Exchange is null) throw new InvalidOperationException("Exchange is null"); return "ok"; } } /// Controller exercising the JSON-object name-binding rules for ResolvePositional. public class BindController : RedbController { public string CreateBody([FromBody] CreateModuleRequest r) => r.Name; // [FromBody] → whole object public string CreateBare(CreateModuleRequest request) => request.Name; // lone complex → whole object public string Update([FromRoute("id")] string id, [FromBody] CreateModuleRequest r) => $"{id}|{r.Name}"; public string List(int offset = 0, int count = 25) => $"{offset}:{count}"; // simple params by key, defaults kept } /// Reports which instance served the call, so a test can tell one instance per request from a shared one. [Route("instance")] public class InstanceProbeController : RedbController { private readonly Guid _instanceId = Guid.NewGuid(); [HttpGet] public string Which() => $"{_instanceId}|{Exchange.ExchangeId}"; } /// A controller that asks for a constructor dependency, which the README says is not supported. [Route("ctor-arg")] public class ConstructorArgumentController(string dependency) : RedbController { [HttpGet] public string Get() => dependency; } /// /// An action that answers by itself, the way Tsak's ApiResponse helpers do: it writes Out (body, status, /// Content-Type), stops the exchange and returns null. Reachable by path and by method name. /// [Route("self-reply")] public class SelfReplyController : RedbController { [HttpGet] public object? Missing() { Exchange.Out ??= Exchange.In.Clone(); Exchange.Out.Body = new ControllerErrorResponse { Error = "NotFound", Message = "no such thing", StatusCode = 404 }; Exchange.Out.Headers["status.code"] = 404; Exchange.Out.Headers["Content-Type"] = "application/json"; Exchange.Stop(); return null; } } Path: redb-route/tests/redb.Route.Tests.Controllers/redb.Route.Tests.Controllers.csproj Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Controllers/redb.Route.Tests.Controllers.csproj ----