test: fake-time hosted-service wiring tests, drop a real-clock sleep (mxaccessgw#205)
R21-O32: SessionLeaseMonitorHostedService gets FakeTimeProvider tests (no sweep before the interval, one sweep per interval with the clock's now, a failing sweep does not stop the loop, interval floor, stop ends the loop), and OrphanWorkerCleanupHostedService gets startup tests (sweeps once, failure swallowed) plus a registration-order test (orphan cleanup before the session hosted services). TickObservingTimeProvider gains WaitForWatchedTimersAsync so Advance never races a service that has not armed its timer yet. R21-O29: the 250 ms negative-assertion sleep in the stopping-WorkerClient test is replaced by disposing the client and awaiting the pipe read-ahead to EOF. Remaining real-clock sleeps (dashboard feed/publisher, alarm monitor tests) need TimeProvider seams in production code and are left open. Claude-Session: https://claude.ai/code/session_01GT67AEHd2Acv1YPwGfXEoV
This commit is contained in:
+102
@@ -0,0 +1,102 @@
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Microsoft.Extensions.Options;
|
||||
using ZB.MOM.WW.MxGateway.Server.Configuration;
|
||||
using ZB.MOM.WW.MxGateway.Server.Metrics;
|
||||
using ZB.MOM.WW.MxGateway.Server.Sessions;
|
||||
using ZB.MOM.WW.MxGateway.Server.Workers;
|
||||
|
||||
namespace ZB.MOM.WW.MxGateway.Tests.Gateway.Workers;
|
||||
|
||||
/// <summary>
|
||||
/// Startup wiring of <see cref="OrphanWorkerCleanupHostedService"/> and its registration order
|
||||
/// relative to the session subsystem (mxaccessgw#205, R21-O32).
|
||||
/// </summary>
|
||||
public sealed class OrphanWorkerCleanupHostedServiceTests
|
||||
{
|
||||
private static readonly string WorkerPath = Path.GetFullPath(Path.Combine(
|
||||
Path.GetTempPath(), "OrphanHostedTests", "ZB.MOM.WW.MxGateway.Worker.exe"));
|
||||
|
||||
private static OrphanWorkerCleanupHostedService Create(CountingInspector inspector) =>
|
||||
new(
|
||||
new OrphanWorkerTerminator(
|
||||
Options.Create(new GatewayOptions { Worker = new WorkerOptions { ExecutablePath = WorkerPath } }),
|
||||
inspector,
|
||||
new GatewayMetrics()),
|
||||
NullLogger<OrphanWorkerCleanupHostedService>.Instance);
|
||||
|
||||
/// <summary>StartAsync sweeps for orphans exactly once and kills what the terminator finds.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task StartAsync_TerminatesOrphansOnce()
|
||||
{
|
||||
CountingInspector inspector = new([new RunningProcessInfo(4242, WorkerPath)]);
|
||||
OrphanWorkerCleanupHostedService service = Create(inspector);
|
||||
|
||||
await service.StartAsync(CancellationToken.None);
|
||||
await service.StopAsync(CancellationToken.None);
|
||||
|
||||
Assert.Equal(1, inspector.EnumerateCalls);
|
||||
Assert.Equal([4242], inspector.Killed);
|
||||
}
|
||||
|
||||
/// <summary>A cleanup failure is swallowed so the gateway still starts.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task StartAsync_WhenCleanupThrows_DoesNotFailStartup()
|
||||
{
|
||||
CountingInspector inspector = new([]) { ThrowOnEnumerate = true };
|
||||
OrphanWorkerCleanupHostedService service = Create(inspector);
|
||||
|
||||
await service.StartAsync(CancellationToken.None);
|
||||
|
||||
Assert.Equal(1, inspector.EnumerateCalls);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The worker launcher registration must put orphan cleanup ahead of the session
|
||||
/// subsystem's hosted services, so leaked workers are gone before sessions are accepted.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void Registration_OrdersOrphanCleanupBeforeSessionHostedServices()
|
||||
{
|
||||
ServiceCollection services = new();
|
||||
services.AddWorkerProcessLauncher();
|
||||
services.AddGatewaySessions();
|
||||
|
||||
List<Type?> hosted = services
|
||||
.Where(d => d.ServiceType == typeof(IHostedService))
|
||||
.Select(d => d.ImplementationType)
|
||||
.ToList();
|
||||
|
||||
int cleanup = hosted.IndexOf(typeof(OrphanWorkerCleanupHostedService));
|
||||
int lease = hosted.IndexOf(typeof(SessionLeaseMonitorHostedService));
|
||||
Assert.True(cleanup >= 0, "OrphanWorkerCleanupHostedService is not registered.");
|
||||
Assert.True(lease >= 0, "SessionLeaseMonitorHostedService is not registered.");
|
||||
Assert.True(cleanup < lease, "Orphan cleanup must start before the session lease monitor.");
|
||||
Assert.Contains(typeof(SessionShutdownHostedService), hosted);
|
||||
}
|
||||
|
||||
private sealed class CountingInspector(IReadOnlyList<RunningProcessInfo> processes) : IRunningProcessInspector
|
||||
{
|
||||
public int EnumerateCalls { get; private set; }
|
||||
|
||||
public bool ThrowOnEnumerate { get; init; }
|
||||
|
||||
public List<int> Killed { get; } = [];
|
||||
|
||||
public IReadOnlyList<RunningProcessInfo> GetProcessesByName(string processName)
|
||||
{
|
||||
EnumerateCalls++;
|
||||
if (ThrowOnEnumerate)
|
||||
{
|
||||
throw new InvalidOperationException("enumeration failed");
|
||||
}
|
||||
|
||||
return processes;
|
||||
}
|
||||
|
||||
public void Kill(int processId) => Killed.Add(processId);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user