Merge branch 'deployments-server-paging' — Deployments page server-side paging + status counts (residual #4 / R3)

This commit is contained in:
Joseph Doherty
2026-08-15 03:34:22 -04:00
12 changed files with 1436 additions and 139 deletions
@@ -6,9 +6,8 @@ using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;
using NSubstitute;
using ZB.MOM.WW.ScadaBridge.CentralUI.Auth;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Deployment;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Deployment;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums;
using ZB.MOM.WW.ScadaBridge.DeploymentManager;
using DeploymentsPage = ZB.MOM.WW.ScadaBridge.CentralUI.Components.Pages.Deployment.Deployments;
@@ -23,29 +22,32 @@ namespace ZB.MOM.WW.ScadaBridge.CentralUI.Tests.Deployment;
/// the timer and subscribes to <see cref="IDeploymentStatusNotifier"/>, which
/// <c>DeploymentService</c> raises on every deployment-record status write;
/// Blazor Server then pushes the re-render over its SignalR circuit.
///
/// <para>
/// The "did it reload?" assertions moved from <c>GetAllDeploymentRecordsAsync</c>
/// to <c>QueryDeploymentListPageAsync</c> when the page's read path went
/// server-paged (residual R3) — the push mechanism under test is unchanged, only
/// the query it drives.
/// </para>
/// </summary>
public class DeploymentsPushUpdateTests : BunitContext
{
private IDeploymentManagerRepository _deployRepo = null!;
private ITemplateEngineRepository _templateRepo = null!;
private DeploymentStatusNotifier _notifier = null!;
private void RegisterServices()
{
_deployRepo = Substitute.For<IDeploymentManagerRepository>();
_templateRepo = Substitute.For<ITemplateEngineRepository>();
_notifier = new DeploymentStatusNotifier(NullLogger<DeploymentStatusNotifier>.Instance);
_templateRepo.GetAllInstancesAsync(Arg.Any<CancellationToken>())
.Returns(new List<Instance>
{
new("Inst-1") { Id = 1, SiteId = 1 }
});
_deployRepo.GetAllDeploymentRecordsAsync(Arg.Any<CancellationToken>())
.Returns(new List<DeploymentRecord>());
_deployRepo.QueryDeploymentListPageAsync(
Arg.Any<DeploymentListFilter>(), Arg.Any<int>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
.Returns(DeploymentListPage.Empty);
_deployRepo.GetDeploymentStatusCountsAsync(
Arg.Any<DeploymentListFilter>(), Arg.Any<CancellationToken>())
.Returns(DeploymentStatusCounts.Empty);
Services.AddSingleton(_deployRepo);
Services.AddSingleton(_templateRepo);
Services.AddSingleton<IDeploymentStatusNotifier>(_notifier);
var identity = new ClaimsIdentity(
@@ -80,9 +82,8 @@ public class DeploymentsPushUpdateTests : BunitContext
RegisterServices();
var cut = Render<DeploymentsPage>();
// Initial load: instances + records each fetched once.
// Initial load: the paged query is issued once.
_deployRepo.ClearReceivedCalls();
_templateRepo.ClearReceivedCalls();
// A deployment status write in DeploymentManager raises the notifier;
// the page must reload in response (no polling timer involved).
@@ -90,7 +91,8 @@ public class DeploymentsPushUpdateTests : BunitContext
new DeploymentStatusChange("dep-1", 1, DeploymentStatus.Success));
cut.WaitForAssertion(() =>
_deployRepo.Received().GetAllDeploymentRecordsAsync(Arg.Any<CancellationToken>()));
_deployRepo.Received().QueryDeploymentListPageAsync(
Arg.Any<DeploymentListFilter>(), Arg.Any<int>(), Arg.Any<int>(), Arg.Any<CancellationToken>()));
}
[Fact]
@@ -106,8 +108,8 @@ public class DeploymentsPushUpdateTests : BunitContext
_notifier.NotifyStatusChanged(
new DeploymentStatusChange("dep-2", 1, DeploymentStatus.Failed));
_deployRepo.DidNotReceive()
.GetAllDeploymentRecordsAsync(Arg.Any<CancellationToken>());
_deployRepo.DidNotReceive().QueryDeploymentListPageAsync(
Arg.Any<DeploymentListFilter>(), Arg.Any<int>(), Arg.Any<int>(), Arg.Any<CancellationToken>());
}
/// <summary>
@@ -150,7 +152,7 @@ public class DeploymentsPushUpdateTests : BunitContext
Assert.Null(ex);
// The guard short-circuits before any reload is attempted.
_deployRepo.DidNotReceive()
.GetAllDeploymentRecordsAsync(Arg.Any<CancellationToken>());
_deployRepo.DidNotReceive().QueryDeploymentListPageAsync(
Arg.Any<DeploymentListFilter>(), Arg.Any<int>(), Arg.Any<int>(), Arg.Any<CancellationToken>());
}
}
@@ -5,9 +5,8 @@ using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;
using NSubstitute;
using ZB.MOM.WW.ScadaBridge.CentralUI.Auth;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Deployment;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Deployment;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums;
using ZB.MOM.WW.ScadaBridge.DeploymentManager;
using DeploymentsPage = ZB.MOM.WW.ScadaBridge.CentralUI.Components.Pages.Deployment.Deployments;
@@ -15,31 +14,36 @@ using DeploymentsPage = ZB.MOM.WW.ScadaBridge.CentralUI.Components.Pages.Deploym
namespace ZB.MOM.WW.ScadaBridge.CentralUI.Tests.Deployment;
/// <summary>
/// Regression tests for the Deployment Status push coalescing (arch-review WP2.4). One
/// notifier callback reloads EVERY deployment record plus EVERY instance, and the notifier
/// fires per status write — so a multi-instance deploy produced a stampede of full reloads
/// per circuit. The reload is now leading-edge debounced: the first push after an idle gap
/// is still immediate, and a burst behind it collapses into one trailing reload.
/// Regression tests for the Deployment Status push coalescing (arch-review WP2.4). The
/// notifier fires per status write, so a multi-instance deploy produced a stampede of
/// reloads per circuit. The reload is leading-edge debounced: the first push after an
/// idle gap is still immediate, and a burst behind it collapses into one trailing reload.
///
/// <para>
/// Server-side paging (residual R3) shrank what one reload costs but not how many
/// arrive, so the coalescing still has to hold. The assertions now count
/// <c>QueryDeploymentListPageAsync</c> calls instead of the deleted
/// <c>GetAllDeploymentRecordsAsync</c>.
/// </para>
/// </summary>
public class DeploymentsReloadDebounceTests : BunitContext
{
private IDeploymentManagerRepository _deployRepo = null!;
private ITemplateEngineRepository _templateRepo = null!;
private DeploymentStatusNotifier _notifier = null!;
private void RegisterServices()
{
_deployRepo = Substitute.For<IDeploymentManagerRepository>();
_templateRepo = Substitute.For<ITemplateEngineRepository>();
_notifier = new DeploymentStatusNotifier(NullLogger<DeploymentStatusNotifier>.Instance);
_templateRepo.GetAllInstancesAsync(Arg.Any<CancellationToken>())
.Returns(new List<Instance> { new("Inst-1") { Id = 1, SiteId = 1 } });
_deployRepo.GetAllDeploymentRecordsAsync(Arg.Any<CancellationToken>())
.Returns(new List<DeploymentRecord>());
_deployRepo.QueryDeploymentListPageAsync(
Arg.Any<DeploymentListFilter>(), Arg.Any<int>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
.Returns(DeploymentListPage.Empty);
_deployRepo.GetDeploymentStatusCountsAsync(
Arg.Any<DeploymentListFilter>(), Arg.Any<CancellationToken>())
.Returns(DeploymentStatusCounts.Empty);
Services.AddSingleton(_deployRepo);
Services.AddSingleton(_templateRepo);
Services.AddSingleton<IDeploymentStatusNotifier>(_notifier);
var identity = new ClaimsIdentity(
@@ -58,13 +62,17 @@ public class DeploymentsReloadDebounceTests : BunitContext
=> Task.FromResult(_state);
}
private void AssertReloaded(IRenderedComponent<DeploymentsPage> cut) =>
cut.WaitForAssertion(() =>
_deployRepo.Received().QueryDeploymentListPageAsync(
Arg.Any<DeploymentListFilter>(), Arg.Any<int>(), Arg.Any<int>(), Arg.Any<CancellationToken>()));
[Fact]
public void BurstOfStatusWrites_CollapsesIntoFarFewerReloads()
{
RegisterServices();
var cut = Render<DeploymentsPage>();
cut.WaitForAssertion(() =>
_deployRepo.Received().GetAllDeploymentRecordsAsync(Arg.Any<CancellationToken>()));
AssertReloaded(cut);
_deployRepo.ClearReceivedCalls();
// A 40-instance site deploy: every status write raises the notifier.
@@ -75,14 +83,13 @@ public class DeploymentsReloadDebounceTests : BunitContext
}
// Leading edge fires at once; the rest ride one trailing reload.
cut.WaitForAssertion(() =>
_deployRepo.Received().GetAllDeploymentRecordsAsync(Arg.Any<CancellationToken>()));
AssertReloaded(cut);
// Let the trailing window close before counting.
Thread.Sleep(900);
var reloads = _deployRepo.ReceivedCalls()
.Count(c => c.GetMethodInfo().Name == nameof(IDeploymentManagerRepository.GetAllDeploymentRecordsAsync));
.Count(c => c.GetMethodInfo().Name == nameof(IDeploymentManagerRepository.QueryDeploymentListPageAsync));
Assert.InRange(reloads, 1, 4);
}
@@ -91,8 +98,7 @@ public class DeploymentsReloadDebounceTests : BunitContext
{
RegisterServices();
var cut = Render<DeploymentsPage>();
cut.WaitForAssertion(() =>
_deployRepo.Received().GetAllDeploymentRecordsAsync(Arg.Any<CancellationToken>()));
AssertReloaded(cut);
_deployRepo.ClearReceivedCalls();
// Idle since the initial load — the leading edge must not wait out the window.
@@ -101,7 +107,8 @@ public class DeploymentsReloadDebounceTests : BunitContext
new DeploymentStatusChange("dep-1", 1, DeploymentStatus.Success));
cut.WaitForAssertion(
() => _deployRepo.Received().GetAllDeploymentRecordsAsync(Arg.Any<CancellationToken>()),
() => _deployRepo.Received().QueryDeploymentListPageAsync(
Arg.Any<DeploymentListFilter>(), Arg.Any<int>(), Arg.Any<int>(), Arg.Any<CancellationToken>()),
TimeSpan.FromMilliseconds(400));
}
@@ -110,8 +117,7 @@ public class DeploymentsReloadDebounceTests : BunitContext
{
RegisterServices();
var cut = Render<DeploymentsPage>();
cut.WaitForAssertion(() =>
_deployRepo.Received().GetAllDeploymentRecordsAsync(Arg.Any<CancellationToken>()));
AssertReloaded(cut);
// Two pushes: the first takes the leading edge, the second arms the trailing timer.
_notifier.NotifyStatusChanged(new DeploymentStatusChange("dep-1", 1, DeploymentStatus.InProgress));
@@ -122,6 +128,7 @@ public class DeploymentsReloadDebounceTests : BunitContext
// The armed timer must be disposed with the component, not fire against it.
Thread.Sleep(900);
_deployRepo.DidNotReceive().GetAllDeploymentRecordsAsync(Arg.Any<CancellationToken>());
_deployRepo.DidNotReceive().QueryDeploymentListPageAsync(
Arg.Any<DeploymentListFilter>(), Arg.Any<int>(), Arg.Any<int>(), Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,323 @@
using System.Security.Claims;
using Bunit;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;
using NSubstitute;
using ZB.MOM.WW.ScadaBridge.CentralUI.Auth;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Deployment;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums;
using ZB.MOM.WW.ScadaBridge.DeploymentManager;
using ZB.MOM.WW.ScadaBridge.Security;
using DeploymentsPage = ZB.MOM.WW.ScadaBridge.CentralUI.Components.Pages.Deployment.Deployments;
namespace ZB.MOM.WW.ScadaBridge.CentralUI.Tests.Deployment;
/// <summary>
/// Coverage for the Deployment Status page's server-side paging, server-computed
/// status tiles and debounced filter input (residual R3).
///
/// <para>
/// Before this change the page read EVERY deployment record and EVERY instance on
/// each load, then site-scoped, sorted, counted the four tiles and sliced a 25-row
/// page in the Blazor circuit's memory. These tests pin the replacement contract:
/// the page asks the repository for ONE page plus the filtered total, asks for the
/// tile counts separately, pushes the site-scope grant into the query rather than
/// intersecting in memory, and never touches the instance repository.
/// </para>
/// </summary>
public class DeploymentsServerPagingTests : BunitContext
{
private IDeploymentManagerRepository _deployRepo = null!;
private ITemplateEngineRepository _templateRepo = null!;
private DeploymentStatusNotifier _notifier = null!;
/// <summary>Records every filter/page/pageSize triple the page queried with.</summary>
private readonly List<(DeploymentListFilter Filter, int Page, int PageSize)> _pageCalls = new();
private void RegisterServices(
DeploymentListPage? page = null,
DeploymentStatusCounts? counts = null,
string[]? siteClaims = null)
{
_deployRepo = Substitute.For<IDeploymentManagerRepository>();
_templateRepo = Substitute.For<ITemplateEngineRepository>();
_notifier = new DeploymentStatusNotifier(NullLogger<DeploymentStatusNotifier>.Instance);
var resultPage = page ?? DeploymentListPage.Empty;
_deployRepo.QueryDeploymentListPageAsync(
Arg.Any<DeploymentListFilter>(), Arg.Any<int>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
.Returns(ci =>
{
_pageCalls.Add((ci.ArgAt<DeploymentListFilter>(0), ci.ArgAt<int>(1), ci.ArgAt<int>(2)));
return Task.FromResult(resultPage);
});
_deployRepo.GetDeploymentStatusCountsAsync(
Arg.Any<DeploymentListFilter>(), Arg.Any<CancellationToken>())
.Returns(counts ?? DeploymentStatusCounts.Empty);
Services.AddSingleton(_deployRepo);
Services.AddSingleton(_templateRepo);
Services.AddSingleton<IDeploymentStatusNotifier>(_notifier);
var claims = new List<Claim> { new(ClaimTypes.Name, "deployer") };
foreach (var siteId in siteClaims ?? Array.Empty<string>())
{
claims.Add(new Claim(JwtTokenService.SiteIdClaimType, siteId));
}
var identity = new ClaimsIdentity(claims, "TestCookie");
var stubAuth = new StubAuthStateProvider(
new AuthenticationState(new ClaimsPrincipal(identity)));
Services.AddSingleton<AuthenticationStateProvider>(stubAuth);
Services.AddScoped(_ => new SiteScopeService(stubAuth));
}
private sealed class StubAuthStateProvider : AuthenticationStateProvider
{
private readonly AuthenticationState _state;
public StubAuthStateProvider(AuthenticationState state) => _state = state;
public override Task<AuthenticationState> GetAuthenticationStateAsync()
=> Task.FromResult(_state);
}
private static DeploymentListRow Row(int id, string instance, DeploymentStatus status = DeploymentStatus.Success) =>
new(
Id: id,
DeploymentId: $"dep-{id:D4}",
InstanceId: id,
InstanceUniqueName: instance,
SiteId: 1,
Status: status,
RevisionHash: $"rev{id:D4}hash",
DeployedBy: "deployer",
DeployedAt: DateTimeOffset.UtcNow.AddMinutes(-id),
CompletedAt: DateTimeOffset.UtcNow,
ErrorMessage: null);
// ── Paging ────────────────────────────────────────────────────────────────
[Fact]
public void InitialLoad_RequestsPageOneFromTheServer_AndNeverReadsEveryInstance()
{
RegisterServices(new DeploymentListPage(new[] { Row(1, "Inst-1") }, TotalCount: 1));
Render<DeploymentsPage>();
var call = Assert.Single(_pageCalls);
Assert.Equal(1, call.Page);
Assert.Equal(25, call.PageSize);
// The full-instance-table read that used to build the name/site maps is gone.
_templateRepo.DidNotReceiveWithAnyArgs().GetAllInstancesAsync();
}
[Fact]
public void TotalCountFromServer_DrivesThePager_NotTheRowsOnScreen()
{
// One page of 25 rows out of 130 total => 6 pages. Under the old
// client-materialized model the pager could only ever see the rows it held.
var rows = Enumerable.Range(1, 25).Select(i => Row(i, $"Inst-{i}")).ToList();
RegisterServices(new DeploymentListPage(rows, TotalCount: 130));
var cut = Render<DeploymentsPage>();
Assert.Contains("130 matching deployments", cut.Find("[data-test=\"deploy-result-count\"]").TextContent);
// Windowed pager: first, last and a radius around the current page.
var pageButtons = cut.FindAll("ul.pagination li.page-item").Count;
Assert.True(pageButtons > 2, "Pager must render page buttons, not just Previous/Next.");
Assert.Contains("6", cut.Find("ul.pagination").TextContent);
}
[Fact]
public void NextPage_RequeriesTheServerForPageTwo()
{
var rows = Enumerable.Range(1, 25).Select(i => Row(i, $"Inst-{i}")).ToList();
RegisterServices(new DeploymentListPage(rows, TotalCount: 130));
var cut = Render<DeploymentsPage>();
_pageCalls.Clear();
cut.Find("[data-test=\"deploy-page-next\"]").Click();
var call = Assert.Single(_pageCalls);
Assert.Equal(2, call.Page);
}
[Fact]
public void SinglePageResult_RendersNoPager()
{
RegisterServices(new DeploymentListPage(new[] { Row(1, "Inst-1") }, TotalCount: 1));
var cut = Render<DeploymentsPage>();
Assert.Empty(cut.FindAll("ul.pagination"));
}
// ── Status tiles ──────────────────────────────────────────────────────────
[Fact]
public void Tiles_RenderServerComputedCounts_NotCountsOfTheVisiblePage()
{
// The page holds ONE row, but the server reports fleet-wide counts. Under
// the old model the tiles were Count() over the in-memory list, so paging
// would have silently reduced them to per-page counts.
RegisterServices(
new DeploymentListPage(new[] { Row(1, "Inst-1") }, TotalCount: 400),
new DeploymentStatusCounts(Pending: 7, InProgress: 3, Success: 380, Failed: 10));
var cut = Render<DeploymentsPage>();
Assert.Contains("7", cut.Find("[data-test=\"deploy-tile-pending\"]").TextContent);
Assert.Contains("3", cut.Find("[data-test=\"deploy-tile-inprogress\"]").TextContent);
Assert.Contains("380", cut.Find("[data-test=\"deploy-tile-success\"]").TextContent);
Assert.Contains("10", cut.Find("[data-test=\"deploy-tile-failed\"]").TextContent);
Assert.Contains("400", cut.Find("[data-test=\"deploy-tile-all\"]").TextContent);
}
[Fact]
public void ClickingAStatusTile_AppliesTheFilterServerSide_AndResetsToPageOne()
{
var rows = Enumerable.Range(1, 25).Select(i => Row(i, $"Inst-{i}")).ToList();
RegisterServices(new DeploymentListPage(rows, TotalCount: 130));
var cut = Render<DeploymentsPage>();
cut.Find("[data-test=\"deploy-page-next\"]").Click();
_pageCalls.Clear();
cut.Find("[data-test=\"deploy-tile-failed\"]").Click();
var call = Assert.Single(_pageCalls);
Assert.Equal(DeploymentStatus.Failed, call.Filter.Status);
Assert.Equal(1, call.Page);
Assert.Equal("true", cut.Find("[data-test=\"deploy-tile-failed\"]").GetAttribute("aria-pressed"));
}
[Fact]
public void ClickingTheActiveTileAgain_ClearsTheStatusFilter()
{
RegisterServices(new DeploymentListPage(new[] { Row(1, "Inst-1") }, TotalCount: 1));
var cut = Render<DeploymentsPage>();
cut.Find("[data-test=\"deploy-tile-pending\"]").Click();
_pageCalls.Clear();
cut.Find("[data-test=\"deploy-tile-pending\"]").Click();
var call = Assert.Single(_pageCalls);
Assert.Null(call.Filter.Status);
Assert.Equal("true", cut.Find("[data-test=\"deploy-tile-all\"]").GetAttribute("aria-pressed"));
}
// ── Site scoping ──────────────────────────────────────────────────────────
[Fact]
public void SystemWideUser_QueriesWithNoSiteScope()
{
RegisterServices();
Render<DeploymentsPage>();
Assert.Null(Assert.Single(_pageCalls).Filter.SiteIdScope);
}
[Fact]
public void SiteScopedUser_PushesThePermittedSiteIdsIntoTheQuery()
{
RegisterServices(siteClaims: new[] { "3", "7" });
Render<DeploymentsPage>();
var scope = Assert.Single(_pageCalls).Filter.SiteIdScope;
Assert.NotNull(scope);
Assert.Equal(new[] { 3, 7 }, scope!.OrderBy(x => x));
}
// ── Filter debounce ───────────────────────────────────────────────────────
[Fact]
public void SearchInput_IsDebounced_SoABurstOfKeystrokesIssuesOneQuery()
{
RegisterServices(new DeploymentListPage(new[] { Row(1, "Inst-1") }, TotalCount: 1));
var cut = Render<DeploymentsPage>();
_pageCalls.Clear();
// Type "Reactor" one character at a time, well inside the 500ms window.
const string term = "Reactor";
for (var i = 1; i <= term.Length; i++)
{
cut.Find("[data-test=\"deploy-search\"]").Input(term[..i]);
}
// No query yet — the trailing debounce has not elapsed.
Assert.Empty(_pageCalls);
cut.WaitForAssertion(() => Assert.NotEmpty(_pageCalls), TimeSpan.FromSeconds(3));
Thread.Sleep(300);
var call = Assert.Single(_pageCalls);
Assert.Equal(term, call.Filter.Search);
Assert.Equal(1, call.Page);
}
[Fact]
public void ClearFilters_ResetsSearchAndStatus_AndRequeries()
{
RegisterServices(new DeploymentListPage(new[] { Row(1, "Inst-1") }, TotalCount: 1));
var cut = Render<DeploymentsPage>();
cut.Find("[data-test=\"deploy-tile-failed\"]").Click();
_pageCalls.Clear();
cut.Find("[data-test=\"deploy-clear-filters\"]").Click();
var call = Assert.Single(_pageCalls);
Assert.Null(call.Filter.Status);
Assert.Null(call.Filter.NormalizedSearch);
Assert.Equal(1, call.Page);
}
[Fact]
public void ClearFilters_IsEnabledAsSoonAsTheOperatorTypes_NotOnlyOnceTheDebounceFires()
{
RegisterServices(new DeploymentListPage(new[] { Row(1, "Inst-1") }, TotalCount: 1));
var cut = Render<DeploymentsPage>();
Assert.True(cut.Find("[data-test=\"deploy-clear-filters\"]").HasAttribute("disabled"));
cut.Find("[data-test=\"deploy-search\"]").Input("Rea");
// Still inside the 500ms window — the escape hatch must not be dead.
Assert.False(cut.Find("[data-test=\"deploy-clear-filters\"]").HasAttribute("disabled"));
}
[Fact]
public void DisposeWithAnArmedFilterTimer_DoesNotQuery()
{
RegisterServices(new DeploymentListPage(new[] { Row(1, "Inst-1") }, TotalCount: 1));
var cut = Render<DeploymentsPage>();
cut.Find("[data-test=\"deploy-search\"]").Input("abc");
cut.Instance.Dispose();
_pageCalls.Clear();
Thread.Sleep(900);
Assert.Empty(_pageCalls);
}
// ── Rendering ─────────────────────────────────────────────────────────────
[Fact]
public void InstanceName_ComesFromTheJoinedRow_NotAClientSideLookupTable()
{
RegisterServices(new DeploymentListPage(new[] { Row(42, "Line3.Filler") }, TotalCount: 1));
var cut = Render<DeploymentsPage>();
Assert.Contains("Line3.Filler", cut.Markup);
}
}
@@ -0,0 +1,375 @@
using Microsoft.EntityFrameworkCore;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Deployment;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Deployment;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums;
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Repositories;
namespace ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests;
/// <summary>
/// Coverage for the Central UI deployment-status page's server-side read path —
/// <see cref="DeploymentManagerRepository.QueryDeploymentListPageAsync"/> and
/// <see cref="DeploymentManagerRepository.GetDeploymentStatusCountsAsync"/>
/// (residual R3).
///
/// <para>
/// These replace a whole-table <c>GetAllDeploymentRecords</c> read whose only
/// caller then site-scoped, sorted, counted the status tiles and sliced a page in
/// the Blazor circuit's memory. Every one of those jobs is asserted here to happen
/// in SQL instead: the filter dimensions, the total count, the deterministic
/// ordering that makes offset paging safe, and the grouped tile aggregation.
/// </para>
///
/// <para>
/// Uses the shared SQLite in-memory fixture. It enforces the
/// <c>DeploymentRecord → Instance</c> FK, which is exactly the relationship the
/// new query's inner join relies on, so the seeds are real Site/Template/Instance
/// rows.
/// </para>
/// </summary>
public class DeploymentListQueryRepositoryTests : IDisposable
{
private readonly ScadaBridgeDbContext _context;
private readonly DeploymentManagerRepository _repository;
private readonly DateTimeOffset _base = new(2026, 8, 15, 12, 0, 0, TimeSpan.Zero);
public DeploymentListQueryRepositoryTests()
{
_context = SqliteTestHelper.CreateInMemoryContext();
_repository = new DeploymentManagerRepository(_context);
}
public void Dispose()
{
_context.Database.CloseConnection();
_context.Dispose();
GC.SuppressFinalize(this);
}
private async Task<int> SeedSiteAsync(string name)
{
var site = new Site(name, name);
_context.Sites.Add(site);
await _context.SaveChangesAsync();
return site.Id;
}
private async Task<int> SeedInstanceAsync(string uniqueName, int siteId)
{
var template = new Template($"T-{uniqueName}");
_context.Templates.Add(template);
await _context.SaveChangesAsync();
var instance = new Instance(uniqueName) { SiteId = siteId, TemplateId = template.Id };
_context.Instances.Add(instance);
await _context.SaveChangesAsync();
return instance.Id;
}
private async Task<DeploymentRecord> SeedRecordAsync(
string deploymentId,
int instanceId,
DeploymentStatus status,
DateTimeOffset deployedAt,
string deployedBy = "alice",
string? revisionHash = null)
{
var record = new DeploymentRecord(deploymentId, deployedBy)
{
InstanceId = instanceId,
Status = status,
DeployedAt = deployedAt,
RevisionHash = revisionHash
};
_context.DeploymentRecords.Add(record);
await _context.SaveChangesAsync();
return record;
}
// ── Paging ────────────────────────────────────────────────────────────────
[Fact]
public async Task QueryPage_ReturnsRequestedSlice_AndTheTotalCountOfTheWholeSet()
{
var siteId = await SeedSiteAsync("S1");
var instanceId = await SeedInstanceAsync("Inst-1", siteId);
for (var i = 0; i < 25; i++)
{
await SeedRecordAsync($"dep-{i:D3}", instanceId, DeploymentStatus.Success, _base.AddMinutes(i));
}
var page2 = await _repository.QueryDeploymentListPageAsync(
new DeploymentListFilter(), pageNumber: 2, pageSize: 10);
Assert.Equal(25, page2.TotalCount);
Assert.Equal(10, page2.Rows.Count);
Assert.Equal(3, page2.PageCount(10));
// Newest first: page 2 of 10 starts at the 11th newest, dep-014.
Assert.Equal("dep-014", page2.Rows[0].DeploymentId);
Assert.Equal("dep-005", page2.Rows[^1].DeploymentId);
}
[Fact]
public async Task QueryPage_PagesDoNotOverlapOrDropRows_EvenWhenDeployedAtTies()
{
// Rapid redeploys write several records on the same clock tick. Without the
// Id tie-break the sort key is unstable and offset paging repeats or drops
// rows between pages — the failure mode the ThenByDescending(Id) prevents.
var siteId = await SeedSiteAsync("S1");
var instanceId = await SeedInstanceAsync("Inst-1", siteId);
for (var i = 0; i < 9; i++)
{
await SeedRecordAsync($"dep-{i:D3}", instanceId, DeploymentStatus.Success, _base);
}
var seen = new List<string>();
for (var page = 1; page <= 3; page++)
{
var result = await _repository.QueryDeploymentListPageAsync(
new DeploymentListFilter(), pageNumber: page, pageSize: 3);
seen.AddRange(result.Rows.Select(r => r.DeploymentId));
}
Assert.Equal(9, seen.Count);
Assert.Equal(9, seen.Distinct().Count());
}
[Fact]
public async Task QueryPage_NonPositivePageNumber_IsFlooredAtPageOne()
{
var siteId = await SeedSiteAsync("S1");
var instanceId = await SeedInstanceAsync("Inst-1", siteId);
await SeedRecordAsync("dep-000", instanceId, DeploymentStatus.Success, _base);
var page = await _repository.QueryDeploymentListPageAsync(
new DeploymentListFilter(), pageNumber: 0, pageSize: 10);
Assert.Single(page.Rows);
}
[Fact]
public async Task QueryPage_OversizedPageSize_IsClampedToTheMaximum()
{
var siteId = await SeedSiteAsync("S1");
var instanceId = await SeedInstanceAsync("Inst-1", siteId);
await SeedRecordAsync("dep-000", instanceId, DeploymentStatus.Success, _base);
// A caller asking for int.MaxValue rows must not be able to turn the paged
// read back into the whole-table read it replaced.
var page = await _repository.QueryDeploymentListPageAsync(
new DeploymentListFilter(), pageNumber: 1, pageSize: int.MaxValue);
Assert.Single(page.Rows);
Assert.True(DeploymentRecordSummary.MaxPageSize > 0);
}
[Fact]
public async Task QueryPage_PastTheEnd_ReturnsNoRowsButStillReportsTheTotal()
{
var siteId = await SeedSiteAsync("S1");
var instanceId = await SeedInstanceAsync("Inst-1", siteId);
await SeedRecordAsync("dep-000", instanceId, DeploymentStatus.Success, _base);
var page = await _repository.QueryDeploymentListPageAsync(
new DeploymentListFilter(), pageNumber: 9, pageSize: 25);
Assert.Empty(page.Rows);
Assert.Equal(1, page.TotalCount);
}
// ── Joined projection ─────────────────────────────────────────────────────
[Fact]
public async Task QueryPage_JoinsTheInstance_SoNameAndSiteTravelWithTheRow()
{
var siteId = await SeedSiteAsync("S1");
var instanceId = await SeedInstanceAsync("Line3.Filler", siteId);
await SeedRecordAsync("dep-000", instanceId, DeploymentStatus.Failed, _base,
deployedBy: "bob", revisionHash: "abc123");
var row = Assert.Single(
(await _repository.QueryDeploymentListPageAsync(new DeploymentListFilter(), 1, 25)).Rows);
Assert.Equal("Line3.Filler", row.InstanceUniqueName);
Assert.Equal(siteId, row.SiteId);
Assert.Equal(instanceId, row.InstanceId);
Assert.Equal("dep-000", row.DeploymentId);
Assert.Equal(DeploymentStatus.Failed, row.Status);
Assert.Equal("bob", row.DeployedBy);
Assert.Equal("abc123", row.RevisionHash);
}
// ── Filters ───────────────────────────────────────────────────────────────
[Fact]
public async Task QueryPage_StatusFilter_IsAppliedInTheDatabase()
{
var siteId = await SeedSiteAsync("S1");
var instanceId = await SeedInstanceAsync("Inst-1", siteId);
await SeedRecordAsync("dep-ok", instanceId, DeploymentStatus.Success, _base);
await SeedRecordAsync("dep-bad", instanceId, DeploymentStatus.Failed, _base.AddMinutes(1));
var page = await _repository.QueryDeploymentListPageAsync(
new DeploymentListFilter(Status: DeploymentStatus.Failed), 1, 25);
Assert.Equal(1, page.TotalCount);
Assert.Equal("dep-bad", Assert.Single(page.Rows).DeploymentId);
}
[Fact]
public async Task QueryPage_InstanceFilter_RestrictsToOneInstanceHistory()
{
var siteId = await SeedSiteAsync("S1");
var a = await SeedInstanceAsync("Inst-A", siteId);
var b = await SeedInstanceAsync("Inst-B", siteId);
await SeedRecordAsync("dep-a", a, DeploymentStatus.Success, _base);
await SeedRecordAsync("dep-b", b, DeploymentStatus.Success, _base);
var page = await _repository.QueryDeploymentListPageAsync(
new DeploymentListFilter(InstanceId: b), 1, 25);
Assert.Equal("dep-b", Assert.Single(page.Rows).DeploymentId);
}
[Theory]
[InlineData("Filler", "dep-a")] // instance unique name
[InlineData("dep-b", "dep-b")] // deployment id
[InlineData("carol", "dep-b")] // initiating user
[InlineData("rev-a", "dep-a")] // revision hash
public async Task QueryPage_Search_MatchesAcrossTheFindableIdentifiers(string term, string expected)
{
var siteId = await SeedSiteAsync("S1");
var a = await SeedInstanceAsync("Line3.Filler", siteId);
var b = await SeedInstanceAsync("Line4.Capper", siteId);
await SeedRecordAsync("dep-a", a, DeploymentStatus.Success, _base, deployedBy: "alice", revisionHash: "rev-a1");
await SeedRecordAsync("dep-b", b, DeploymentStatus.Success, _base.AddMinutes(1), deployedBy: "carol", revisionHash: "rev-b1");
var page = await _repository.QueryDeploymentListPageAsync(
new DeploymentListFilter(Search: term), 1, 25);
Assert.Equal(expected, Assert.Single(page.Rows).DeploymentId);
}
[Fact]
public async Task QueryPage_WhitespaceSearch_IsTreatedAsUnconstrained()
{
var siteId = await SeedSiteAsync("S1");
var instanceId = await SeedInstanceAsync("Inst-1", siteId);
await SeedRecordAsync("dep-000", instanceId, DeploymentStatus.Success, _base);
var page = await _repository.QueryDeploymentListPageAsync(
new DeploymentListFilter(Search: " "), 1, 25);
Assert.Equal(1, page.TotalCount);
}
[Fact]
public async Task QueryPage_SiteScope_RestrictsToTheGrantedSites()
{
var s1 = await SeedSiteAsync("S1");
var s2 = await SeedSiteAsync("S2");
var a = await SeedInstanceAsync("Inst-A", s1);
var b = await SeedInstanceAsync("Inst-B", s2);
await SeedRecordAsync("dep-a", a, DeploymentStatus.Success, _base);
await SeedRecordAsync("dep-b", b, DeploymentStatus.Success, _base.AddMinutes(1));
var page = await _repository.QueryDeploymentListPageAsync(
new DeploymentListFilter(SiteIdScope: new[] { s2 }), 1, 25);
Assert.Equal(1, page.TotalCount);
Assert.Equal("dep-b", Assert.Single(page.Rows).DeploymentId);
}
[Fact]
public async Task QueryPage_EmptySiteScope_IsARealFilterThatMatchesNothing()
{
// A scoped user granted no sites must see nothing — an empty scope must NOT
// degrade into "unconstrained", which would leak every site's deployments.
var siteId = await SeedSiteAsync("S1");
var instanceId = await SeedInstanceAsync("Inst-1", siteId);
await SeedRecordAsync("dep-000", instanceId, DeploymentStatus.Success, _base);
var page = await _repository.QueryDeploymentListPageAsync(
new DeploymentListFilter(SiteIdScope: Array.Empty<int>()), 1, 25);
Assert.Equal(0, page.TotalCount);
Assert.Empty(page.Rows);
}
// ── Status counts ─────────────────────────────────────────────────────────
[Fact]
public async Task StatusCounts_GroupsEveryStatus_WithAbsentOnesReportedAsZero()
{
var siteId = await SeedSiteAsync("S1");
var instanceId = await SeedInstanceAsync("Inst-1", siteId);
await SeedRecordAsync("dep-1", instanceId, DeploymentStatus.Success, _base);
await SeedRecordAsync("dep-2", instanceId, DeploymentStatus.Success, _base.AddMinutes(1));
await SeedRecordAsync("dep-3", instanceId, DeploymentStatus.Failed, _base.AddMinutes(2));
await SeedRecordAsync("dep-4", instanceId, DeploymentStatus.InProgress, _base.AddMinutes(3));
var counts = await _repository.GetDeploymentStatusCountsAsync(new DeploymentListFilter());
Assert.Equal(0, counts.Pending);
Assert.Equal(1, counts.InProgress);
Assert.Equal(2, counts.Success);
Assert.Equal(1, counts.Failed);
Assert.Equal(4, counts.Total);
}
[Fact]
public async Task StatusCounts_IgnoreTheStatusFilter_SoEachTileKeepsItsOwnTotal()
{
// The tiles are the status BREAKDOWN of the filtered set. Honouring the
// active status filter here would zero the other three tiles the moment an
// operator clicked one.
var siteId = await SeedSiteAsync("S1");
var instanceId = await SeedInstanceAsync("Inst-1", siteId);
await SeedRecordAsync("dep-1", instanceId, DeploymentStatus.Success, _base);
await SeedRecordAsync("dep-2", instanceId, DeploymentStatus.Failed, _base.AddMinutes(1));
var counts = await _repository.GetDeploymentStatusCountsAsync(
new DeploymentListFilter(Status: DeploymentStatus.Failed));
Assert.Equal(1, counts.Success);
Assert.Equal(1, counts.Failed);
Assert.Equal(2, counts.Total);
}
[Fact]
public async Task StatusCounts_HonourEveryOtherFilterDimension()
{
var s1 = await SeedSiteAsync("S1");
var s2 = await SeedSiteAsync("S2");
var a = await SeedInstanceAsync("Inst-A", s1);
var b = await SeedInstanceAsync("Inst-B", s2);
await SeedRecordAsync("dep-a1", a, DeploymentStatus.Success, _base);
await SeedRecordAsync("dep-a2", a, DeploymentStatus.Failed, _base.AddMinutes(1));
await SeedRecordAsync("dep-b1", b, DeploymentStatus.Success, _base.AddMinutes(2));
var scoped = await _repository.GetDeploymentStatusCountsAsync(
new DeploymentListFilter(SiteIdScope: new[] { s1 }));
Assert.Equal(2, scoped.Total);
var searched = await _repository.GetDeploymentStatusCountsAsync(
new DeploymentListFilter(Search: "Inst-B"));
Assert.Equal(1, searched.Total);
Assert.Equal(1, searched.Success);
var byInstance = await _repository.GetDeploymentStatusCountsAsync(
new DeploymentListFilter(InstanceId: a));
Assert.Equal(2, byInstance.Total);
}
[Fact]
public async Task StatusCounts_EmptySet_IsAllZeros()
{
var counts = await _repository.GetDeploymentStatusCountsAsync(new DeploymentListFilter());
Assert.Equal(DeploymentStatusCounts.Empty, counts);
}
}