Path: redb-identity/tests/redb.Identity.Tests/Module/GracefulShutdownTests.cs
Snapshot: redb-identity, 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-identity
Page: https://redbase.app/src/dev-2026-12-06/redb-identity/tests/redb.Identity.Tests/Module/GracefulShutdownTests.cs
----
using AwesomeAssertions;
using Microsoft.Extensions.DependencyInjection;
using NSubstitute;
using redb.Route.Abstractions;
using redb.Route.Core;
using Xunit;
namespace redb.Identity.Tests.Module;
///
/// F2 — graceful shutdown contract for the Identity route context.
///
public class GracefulShutdownTests
{
[Fact]
public async Task ContextStop_InvokesStoppingThenStopped_OnAllListeners()
{
var sp = new ServiceCollection().BuildServiceProvider();
await using var ctx = new RouteContext(sp, "graceful-shutdown-test");
var listener = Substitute.For();
ctx.AddLifecycleListener(listener);
await ctx.Start();
ctx.IsStarted.Should().BeTrue();
await ctx.Stop();
Received.InOrder(() =>
{
listener.OnContextStopping(ctx, Arg.Any());
listener.OnContextStopped(ctx, Arg.Any());
});
}
[Fact]
public async Task ContextStop_PropagatesProvidedCancellationToken()
{
var sp = new ServiceCollection().BuildServiceProvider();
await using var ctx = new RouteContext(sp, "graceful-shutdown-ct-test");
CancellationToken capturedStopping = default;
CancellationToken capturedStopped = default;
var listener = Substitute.For();
listener.OnContextStopping(Arg.Any(), Arg.Do(t => capturedStopping = t))
.Returns(Task.CompletedTask);
listener.OnContextStopped(Arg.Any(), Arg.Do(t => capturedStopped = t))
.Returns(Task.CompletedTask);
ctx.AddLifecycleListener(listener);
await ctx.Start();
using var cts = new CancellationTokenSource();
await ctx.Stop(cts.Token);
capturedStopping.Should().Be(cts.Token);
capturedStopped.Should().Be(cts.Token);
}
[Fact]
public async Task ContextStop_WhenListenerThrows_StillStops()
{
var sp = new ServiceCollection().BuildServiceProvider();
await using var ctx = new RouteContext(sp, "graceful-shutdown-throw-test");
var crashing = Substitute.For();
crashing.OnContextStopping(Arg.Any(), Arg.Any())
.Returns(_ => throw new InvalidOperationException("boom"));
ctx.AddLifecycleListener(crashing);
await ctx.Start();
try
{
await ctx.Stop();
}
catch (InvalidOperationException)
{
}
ctx.IsStarted.Should().BeFalse();
}
}