Files
ScadaBridge/tests/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests/Repositories/NotificationOutboxRepositoryIntegrationTests.cs
T
Joseph Doherty 5a052c6327 fix(ui): apply site scope and the history status filter in the server query, before paging (UI-7, UI-9, UI-10, WP1 task 1.7)
UI-7: Site Calls and the Notification report sent an unscoped query and
dropped other sites' rows client-side after paging - Site Calls pages
went short (Next disabled, own rows hidden), Notifications showed other
sites' counts and empty pages. New additive SourceSitesFilter on
SiteCallQueryRequest / NotificationOutboxQueryRequest (+ SourceSites /
SourceSiteIds on the repository filters; OPENJSON IN-list in the
SiteCalls keyset SQL, Contains in EF) carries the permitted identifiers;
an empty set matches nothing. Next is gated on the server page size.

UI-9: Secured Writes history paged over every status and filtered
terminal rows client-side. Additive ListSecuredWritesCommand.Statuses
reaches the repository query and count.

UI-10: Notification KPIs per-site table is narrowed to the caller's
sites (SiteScopeService.Resolve on the principal).

Tests: MSSQL mixed-site keyset/offset paging + count for both repos and
the secured-write status set; handler forwards Statuses; UI pages send
the permitted set (scoped) / none (system-wide); history requests the
terminal statuses; KPI per-site rows narrowed.
2026-12-03 10:21:01 -05:00

214 lines
9.3 KiB
C#

using Microsoft.EntityFrameworkCore;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Notifications;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Notifications;
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase;
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Repositories;
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests.Migrations;
using Xunit;
namespace ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests.Repositories;
/// <summary>
/// Race-fix integration tests for
/// <see cref="NotificationOutboxRepository.InsertIfNotExistsAsync"/>. The method
/// is raw-SQL (<c>IF NOT EXISTS … INSERT</c>) matching the AuditLog and SiteCalls
/// idempotent-insert pattern; it must execute against a real SQL Server schema,
/// so this class uses <see cref="MsSqlMigrationFixture"/> rather than the SQLite
/// in-memory provider used by <see cref="RepositoryCoverageTests"/>.
/// </summary>
public class NotificationOutboxRepositoryIntegrationTests : IClassFixture<MsSqlMigrationFixture>
{
private readonly MsSqlMigrationFixture _fixture;
/// <summary>Initializes a new instance of the <c>NotificationOutboxRepositoryIntegrationTests</c> class.</summary>
/// <param name="fixture">The shared database fixture.</param>
public NotificationOutboxRepositoryIntegrationTests(MsSqlMigrationFixture fixture)
{
_fixture = fixture;
}
/// <summary>Verifies that inserting a fresh id inserts the row and returns true.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[SkippableFact]
public async Task InsertIfNotExistsAsync_FreshId_InsertsAndReturnsTrue()
{
Skip.IfNot(_fixture.Available, _fixture.SkipReason);
var id = Guid.NewGuid().ToString();
await using var context = CreateContext();
var repo = new NotificationOutboxRepository(context);
var inserted = await repo.InsertIfNotExistsAsync(MakeNotification(id));
Assert.True(inserted);
await using var readContext = CreateContext();
var loaded = await readContext.Notifications.FindAsync(id);
Assert.NotNull(loaded);
Assert.Equal("Subject", loaded!.Subject);
}
/// <summary>Verifies that inserting a duplicate id returns false and leaves the existing row untouched.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[SkippableFact]
public async Task InsertIfNotExistsAsync_DuplicateId_ReturnsFalseAndLeavesExistingRow()
{
Skip.IfNot(_fixture.Available, _fixture.SkipReason);
var id = Guid.NewGuid().ToString();
await using (var context = CreateContext())
{
var repo = new NotificationOutboxRepository(context);
await repo.InsertIfNotExistsAsync(MakeNotification(id, subject: "Original"));
}
await using (var context = CreateContext())
{
var repo = new NotificationOutboxRepository(context);
var inserted = await repo.InsertIfNotExistsAsync(MakeNotification(id, subject: "Changed"));
Assert.False(inserted);
}
await using var readContext = CreateContext();
var loaded = await readContext.Notifications.FindAsync(id);
Assert.NotNull(loaded);
Assert.Equal("Original", loaded!.Subject);
}
/// <summary>Verifies that concurrent inserts of the same id produce exactly one row.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[SkippableFact]
public async Task InsertIfNotExistsAsync_ConcurrentInserts_SameId_OnlyOneRow()
{
Skip.IfNot(_fixture.Available, _fixture.SkipReason);
// Race coverage. The IF NOT EXISTS … INSERT pattern has a
// check-then-act window: two concurrent sessions can both pass the
// EXISTS check and both attempt the INSERT — the loser surfaces as a
// SqlException with Number 2601/2627. The site→central handoff is
// documented at-least-once with insert-if-not-exists, so this collision
// IS the expected contention mode. The race losers MUST be swallowed
// (not bubbled) so the site doesn't retry the same NotificationId
// forever. Final row count must be exactly 1; no exceptions thrown.
var id = Guid.NewGuid().ToString();
await Parallel.ForEachAsync(
Enumerable.Range(0, 50),
new ParallelOptions { MaxDegreeOfParallelism = 50 },
async (_, ct) =>
{
await using var context = CreateContext();
var repo = new NotificationOutboxRepository(context);
await repo.InsertIfNotExistsAsync(MakeNotification(id), ct);
});
await using var readContext = CreateContext();
var count = await readContext.Notifications
.Where(n => n.NotificationId == id)
.CountAsync();
Assert.Equal(1, count);
}
/// <summary>Verifies that filtering by notification id returns exactly that row.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[SkippableFact]
public async Task QueryAsync_NotificationIdFilter_ReturnsExactlyThatRow()
{
Skip.IfNot(_fixture.Available, _fixture.SkipReason);
// Flow Debugger / Audit Log ?correlationId= deep link: an exact match on one
// NotificationId must return that single row and count it alone.
var wantedId = Guid.NewGuid().ToString();
var otherId = Guid.NewGuid().ToString();
await using (var context = CreateContext())
{
var repo = new NotificationOutboxRepository(context);
await repo.InsertIfNotExistsAsync(MakeNotification(wantedId, subject: "Wanted"));
await repo.InsertIfNotExistsAsync(MakeNotification(otherId, subject: "Other"));
}
await using var queryContext = CreateContext();
var queryRepo = new NotificationOutboxRepository(queryContext);
var (rows, totalCount) = await queryRepo.QueryAsync(
new NotificationOutboxFilter(NotificationId: wantedId), pageNumber: 1, pageSize: 50);
Assert.Equal(1, totalCount);
var row = Assert.Single(rows);
Assert.Equal(wantedId, row.NotificationId);
Assert.Equal("Wanted", row.Subject);
}
/// <summary>
/// Code review 2026-12-02 UI-7: the permitted-sites filter is applied in the query, so the
/// page AND the total count cover only rows the scoped caller may see (pre-fix the count
/// included every site and pages came back partly or wholly empty after client filtering).
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[SkippableFact]
public async Task QueryAsync_SourceSiteIdsFilter_PagesAndCountsInScopeRowsOnly()
{
Skip.IfNot(_fixture.Available, _fixture.SkipReason);
var mine = "site-ui7-" + Guid.NewGuid().ToString("N")[..8];
var other = "site-ui7-" + Guid.NewGuid().ToString("N")[..8];
await using (var context = CreateContext())
{
var repo = new NotificationOutboxRepository(context);
for (var i = 0; i < 3; i++)
await repo.InsertIfNotExistsAsync(MakeNotification(Guid.NewGuid().ToString(), sourceSiteId: mine, minutes: i));
for (var i = 0; i < 7; i++)
await repo.InsertIfNotExistsAsync(MakeNotification(Guid.NewGuid().ToString(), sourceSiteId: other, minutes: 10 + i));
}
await using var queryContext = CreateContext();
var queryRepo = new NotificationOutboxRepository(queryContext);
var (rows, totalCount) = await queryRepo.QueryAsync(
new NotificationOutboxFilter(SourceSiteIds: new[] { mine }), pageNumber: 1, pageSize: 2);
Assert.Equal(3, totalCount);
Assert.Equal(2, rows.Count);
Assert.All(rows, r => Assert.Equal(mine, r.SourceSiteId));
var (page2, _) = await queryRepo.QueryAsync(
new NotificationOutboxFilter(SourceSiteIds: new[] { mine }), pageNumber: 2, pageSize: 2);
Assert.Equal(mine, Assert.Single(page2).SourceSiteId);
var (none, noneCount) = await queryRepo.QueryAsync(
new NotificationOutboxFilter(SourceSiteIds: Array.Empty<string>()), pageNumber: 1, pageSize: 50);
Assert.Empty(none);
Assert.Equal(0, noneCount);
}
// --- helpers ------------------------------------------------------------
private ScadaBridgeDbContext CreateContext()
{
var options = new DbContextOptionsBuilder<ScadaBridgeDbContext>()
.UseSqlServer(_fixture.ConnectionString)
.Options;
return new ScadaBridgeDbContext(options);
}
private static Notification MakeNotification(
string id,
NotificationStatus status = NotificationStatus.Pending,
string subject = "Subject",
string sourceSiteId = "site-cd015",
int minutes = 0)
{
return new Notification(
id,
NotificationType.Email,
"Ops List",
subject,
"Body",
sourceSiteId)
{
Status = status,
CreatedAt = new DateTimeOffset(2026, 5, 20, 10, 0, 0, TimeSpan.Zero).AddMinutes(minutes),
SiteEnqueuedAt = new DateTimeOffset(2026, 5, 20, 9, 59, 0, TimeSpan.Zero),
};
}
}