using System.Security.Claims;
using Bunit;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using NSubstitute;
using ZB.MOM.WW.ScadaBridge.CentralUI.Components.Shared;
using ZB.MOM.WW.ScadaBridge.CentralUI.Services;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Services;
using ZB.MOM.WW.ScadaBridge.Communication;
using ZB.MOM.WW.ScadaBridge.DeploymentManager;
using ZB.MOM.WW.ScadaBridge.DeploymentManager.PendingUpdates;
using ZB.MOM.WW.Secrets.Abstractions;
using SitesPage = ZB.MOM.WW.ScadaBridge.CentralUI.Components.Pages.Admin.Sites;
namespace ZB.MOM.WW.ScadaBridge.CentralUI.Tests.Admin;
///
/// Regression tests for the Sites page N+1 query fix. The Sites page loaded all sites and then
/// issued GetDataConnectionsBySiteIdAsync once per site (N+1 database
/// round-trips on every load and post-delete refresh). The fix fetches all
/// data connections in a single GetAllDataConnectionsAsync call and
/// groups them client-side.
///
public class SitesPageTests : BunitContext
{
private readonly ISiteRepository _siteRepo = Substitute.For();
private readonly IPendingUpdatesCache _pendingUpdates = Substitute.For();
private void RegisterServices()
{
Services.AddSingleton(_siteRepo);
// Default: an empty snapshot, so the page's badges resolve without a stub.
// Individual tests re-stub GetAsync before rendering.
_pendingUpdates.GetAsync(Arg.Any(), Arg.Any())
.Returns(_ => Task.FromResult(Snapshot()));
Services.AddSingleton(_pendingUpdates);
var comms = new CommunicationService(
Options.Create(new CommunicationOptions()),
NullLogger.Instance);
Services.AddSingleton(comms);
var artifactSvc = new ArtifactDeploymentService(
_siteRepo,
Substitute.For(),
Substitute.For(),
Substitute.For(),
comms,
Substitute.For(),
Options.Create(new DeploymentManagerOptions()),
NullLogger.Instance,
new ArtifactRevisionHashService(),
// These tests don't exercise secret references, so a store that never has
// anything is never called — CollectAsync only queries a scanned secret: reference.
new SiteSecretsCollector(Substitute.For()));
Services.AddSingleton(artifactSvc);
Services.AddSingleton(Substitute.For());
var identity = new ClaimsIdentity(
new[] { new Claim(ClaimTypes.Name, "admin") }, "TestCookie");
var authState = new AuthenticationState(new ClaimsPrincipal(identity));
Services.AddSingleton(
new StubAuthStateProvider(authState));
}
private sealed class StubAuthStateProvider : AuthenticationStateProvider
{
private readonly AuthenticationState _state;
/// Initializes a new instance of the class.
/// The authentication state returned to callers.
public StubAuthStateProvider(AuthenticationState state) => _state = state;
///
public override Task GetAuthenticationStateAsync()
=> Task.FromResult(_state);
}
private static List Sites(params int[] ids)
=> ids.Select(id => new Site($"Site{id}", $"SITE-{id}") { Id = id }).ToList();
private static DataConnection Conn(int siteId, string name)
=> new(name, "OpcUa", siteId);
private static PendingUpdatesSnapshot Snapshot(params SitePendingUpdates[] sites)
=> new(new DateTimeOffset(2026, 9, 14, 10, 30, 0, TimeSpan.Zero), sites);
private static SitePendingUpdates Pending(
int siteId,
ArtifactDeploymentState state,
int deployed = 0,
int stale = 0,
int unknown = 0)
=> new(
siteId,
$"SITE-{siteId}",
$"Site{siteId}",
state,
state == ArtifactDeploymentState.NeverDeployed
? null
: new DateTimeOffset(2026, 9, 13, 8, 0, 0, TimeSpan.Zero),
deployed,
stale,
unknown);
/// Verifies that loading data fetches all connections in one query rather than one query per site.
[Fact]
public void LoadData_FetchesAllConnectionsInOneQuery_NoPerSiteQueries()
{
RegisterServices();
_siteRepo.GetAllSitesAsync().Returns(Sites(1, 2, 3));
_siteRepo.GetAllDataConnectionsAsync().Returns(new List
{
Conn(1, "c1"), Conn(2, "c2"), Conn(3, "c3"),
});
Render();
// Regression: exactly one bulk query, and zero per-site queries.
_siteRepo.Received(1).GetAllDataConnectionsAsync();
_siteRepo.DidNotReceive().GetDataConnectionsBySiteIdAsync(Arg.Any());
}
/// Verifies that loading data groups connections by site and renders them under their site.
[Fact]
public void LoadData_GroupsConnectionsBySite_AndRendersThem()
{
RegisterServices();
_siteRepo.GetAllSitesAsync().Returns(Sites(1, 2));
_siteRepo.GetAllDataConnectionsAsync().Returns(new List
{
Conn(1, "alpha-conn"), Conn(2, "beta-conn"),
});
var cut = Render();
Assert.Contains("alpha-conn", cut.Markup);
Assert.Contains("beta-conn", cut.Markup);
}
/// Verifies that the artifact badge shows Current, Out of date or Never deployed according to the site's artifact state.
[Fact]
public void ArtifactBadge_ShowsCurrent_OutOfDate_NeverDeployed()
{
RegisterServices();
_siteRepo.GetAllSitesAsync().Returns(Sites(1, 2, 3));
_siteRepo.GetAllDataConnectionsAsync().Returns(new List());
_pendingUpdates.GetAsync(Arg.Any(), Arg.Any())
.Returns(_ => Task.FromResult(Snapshot(
Pending(1, ArtifactDeploymentState.Current),
Pending(2, ArtifactDeploymentState.OutOfDate),
Pending(3, ArtifactDeploymentState.NeverDeployed))));
var cut = Render();
cut.WaitForAssertion(() =>
{
Assert.Contains("aria-label=\"Artifacts: current\"", cut.Markup);
Assert.Contains("Artifacts current", cut.Markup);
Assert.Contains("aria-label=\"Artifacts: out of date\"", cut.Markup);
Assert.Contains("Artifacts out of date", cut.Markup);
Assert.Contains("aria-label=\"Artifacts: never deployed\"", cut.Markup);
Assert.Contains("Artifacts never deployed", cut.Markup);
});
}
/// Verifies that the instance line shows the stale count out of the deployed count.
[Fact]
public void InstanceLine_ShowsStaleOfDeployed()
{
RegisterServices();
_siteRepo.GetAllSitesAsync().Returns(Sites(1));
_siteRepo.GetAllDataConnectionsAsync().Returns(new List());
_pendingUpdates.GetAsync(Arg.Any(), Arg.Any())
.Returns(_ => Task.FromResult(Snapshot(
Pending(1, ArtifactDeploymentState.Current, deployed: 5, stale: 2, unknown: 1))));
var cut = Render();
cut.WaitForAssertion(() =>
{
Assert.Contains("2 of 5 instances out of date", cut.Markup);
Assert.Contains("1 could not be evaluated", cut.Markup);
Assert.Contains("/deployment/topology", cut.Markup);
});
}
/// Verifies that the instance line uses the correct singular wording when exactly one instance is affected.
[Fact]
public void InstanceLine_PluralisesTheSingleInstanceCase()
{
RegisterServices();
_siteRepo.GetAllSitesAsync().Returns(Sites(1, 2));
_siteRepo.GetAllDataConnectionsAsync().Returns(new List());
_pendingUpdates.GetAsync(Arg.Any(), Arg.Any())
.Returns(_ => Task.FromResult(Snapshot(
Pending(1, ArtifactDeploymentState.Current, deployed: 1, stale: 1),
Pending(2, ArtifactDeploymentState.Current, deployed: 1))));
var cut = Render();
cut.WaitForAssertion(() =>
{
Assert.Contains("1 of 1 instance out of date", cut.Markup);
Assert.Contains("All 1 instance current", cut.Markup);
Assert.DoesNotContain("1 instances", cut.Markup);
});
}
/// Verifies that Re-check forces a refresh of the pending-updates snapshot.
[Fact]
public void Recheck_ForcesRefresh()
{
RegisterServices();
_siteRepo.GetAllSitesAsync().Returns(Sites(1));
_siteRepo.GetAllDataConnectionsAsync().Returns(new List());
var cut = Render();
cut.Find("button[aria-label=\"Re-check pending updates\"]").Click();
cut.WaitForAssertion(() =>
_pendingUpdates.Received().GetAsync(true, Arg.Any()));
}
/// Verifies that a failure loading sites skips the fleet-wide evaluation.
[Fact]
public void SiteLoadFailure_SkipsTheFleetEvaluation()
{
RegisterServices();
_siteRepo.GetAllSitesAsync()
.Returns>>(_ => throw new InvalidOperationException("db down"));
var cut = Render();
cut.WaitForAssertion(() => Assert.Contains("Failed to load sites", cut.Markup));
// No cards to badge, so the whole-fleet flatten must not run at all.
_pendingUpdates.DidNotReceive().GetAsync(Arg.Any(), Arg.Any());
}
/// Verifies that a failed re-check clears the stale as-of caption.
[Fact]
public void FailedRecheck_ClearsTheStaleAsOfCaption()
{
RegisterServices();
_siteRepo.GetAllSitesAsync().Returns(Sites(1));
_siteRepo.GetAllDataConnectionsAsync().Returns(new List());
_pendingUpdates.GetAsync(Arg.Any(), Arg.Any())
.Returns(_ => Task.FromResult(Snapshot(Pending(1, ArtifactDeploymentState.Current))));
var cut = Render();
cut.WaitForAssertion(() => Assert.Contains("Updates as of", cut.Markup));
// The re-check now faults: the error wins, so the caption from the earlier good
// evaluation must not stand next to "unavailable" badges.
_pendingUpdates.GetAsync(Arg.Any(), Arg.Any())
.Returns>(_ => throw new InvalidOperationException("evaluator down"));
cut.Find("button[aria-label=\"Re-check pending updates\"]").Click();
cut.WaitForAssertion(() =>
{
Assert.DoesNotContain("Updates as of", cut.Markup);
Assert.Contains("Artifacts: unavailable", cut.Markup);
Assert.Contains("Site1", cut.Markup);
});
}
/// Verifies that a cache fault shows an unavailable state while the sites still render.
[Fact]
public void CacheFault_ShowsUnavailable_AndSitesStillRender()
{
RegisterServices();
_siteRepo.GetAllSitesAsync().Returns(Sites(1, 2));
_siteRepo.GetAllDataConnectionsAsync().Returns(new List());
_pendingUpdates.GetAsync(Arg.Any(), Arg.Any())
.Returns>(_ => throw new InvalidOperationException("evaluator down"));
var cut = Render();
cut.WaitForAssertion(() =>
{
// The snapshot failing must never take the site list down with it.
Assert.Contains("Site1", cut.Markup);
Assert.Contains("Site2", cut.Markup);
Assert.Contains("Artifacts: unavailable", cut.Markup);
});
}
/// Marks the DI scope an artifact deploy ran in, so the test can see it was disposed.
private sealed class ScopeProbe : IDisposable
{
public bool Disposed { get; private set; }
public void Dispose() => Disposed = true;
}
private sealed class ProbingArtifactDeploymentService : ArtifactDeploymentService
{
private readonly ScopeProbe _probe;
private readonly Action _onDeploy;
public ProbingArtifactDeploymentService(ISiteRepository siteRepo, CommunicationService comms, ScopeProbe probe, Action onDeploy)
: base(siteRepo, Substitute.For(), Substitute.For(),
Substitute.For(), comms, Substitute.For(),
Options.Create(new DeploymentManagerOptions()), NullLogger.Instance,
new ArtifactRevisionHashService(), new SiteSecretsCollector(Substitute.For()))
{
_probe = probe;
_onDeploy = onDeploy;
}
public override Task> DeployToAllSitesAsync(
string user, CancellationToken cancellationToken = default)
{
_onDeploy(_probe);
return Task.FromResult(ZB.MOM.WW.ScadaBridge.Commons.Types.Result.Success(
new ArtifactDeploymentSummary("dep-1", Array.Empty(), 0, 0)));
}
}
///
/// Code review 2026-12-02 UI-3: "Deploy artifacts to all sites" must run on its own DI scope
/// (its own DbContext) — not the circuit's — so the post-fan-out record / audit / revision
/// stamp neither collide with other page queries nor die with the circuit. The scope the
/// deploy ran in is created for the action and disposed when it ends.
///
[Fact]
public void DeployToAllSites_RunsInItsOwnScope_DisposedAfterTheAction()
{
RegisterServices();
_siteRepo.GetAllSitesAsync().Returns(Sites(1));
_siteRepo.GetAllDataConnectionsAsync().Returns(new List());
// The deploy actions demand a fresh Administrator check.
Services.AddSingleton(new TestAuthStateProvider(new ClaimsPrincipal(
new ClaimsIdentity(new[]
{
new Claim(ZB.MOM.WW.ScadaBridge.Security.JwtTokenService.UsernameClaimType, "admin"),
new Claim(ZB.MOM.WW.ScadaBridge.Security.JwtTokenService.RoleClaimType, "Administrator"),
}, "TestAuth"))));
ScopeProbe? deployScope = null;
Services.AddScoped();
Services.AddScoped(sp => new ProbingArtifactDeploymentService(
_siteRepo, sp.GetRequiredService(), sp.GetRequiredService(),
probe => deployScope = probe));
var cut = Render();
cut.FindAll("button").First(b => b.TextContent.Contains("Deploy artifacts to all sites", StringComparison.OrdinalIgnoreCase)).Click();
cut.WaitForAssertion(() => Assert.NotNull(deployScope));
cut.WaitForAssertion(() => Assert.True(deployScope!.Disposed,
"the deploy must own a fresh scope that ends with the action, not the circuit's scope"));
}
}