Files
ScadaBridge/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Pages/QueryStringDrillInTests.cs
T
Joseph Doherty 513fa1aa16 docs(tests): fix CommentChecker findings across tests/ — 13,392 → 0 (repo-wide scan clean)
Comment/XML-doc changes only:
- add summaries to ~10k test methods, fixtures, fakes and helpers
  (+ <param> on theories, <returns> on async Task methods,
  <inheritdoc/> on interface implementations the checker can resolve)
- strip ~2.6k project-tracking references (WP*, P*-*, row-NN, Task N,
  #NN, Component-0NN) from comments, keeping the explanatory text;
  reword false positives in comments only
- real docs on fakes implementing BCL/library interfaces
  (IDisposable, ILogger, IOptionsMonitor, IAsyncLifetime)
- reword the last 5 src/ false positives (CWE-1236, failures-1,
  year-0001, M365)

Only non-comment edits: four one-line nested classes split across lines
so members can carry docs. Build 0 errors / 0 warnings.
2026-10-07 15:05:49 -04:00

432 lines
20 KiB
C#

using System.Security.Claims;
using ZB.MOM.WW.ScadaBridge.Security;
using Akka.Actor;
using Bunit;
using Bunit.TestDoubles;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
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.Commons.Interfaces.Transport;
using ZB.MOM.WW.ScadaBridge.Commons.Messages.Audit;
using ZB.MOM.WW.ScadaBridge.Commons.Messages.Notification;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Transport;
using ZB.MOM.WW.ScadaBridge.Communication;
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase;
using ZB.MOM.WW.ScadaBridge.Transport;
using NotificationReportPage = ZB.MOM.WW.ScadaBridge.CentralUI.Components.Pages.Notifications.NotificationReport;
using SiteCallsReportPage = ZB.MOM.WW.ScadaBridge.CentralUI.Components.Pages.SiteCalls.SiteCallsReport;
using TransportImportPage = ZB.MOM.WW.ScadaBridge.CentralUI.Components.Pages.Design.TransportImport;
namespace ZB.MOM.WW.ScadaBridge.CentralUI.Tests.Pages;
/// <summary>
/// Tests for the drill-in / query-string code paths on the two
/// newest pages (TransportImport + SiteCallsReport). The base happy-path cases
/// (Parked, stuck=true, no params) live next to the rest of the page's tests in
/// <c>SiteCallsReportPageTests</c> / <c>TransportImportPageTests</c>; this file
/// fills the remaining gaps the finding called out — unrecognised values, case
/// handling, and the no-query-string default for the Transport wizard.
/// </summary>
public sealed class QueryStringDrillInTests
{
// -----------------------------------------------------------------
// SiteCallsReport — ?status=
// -----------------------------------------------------------------
/// <summary>Verifies that a case-insensitive status query parameter on the site calls report normalises to the canonical casing.</summary>
[Fact]
public void SiteCallsReport_StatusParam_CaseInsensitiveMatch_NormalisesToCanonicalCasing()
{
// The dropdown options use canonical casing ("Parked"). The KPI tiles
// emit canonical, but a hand-crafted ?status=parked URL must still seed
// the filter — the parser is case-insensitive and the seeded value uses
// the canonical casing so the <select> can bind it.
using var ctx = new SiteCallsReportFixture();
var nav = (BunitNavigationManager)ctx.Services.GetRequiredService<NavigationManager>();
nav.NavigateTo("/site-calls/report?status=parked");
var cut = ctx.Render<SiteCallsReportPage>();
cut.WaitForAssertion(() =>
{
Assert.Single(ctx.QueryRequests);
// Normalised to canonical casing (the dropdown's option text), not
// the URL's raw "parked".
Assert.Equal("Parked", ctx.QueryRequests[0].StatusFilter);
});
}
/// <summary>Verifies that an unrecognised status query parameter on the site calls report is silently dropped.</summary>
[Fact]
public void SiteCallsReport_StatusParam_Unrecognised_IsSilentlyDropped()
{
// Lax parsing: an unrecognised status value is ignored, leaving the
// filter empty so the page loads unfiltered. Mirrors AuditLogPage's
// drill-in convention — a hand-crafted bad URL must not break the page.
using var ctx = new SiteCallsReportFixture();
var nav = (BunitNavigationManager)ctx.Services.GetRequiredService<NavigationManager>();
nav.NavigateTo("/site-calls/report?status=NotARealStatus");
var cut = ctx.Render<SiteCallsReportPage>();
cut.WaitForAssertion(() =>
{
Assert.Single(ctx.QueryRequests);
Assert.Null(ctx.QueryRequests[0].StatusFilter);
Assert.False(ctx.QueryRequests[0].StuckOnly);
});
}
/// <summary>Verifies that a non-boolean stuck query parameter on the site calls report is silently dropped.</summary>
[Fact]
public void SiteCallsReport_StuckParam_NonBoolean_IsSilentlyDropped()
{
// bool.TryParse fails for "yes"/"1" — the parser drops the value and
// leaves StuckOnly = false, mirroring the unrecognised-status path.
using var ctx = new SiteCallsReportFixture();
var nav = (BunitNavigationManager)ctx.Services.GetRequiredService<NavigationManager>();
nav.NavigateTo("/site-calls/report?stuck=yes");
var cut = ctx.Render<SiteCallsReportPage>();
cut.WaitForAssertion(() =>
{
Assert.Single(ctx.QueryRequests);
Assert.False(ctx.QueryRequests[0].StuckOnly);
});
}
// -----------------------------------------------------------------
// SiteCallsReport — ?correlationId= (Flow Debugger / Audit Log deep link, D2)
// -----------------------------------------------------------------
/// <summary>Verifies that the correlation id query parameter seeds the operation filter on the site calls report.</summary>
[Fact]
public void SiteCallsReport_CorrelationIdQuery_SeedsTheOperationFilter()
{
// A well-formed GUID rides on the first query as the exact-match
// TrackedOperationIdFilter and renders the read-only Operation pill.
var op = Guid.Parse("44444444-4444-4444-4444-444444444444");
using var ctx = new SiteCallsReportFixture();
var nav = (BunitNavigationManager)ctx.Services.GetRequiredService<NavigationManager>();
nav.NavigateTo($"/site-calls/report?correlationId={op}");
var cut = ctx.Render<SiteCallsReportPage>();
cut.WaitForAssertion(() =>
{
Assert.Single(ctx.QueryRequests);
Assert.Equal(op, ctx.QueryRequests[0].TrackedOperationIdFilter);
var pill = cut.Find("[data-test='site-calls-filter-operation']");
Assert.Contains(op.ToString("N")[..12], pill.TextContent);
});
}
/// <summary>Verifies that a malformed correlation id query parameter on the site calls report is ignored.</summary>
[Fact]
public void SiteCallsReport_CorrelationIdQuery_Malformed_IsIgnored()
{
// Lax parsing, like ?status= — a value that is not a GUID leaves the
// filter null and renders no pill, so a hand-crafted bad URL loads the
// page unfiltered instead of breaking it.
using var ctx = new SiteCallsReportFixture();
var nav = (BunitNavigationManager)ctx.Services.GetRequiredService<NavigationManager>();
nav.NavigateTo("/site-calls/report?correlationId=nope");
var cut = ctx.Render<SiteCallsReportPage>();
cut.WaitForAssertion(() =>
{
Assert.Single(ctx.QueryRequests);
Assert.Null(ctx.QueryRequests[0].TrackedOperationIdFilter);
});
Assert.Empty(cut.FindAll("[data-test='site-calls-filter-operation']"));
}
// -----------------------------------------------------------------
// NotificationReport — ?correlationId= (Flow Debugger follow-ups, D2)
// -----------------------------------------------------------------
/// <summary>Verifies that a blank correlation id query parameter on the notification report is ignored.</summary>
[Fact]
public void NotificationReport_CorrelationIdQuery_Blank_IsIgnored()
{
// A blank/whitespace ?correlationId= is dropped: the first query carries
// no NotificationIdFilter and no pill renders, so a hand-crafted empty
// deep link degrades to the plain unfiltered page.
using var ctx = new NotificationReportFixture();
var nav = (BunitNavigationManager)ctx.Services.GetRequiredService<NavigationManager>();
nav.NavigateTo("/notifications/report?correlationId=%20");
var cut = ctx.Render<NotificationReportPage>();
cut.WaitForAssertion(() =>
{
Assert.Single(ctx.QueryRequests);
Assert.Null(ctx.QueryRequests[0].NotificationIdFilter);
Assert.Empty(cut.FindAll("[data-test='notif-filter-notification']"));
});
}
// -----------------------------------------------------------------
// TransportImport — no query-string parameters on this route
// -----------------------------------------------------------------
/// <summary>
/// TransportImport.razor declares no <c>[Parameter]</c> /
/// <c>SupplyParameterFromQuery</c> bindings — the wizard's initial state is
/// purely <c>ImportWizardStep.Upload</c> regardless of the query-string. This
/// test pins that contract: navigating with an unrecognised query-string
/// param does not throw and does not change the initial step.
/// </summary>
[Fact]
public void TransportImport_UnrecognisedQueryStringParam_DoesNotChangeInitialStep()
{
using var ctx = new TransportImportFixture();
var nav = (BunitNavigationManager)ctx.Services.GetRequiredService<NavigationManager>();
nav.NavigateTo("/design/transport/import?bundleImportId=11111111-1111-1111-1111-111111111111&foo=bar");
var cut = ctx.Render<TransportImportPage>();
// The wizard starts at Upload regardless of any drill-in query string —
// the page has no [Parameter]-bound properties so unknown keys are
// silently ignored by Blazor's parameter binding.
var step = (TransportImportPage.ImportWizardStep)typeof(TransportImportPage)
.GetField("_step",
System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!
.GetValue(cut.Instance)!;
Assert.Equal(TransportImportPage.ImportWizardStep.Upload, step);
// And the first-step InputFile control is rendered — the page came up clean.
Assert.NotNull(cut.Find("input[type='file']"));
}
// -----------------------------------------------------------------
// Test-scoped fixtures — kept inside this file to bound the diff.
// The existing page-level test files have their own larger fixtures;
// these copies are intentionally minimal (only what the drill-in
// tests need).
// -----------------------------------------------------------------
private sealed class SiteCallsReportFixture : BunitContext
{
private readonly ActorSystem _system = ActorSystem.Create("qs-drillin-tests");
public readonly CommunicationService Comms;
public readonly List<SiteCallQueryRequest> QueryRequests = new();
/// <summary>Initializes a new instance of the <c>SiteCallsReportFixture</c> class.</summary>
public SiteCallsReportFixture()
{
Comms = new CommunicationService(
Options.Create(new CommunicationOptions()),
NullLogger<CommunicationService>.Instance);
var auditProxy = _system.ActorOf(Props.Create(() => new ScriptedSiteCallAuditActor(this)));
Comms.SetSiteCallAudit(auditProxy);
Services.AddSingleton(Comms);
Services.AddSingleton<IDialogService>(new AlwaysConfirmDialogService());
// The SiteCallsReport page now injects IKpiHistoryQueryService
// for the Trends section. Provide a stand-in so these drill-in tests render.
Services.AddSingleton(Substitute.For<IKpiHistoryQueryService>());
var siteRepo = Substitute.For<ISiteRepository>();
siteRepo.GetAllSitesAsync(Arg.Any<CancellationToken>())
.Returns(Task.FromResult<IReadOnlyList<Site>>(new List<Site>
{
new("Plant A", "plant-a") { Id = 1 },
}));
Services.AddSingleton(siteRepo);
var claims = new[]
{
new Claim(JwtTokenService.UsernameClaimType, "tester"),
new Claim(JwtTokenService.RoleClaimType, "Deployer"),
};
var user = new ClaimsPrincipal(new ClaimsIdentity(claims, "TestAuth"));
Services.AddSingleton<AuthenticationStateProvider>(new TestAuthStateProvider(user));
Services.AddAuthorizationCore();
Services.AddTestConfigurationMutations();
Services.AddScoped<ZB.MOM.WW.ScadaBridge.CentralUI.Auth.SiteScopeService>();
}
/// <inheritdoc />
protected override void Dispose(bool disposing)
{
if (disposing)
{
_system.Terminate().Wait(TimeSpan.FromSeconds(5));
}
base.Dispose(disposing);
}
}
private sealed class ScriptedSiteCallAuditActor : ReceiveActor
{
/// <summary>Initializes a new instance of the <c>ScriptedSiteCallAuditActor</c> class.</summary>
/// <param name="fixture">The fixture supplying the scripted replies.</param>
public ScriptedSiteCallAuditActor(SiteCallsReportFixture fixture)
{
Receive<SiteCallQueryRequest>(req =>
{
fixture.QueryRequests.Add(req);
Sender.Tell(new SiteCallQueryResponse(
req.CorrelationId, true, null,
new List<SiteCallSummary>(), null, null));
});
}
}
private sealed class NotificationReportFixture : BunitContext
{
private readonly ActorSystem _system = ActorSystem.Create("qs-drillin-notif-tests");
public readonly CommunicationService Comms;
public readonly List<NotificationOutboxQueryRequest> QueryRequests = new();
/// <summary>Initializes a new instance of the <c>NotificationReportFixture</c> class.</summary>
public NotificationReportFixture()
{
Comms = new CommunicationService(
Options.Create(new CommunicationOptions()),
NullLogger<CommunicationService>.Instance);
var outbox = _system.ActorOf(Props.Create(() => new ScriptedNotificationOutboxActor(this)));
Comms.SetNotificationOutbox(outbox);
Services.AddSingleton(Comms);
Services.AddSingleton<IDialogService>(new AlwaysConfirmDialogService());
var siteRepo = Substitute.For<ISiteRepository>();
siteRepo.GetAllSitesAsync(Arg.Any<CancellationToken>())
.Returns(Task.FromResult<IReadOnlyList<Site>>(new List<Site>
{
new("Plant A", "plant-a") { Id = 1 },
}));
Services.AddSingleton(siteRepo);
var claims = new[]
{
new Claim(JwtTokenService.UsernameClaimType, "tester"),
new Claim(JwtTokenService.RoleClaimType, "Deployer"),
};
var user = new ClaimsPrincipal(new ClaimsIdentity(claims, "TestAuth"));
Services.AddSingleton<AuthenticationStateProvider>(new TestAuthStateProvider(user));
Services.AddAuthorizationCore();
Services.AddTestConfigurationMutations();
Services.AddScoped<ZB.MOM.WW.ScadaBridge.CentralUI.Auth.SiteScopeService>();
}
/// <inheritdoc />
protected override void Dispose(bool disposing)
{
if (disposing)
{
_system.Terminate().Wait(TimeSpan.FromSeconds(5));
}
base.Dispose(disposing);
}
}
private sealed class ScriptedNotificationOutboxActor : ReceiveActor
{
/// <summary>Initializes a new instance of the <c>ScriptedNotificationOutboxActor</c> class.</summary>
/// <param name="fixture">The fixture supplying the scripted replies.</param>
public ScriptedNotificationOutboxActor(NotificationReportFixture fixture)
{
Receive<NotificationOutboxQueryRequest>(req =>
{
fixture.QueryRequests.Add(req);
Sender.Tell(new NotificationOutboxQueryResponse(
req.CorrelationId, true, null,
new List<NotificationSummary>(), TotalCount: 0));
});
}
}
private sealed class AlwaysConfirmDialogService : IDialogService
{
/// <inheritdoc />
public Task<bool> ConfirmAsync(string title, string message, bool danger = false, string? confirmLabel = null)
=> Task.FromResult(true);
// Register row 75 added a DialogSeverity overload. This stub auto-confirms
// regardless of severity — it exists to let action paths run end to end, not to
// assert anything about styling.
/// <inheritdoc />
public Task<bool> ConfirmAsync(string title, string message, DialogSeverity severity, string? confirmLabel = null)
=> Task.FromResult(true);
/// <inheritdoc />
public Task<string?> PromptAsync(string title, string label, string initialValue = "", string? placeholder = null)
=> Task.FromResult<string?>(null);
/// <summary>Returns the default result without showing a dialog.</summary>
/// <typeparam name="TResult">The dialog result type.</typeparam>
/// <param name="title">The dialog title.</param>
/// <param name="body">The dialog body fragment.</param>
/// <param name="size">The optional dialog size.</param>
/// <returns>A task that resolves to the default result.</returns>
public Task<TResult?> ShowAsync<TResult>(
string title,
Microsoft.AspNetCore.Components.RenderFragment<DialogContext<TResult>> body,
string? size = null)
=> Task.FromResult<TResult?>(default);
}
private sealed class TransportImportFixture : BunitContext
{
/// <summary>Initializes a new instance of the <c>TransportImportFixture</c> class.</summary>
public TransportImportFixture()
{
JSInterop.Mode = JSRuntimeMode.Loose;
var importer = Substitute.For<IBundleImporter>();
Services.AddSingleton(importer);
Services.AddSingleton(Substitute.For<IAuditService>());
// TransportImport's Map step injects ISiteRepository.
Services.AddSingleton(Substitute.For<ISiteRepository>());
// Register row 44: the wizard reads the circuit's client IP for the
// per-IP unlock throttle. No HTTP context under bUnit — use the seam.
Services.AddSingleton(new ZB.MOM.WW.ScadaBridge.CentralUI.Auth.CircuitClientAddressProvider(
clientAddress: null));
Services.AddSingleton<IOptions<TransportOptions>>(
Microsoft.Extensions.Options.Options.Create(new TransportOptions
{
MaxBundleSizeMb = 10,
MaxUnlockAttemptsPerSession = 3,
}));
var dbOptions = new DbContextOptionsBuilder<ScadaBridgeDbContext>()
.UseSqlite("DataSource=:memory:")
.ConfigureWarnings(w => w.Ignore(RelationalEventId.AmbientTransactionWarning))
.Options;
var dbContext = new ScadaBridgeDbContext(dbOptions);
dbContext.Database.OpenConnection();
dbContext.Database.EnsureCreated();
Services.AddSingleton(dbContext);
var claims = new List<Claim>
{
new(ZB.MOM.WW.ScadaBridge.Security.JwtTokenService.UsernameClaimType, "alice"),
new(ZB.MOM.WW.ScadaBridge.Security.JwtTokenService.RoleClaimType, "Administrator"),
};
var principal = new ClaimsPrincipal(new ClaimsIdentity(claims, "TestAuth"));
Services.AddSingleton<AuthenticationStateProvider>(new TestAuthStateProvider(principal));
Services.AddAuthorizationCore();
Services.AddTestConfigurationMutations();
}
}
}