Files
ScadaBridge/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Monitoring/PendingUpdatesHealthTilesTests.cs
T
Joseph Doherty 7addd846a1 fix(centralui): no timers/subscriptions created after a mid-load dispose (UI-4, WP5 task 5.3)
A navigation while an awaited load was still running disposed the component
first; the continuation then created a timer / added a singleton handler that
nothing ever disposed, rooting the dead circuit for the life of the process.

- Health: refresh timer created under _timerLock only if not disposed.
- DataConnections: same for the health-poll timer; also stops before touching
  the disposed CTS when disposed during the first load.
- Deployments: subscribe to IDeploymentStatusNotifier BEFORE the first load
  (the handler only schedules a reload; the generation guard orders flights).
- PendingUpdatesHealthTiles: the Invalidated subscription and the poll timer are
  both created under a lifetime lock after a disposed check; Dispose unsubscribes
  only what was subscribed (covers a dispose during the auth-state await too).
- AlarmSummary: StartTimer/StopTimer/Dispose atomic under _timerLock; StartTimer
  refuses after dispose (Topology.StartLiveUpdatesTimer idiom).

Tests (each fails on the pre-fix component): HealthPageTests, DataConnectionsPageTests,
DeploymentsPerFlightScopeTests, PendingUpdatesHealthTilesTests (x2),
AlarmSummaryRenderTests - dispose mid-load, release the load, assert no timer and
no handler left.
2026-12-03 10:00:36 -05:00

175 lines
7.5 KiB
C#

using System.Security.Claims;
using Bunit;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.Extensions.DependencyInjection;
using NSubstitute;
using ZB.MOM.WW.ScadaBridge.CentralUI.Auth;
using ZB.MOM.WW.ScadaBridge.CentralUI.Components.Health;
using ZB.MOM.WW.ScadaBridge.CentralUI.Services;
using ZB.MOM.WW.ScadaBridge.DeploymentManager.PendingUpdates;
using ZB.MOM.WW.ScadaBridge.Security;
namespace ZB.MOM.WW.ScadaBridge.CentralUI.Tests.Monitoring;
/// <summary>Gitea #63: pending-updates tiles on the Health dashboard.</summary>
public class PendingUpdatesHealthTilesTests : BunitContext
{
private static SitePendingUpdates Row(int id, int stale, ArtifactDeploymentState a = ArtifactDeploymentState.Current) =>
new(id, $"S{id}", $"Site {id}", a, DateTimeOffset.UtcNow, 10, stale, 0);
private IRenderedComponent<PendingUpdatesHealthTiles> RenderFor(IPendingUpdatesCache cache, params Claim[] claims)
{
var user = new ClaimsPrincipal(new ClaimsIdentity(claims, "TestAuth"));
Services.AddScoped<SiteScopeService>();
Services.AddSingleton(cache);
return Render<PendingUpdatesHealthTiles>(ps =>
ps.AddCascadingValue(Task.FromResult(new AuthenticationState(user))));
}
private static IPendingUpdatesCache CacheReturning(params SitePendingUpdates[] rows)
{
var cache = Substitute.For<IPendingUpdatesCache>();
cache.GetAsync(Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(Task.FromResult(new PendingUpdatesSnapshot(DateTimeOffset.UtcNow, rows)));
return cache;
}
private static Claim Role(string r) => new(JwtTokenService.RoleClaimType, r);
/// <summary>A Deployer sees both counts, highlighted when non-zero.</summary>
[Fact]
public void Deployer_SeesBothCounts()
{
var cut = RenderFor(
CacheReturning(Row(1, 4), Row(2, 3, ArtifactDeploymentState.OutOfDate)),
Role(Roles.Deployer));
cut.WaitForAssertion(() =>
{
Assert.Contains("7", cut.Find("[data-test='pending-updates-instances']").TextContent);
Assert.Contains("1", cut.Find("[data-test='pending-updates-artifact-sites']").TextContent);
Assert.Contains("border-warning", cut.Find("[data-test='pending-updates-instances']").ClassName);
});
}
/// <summary>A Viewer sees nothing and triggers no fleet read.</summary>
[Fact]
public void Viewer_SeesNothing_AndNoFleetRead()
{
var cache = CacheReturning(Row(1, 4));
var cut = RenderFor(cache, Role("Viewer"));
Assert.True(string.IsNullOrWhiteSpace(cut.Markup));
cache.DidNotReceive().GetAsync(Arg.Any<bool>(), Arg.Any<CancellationToken>());
}
/// <summary>A site-scoped Deployer's totals exclude sites outside the scope.</summary>
[Fact]
public void SiteScopedDeployer_CountsOnlyPermittedSites()
{
var cut = RenderFor(
CacheReturning(Row(1, 4), Row(2, 9)),
Role(Roles.Deployer), new Claim(JwtTokenService.SiteIdClaimType, "1"));
cut.WaitForAssertion(() =>
Assert.Equal("4", cut.Find("[data-test='pending-updates-instances'] h3").TextContent.Trim()));
}
/// <summary>A failed read is shown as unavailable, never as zero.</summary>
[Fact]
public void ReadFailure_ShowsUnavailable_NotZero()
{
var cache = Substitute.For<IPendingUpdatesCache>();
cache.GetAsync(Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(Task.FromException<PendingUpdatesSnapshot>(new InvalidOperationException("boom")));
var cut = RenderFor(cache, Role(Roles.Administrator));
cut.WaitForAssertion(() =>
{
Assert.Contains("boom", cut.Find("[data-test='pending-updates-error']").TextContent);
Assert.Equal("—", cut.Find("[data-test='pending-updates-instances'] h3").TextContent.Trim());
});
}
/// <summary>An invalidation re-reads the cache.</summary>
[Fact]
public void Invalidated_Rereads()
{
var cache = Substitute.For<IPendingUpdatesCache>();
cache.GetAsync(Arg.Any<bool>(), Arg.Any<CancellationToken>()).Returns(
Task.FromResult(new PendingUpdatesSnapshot(DateTimeOffset.UtcNow, [Row(1, 5)])),
Task.FromResult(new PendingUpdatesSnapshot(DateTimeOffset.UtcNow, [Row(1, 0)])));
var cut = RenderFor(cache, Role(Roles.Deployer));
cut.WaitForAssertion(() => Assert.Equal("5", cut.Find("[data-test='pending-updates-instances'] h3").TextContent.Trim()));
cache.Invalidated += NSubstitute.Raise.Event<Action>();
cut.WaitForAssertion(() => Assert.Equal("0", cut.Find("[data-test='pending-updates-instances'] h3").TextContent.Trim()));
}
/// <summary>Counts subscriptions so a test can see a leaked handler on the singleton cache.</summary>
private sealed class CountingCache : IPendingUpdatesCache
{
public TaskCompletionSource<PendingUpdatesSnapshot> Gate { get; } =
new(TaskCreationOptions.RunContinuationsAsynchronously);
private Action? _handlers;
/// <summary>Handlers currently on the invocation list (removing an absent one is a no-op, as for a real event).</summary>
public int Subscribers => _handlers?.GetInvocationList().Length ?? 0;
public Task<PendingUpdatesSnapshot> GetAsync(bool forceRefresh = false, CancellationToken cancellationToken = default)
=> Gate.Task;
public event Action? Invalidated
{
add => _handlers += value;
remove => _handlers -= value;
}
}
/// <summary>
/// Code review 2026-12-02 UI-4: disposed while the first snapshot load is in flight, the
/// tiles must not start their poll timer, and must leave no handler on the singleton cache.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task DisposedDuringFirstLoad_CreatesNoTimer_AndLeavesNoSubscription()
{
var cache = new CountingCache();
var cut = RenderFor(cache, Role(Roles.Deployer));
var tiles = cut.Instance;
await cut.InvokeAsync(tiles.Dispose);
cache.Gate.SetResult(new PendingUpdatesSnapshot(DateTimeOffset.UtcNow, Array.Empty<SitePendingUpdates>()));
await cut.InvokeAsync(() => { });
await cut.InvokeAsync(() => { });
Assert.Null(typeof(PendingUpdatesHealthTiles)
.GetField("_timer", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!
.GetValue(tiles));
Assert.Equal(0, cache.Subscribers);
}
/// <summary>Disposed while the cascaded auth state is still pending, the tiles never subscribe.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task DisposedBeforeAuthResolves_NeverSubscribes()
{
var cache = new CountingCache();
var auth = new TaskCompletionSource<AuthenticationState>(TaskCreationOptions.RunContinuationsAsynchronously);
Services.AddScoped<SiteScopeService>();
Services.AddSingleton<IPendingUpdatesCache>(cache);
var cut = Render<PendingUpdatesHealthTiles>(ps => ps.AddCascadingValue(auth.Task));
var tiles = cut.Instance;
await cut.InvokeAsync(tiles.Dispose);
auth.SetResult(new AuthenticationState(new ClaimsPrincipal(
new ClaimsIdentity(new[] { Role(Roles.Deployer) }, "TestAuth"))));
await cut.InvokeAsync(() => { });
await cut.InvokeAsync(() => { });
Assert.Equal(0, cache.Subscribers);
}
}