Path: redb-route/tests/redb.Route.Tests/Extensions/RouteHealthCheckTests.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/Extensions/RouteHealthCheckTests.cs ---- using Microsoft.Extensions.Diagnostics.HealthChecks; using NSubstitute; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Extensions; namespace redb.Route.Tests.Extensions; /// /// Tests for per-route status and endpoint statistics. /// public class RouteHealthCheckTests : IAsyncLifetime { private readonly RouteContext _context = new(); public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { await _context.DisposeAsync(); GC.SuppressFinalize(this); } [Fact] public async Task NoRoutes_ReturnsDegraded() { var healthCheck = new RouteHealthCheck(_context); var result = await healthCheck.CheckHealthAsync(CreateContext()); result.Status.Should().Be(HealthStatus.Degraded); result.Description.Should().Contain("No routes"); } [Fact] public async Task AllRoutesStarted_ReturnsHealthy() { _context.AddRoutes(r => { r.From("direct://health-source") .Process(e => { }); }); await _context.Start(); var healthCheck = new RouteHealthCheck(_context); var result = await healthCheck.CheckHealthAsync(CreateContext()); result.Status.Should().Be(HealthStatus.Healthy); result.Description.Should().Contain("1 route(s) running"); } [Fact] public async Task WithRoutes_IncludesRouteCount() { _context.AddRoutes(r => { r.From("direct://a") .Process(e => { }); }); _context.AddRoutes(r => { r.From("direct://b") .Process(e => { }); }); await _context.Start(); var healthCheck = new RouteHealthCheck(_context); var result = await healthCheck.CheckHealthAsync(CreateContext()); result.Status.Should().Be(HealthStatus.Healthy); result.Data.Should().ContainKey("routeCount"); result.Data["routeCount"].Should().Be(2); } [Fact] public async Task WithRoutes_IncludesRouteDetails() { _context.AddRoutes(r => { r.From("direct://meta") .RouteId("test-route") .Process(e => { }); }); await _context.Start(); var healthCheck = new RouteHealthCheck(_context); var result = await healthCheck.CheckHealthAsync(CreateContext()); result.Data.Should().ContainKey("routes"); var routes = result.Data["routes"] as List; routes.Should().NotBeNull(); routes!.Count.Should().Be(1); var routeDict = routes[0] as Dictionary; routeDict.Should().NotBeNull(); routeDict!["routeId"].Should().Be("test-route"); routeDict["status"].Should().Be("Started"); } [Fact] public async Task ErroredRoute_ReturnsUnhealthy() { _context.AddRoutes(r => { r.From("direct://err") .RouteId("errored-route") .Process(e => { }); }); await _context.Start(); // Manually set route to Errored state var route = _context.Routes.First(r => r.RouteId == "errored-route"); route.Status = RouteStatus.Errored; var healthCheck = new RouteHealthCheck(_context); var result = await healthCheck.CheckHealthAsync(CreateContext()); result.Status.Should().Be(HealthStatus.Unhealthy); result.Description.Should().Contain("errors detected"); } [Fact] public async Task StoppedRoute_ReturnsDegraded() { _context.AddRoutes(r => { r.From("direct://stopped") .RouteId("stopped-route") .Process(e => { }); }); await _context.Start(); await _context.StopRoute("stopped-route"); var healthCheck = new RouteHealthCheck(_context); var result = await healthCheck.CheckHealthAsync(CreateContext()); result.Status.Should().Be(HealthStatus.Degraded); result.Description.Should().Contain("degraded"); } [Fact] public void Constructor_NullContext_Throws() { var act = () => new RouteHealthCheck((IRouteContext)null!); act.Should().Throw(); } [Fact] public async Task ASendSideEndpointThatKnowsItIsBroken_MakesTheContextDegraded_UnderItsMaskedUri() { _context.AddComponent(new ConditionComponent()); _context.AddRoutes(r => r.From("direct://health-sender").Process(_ => { })); await _context.Start(); var endpoint = (ConditionEndpoint)_context.GetEndpoint("cond://broker?password=s3cret-pw&host=b1"); endpoint.Condition = (EndpointHealthStatus.Critical, "The broker blocks publishing: low on disk"); var result = await new RouteHealthCheck(_context).CheckHealthAsync(CreateContext()); result.Status.Should().Be(HealthStatus.Degraded, "a send-side endpoint never makes a running context Unhealthy"); var listed = result.Data["endpoints"].Should().BeAssignableTo>().Which .Should().ContainSingle().Which.Should().BeAssignableTo>().Which; listed["uri"].Should().BeOfType().Which.Should().Contain("broker").And.Contain(EndpointUri.Redacted); listed["endpointHealth"].Should().Be("Critical"); listed["reason"].Should().Be("The broker blocks publishing: low on disk"); System.Text.Json.JsonSerializer.Serialize(result.Data).Should().NotContain("s3cret-pw"); // The condition clears, and the endpoint returns to its computed status by itself. endpoint.Condition = null; var cleared = await new RouteHealthCheck(_context).CheckHealthAsync(CreateContext()); cleared.Status.Should().Be(HealthStatus.Healthy); cleared.Data.Should().NotContainKey("endpoints"); } [Fact] public async Task AnErrorThatQuotesACredentialedUri_ReachesThePayloadMasked() { // A connector's exception may quote the URI it failed on, password and all; the payload is often read by // unauthenticated probes. _context.AddRoutes(r => r.From("direct://health-leak").Process(_ => throw new InvalidOperationException( "None of the endpoints were reachable: amqp://svc:Sup3rS3cret@broker:5672 (password=Sup3rS3cret)"))); await _context.Start(); var producer = _context.GetEndpoint("direct://health-leak").CreateProducer(); await producer.Start(); try { await producer.Process(new Exchange(new Message("x"))); } catch (InvalidOperationException) { } var result = await new RouteHealthCheck(_context).CheckHealthAsync(CreateContext()); var payload = System.Text.Json.JsonSerializer.Serialize(result.Data); payload.Should().Contain("svc:" + EndpointUri.Redacted + "@broker", "the error is still there, masked"); payload.Should().NotContain("Sup3rS3cret"); } [Fact] public async Task ManyBrokenSendSideEndpoints_AreListedUpToTheCap_AndCounted() { _context.AddComponent(new ConditionComponent()); _context.AddRoutes(r => r.From("direct://health-many").Process(_ => { })); await _context.Start(); for (var i = 0; i < 1000; i++) { var endpoint = (ConditionEndpoint)_context.GetEndpoint($"cond://dynamic-{i}"); if (i % 2 == 0) endpoint.Condition = (EndpointHealthStatus.Failed, "down"); } var endpointsBefore = _context.GetEndpoints().Count; var result = await new RouteHealthCheck(_context).CheckHealthAsync(CreateContext()); result.Status.Should().Be(HealthStatus.Degraded); ((IReadOnlyList)result.Data["endpoints"]).Should().HaveCount(RouteHealthCheck.MaxListedEndpoints); result.Data["endpointsNotListed"].Should().Be(500 - RouteHealthCheck.MaxListedEndpoints); _context.GetEndpoints().Should().HaveCount(endpointsBefore, "a probe reads endpoints, it never creates one"); } [Fact] public async Task AnIdleSendSideEndpoint_DoesNotDegradeTheContext() { // Only a state that says "broken" counts; a Warning (idle, a few recent errors) on the send side does not. _context.AddComponent(new ConditionComponent()); _context.AddRoutes(r => r.From("direct://health-idle").Process(_ => { })); await _context.Start(); ((ConditionEndpoint)_context.GetEndpoint("cond://idle")).Condition = (EndpointHealthStatus.Warning, "No activity for 30 min"); var result = await new RouteHealthCheck(_context).CheckHealthAsync(CreateContext()); result.Status.Should().Be(HealthStatus.Healthy); result.Data.Should().NotContainKey("endpoints"); } /// An endpoint whose transport condition the test sets. private sealed class ConditionComponent : ComponentBase { public override string Scheme => "cond"; public override IEndpoint CreateEndpoint(EndpointUri uri) => new ConditionEndpoint(uri, this); } private sealed class ConditionOptions : EndpointOptions { public override void Validate() { } } private sealed class ConditionEndpoint(EndpointUri uri, IComponent component) : EndpointBase(uri, component, new ConditionOptions()) { public (EndpointHealthStatus Status, string Reason)? Condition { get; set; } protected override (EndpointHealthStatus Status, string Reason)? TransportCondition => Condition; public override IProducer CreateProducer() => throw new NotSupportedException(); public override IConsumer CreateConsumer(IProcessor processor) => throw new NotSupportedException(); } private static HealthCheckContext CreateContext() { return new HealthCheckContext { Registration = new HealthCheckRegistration( "test", Substitute.For(), HealthStatus.Unhealthy, Array.Empty()) }; } }