Files
ScadaBridge/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Services/SharedAlarmSummaryServiceTests.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

226 lines
10 KiB
C#

using Microsoft.Extensions.DependencyInjection;
using NSubstitute;
using ZB.MOM.WW.ScadaBridge.CentralUI.Services;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;
using ZB.MOM.WW.ScadaBridge.Commons.Messages.DebugView;
using ZB.MOM.WW.ScadaBridge.Commons.Messages.Streaming;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums;
using ZB.MOM.WW.ScadaBridge.Communication;
namespace ZB.MOM.WW.ScadaBridge.CentralUI.Tests.Services;
/// <summary>
/// Unit tests for <see cref="SharedAlarmSummaryService"/>. The Alarm
/// Summary page polls per circuit; the shared façade must collapse those into ONE per-site
/// fan-out per freshness window, and must widen that window while the live alarm cache is
/// serving the site (where the poll only still supplies the not-reporting list).
/// </summary>
public class SharedAlarmSummaryServiceTests : IDisposable
{
private const int SiteId = 7;
private const string SiteIdentifier = "plant-a";
private static readonly DateTimeOffset T0 = new(2026, 8, 14, 9, 0, 0, TimeSpan.Zero);
private readonly ITemplateEngineRepository _instanceRepo = Substitute.For<ITemplateEngineRepository>();
private readonly ISiteRepository _siteRepo = Substitute.For<ISiteRepository>();
private readonly IInstanceSnapshotClient _snapshotClient = Substitute.For<IInstanceSnapshotClient>();
private readonly FakeLiveCache _liveCache = new();
private readonly ServiceProvider _provider;
private DateTimeOffset _now = T0;
/// <summary>Initializes a new instance of the <see cref="SharedAlarmSummaryServiceTests"/> class.</summary>
public SharedAlarmSummaryServiceTests()
{
_siteRepo.GetSiteByIdAsync(SiteId, Arg.Any<CancellationToken>())
.Returns(new Site("Plant A", SiteIdentifier) { Id = SiteId });
_instanceRepo.GetInstancesBySiteIdAsync(SiteId, Arg.Any<CancellationToken>())
.Returns(new List<Instance>
{
new("inst-a") { Id = 1, SiteId = SiteId, State = InstanceState.Enabled },
});
_snapshotClient.GetSnapshotAsync(SiteIdentifier, "inst-a", Arg.Any<CancellationToken>())
.Returns(new DebugViewSnapshot(
"inst-a",
Array.Empty<AttributeValueChanged>(),
new[] { new AlarmStateChanged("inst-a", "A-alarm", AlarmState.Active, 500, T0) },
T0));
var services = new ServiceCollection();
services.AddSingleton(_instanceRepo);
services.AddSingleton(_siteRepo);
services.AddSingleton(_snapshotClient);
services.AddScoped<AlarmSummaryService>();
_provider = services.BuildServiceProvider();
}
private SharedAlarmSummaryService CreateSut() =>
new(_provider.GetRequiredService<IServiceScopeFactory>(), _liveCache, () => _now);
/// <summary>Verifies that concurrent circuits share a single fan-out.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task ConcurrentCircuits_ShareOneFanOut()
{
var sut = CreateSut();
var results = await Task.WhenAll(Enumerable.Range(0, 8).Select(_ => sut.GetSiteAlarmsAsync(SiteId)));
await _instanceRepo.Received(1).GetInstancesBySiteIdAsync(SiteId, Arg.Any<CancellationToken>());
Assert.All(results, r => Assert.Single(r.Alarms));
}
/// <summary>Verifies that a cold live cache refreshes within the page tick.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task ColdLiveCache_RefreshesWithinThePageTick()
{
var sut = CreateSut();
_liveCache.Live = false;
await sut.GetSiteAlarmsAsync(SiteId);
// The page polls every 15s and, while the cache is cold, the poll is its
// authoritative rebuild — so the memo must have expired by then.
_now = T0.AddSeconds(15);
await sut.GetSiteAlarmsAsync(SiteId);
await _instanceRepo.Received(2).GetInstancesBySiteIdAsync(SiteId, Arg.Any<CancellationToken>());
}
/// <summary>Verifies that serving from the live cache skips the fan-out entirely.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task LiveCacheServing_SkipsTheFanOutEntirely()
{
// The aggregator's seed/reconcile already ran this exact fan-out and publishes both
// halves of the answer, so the façade must not run a second one — not now, not after
// any elapsed window.
var sut = CreateSut();
_liveCache.Live = true;
_liveCache.NotReporting = new[] { "inst-silent" };
_liveCache.Current = new[]
{
new AlarmStateChanged("inst-a", "A-alarm", AlarmState.Active, 500, T0),
};
var first = await sut.GetSiteAlarmsAsync(SiteId);
_now = T0.AddSeconds(61);
var second = await sut.GetSiteAlarmsAsync(SiteId);
await _instanceRepo.DidNotReceive().GetInstancesBySiteIdAsync(SiteId, Arg.Any<CancellationToken>());
await _snapshotClient.DidNotReceive().GetSnapshotAsync(
Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
// Both halves come from the cache: the rows so a liveness flip mid-call lands on
// last-known state instead of a blank grid, and the not-reporting names the page shows.
foreach (var result in new[] { first, second })
{
Assert.Equal("A-alarm", Assert.Single(result.Alarms).Alarm.AlarmName);
Assert.Equal("inst-silent", Assert.Single(result.NotReportingInstances));
}
}
/// <summary>Verifies that when the live cache goes cold the service falls back to the fan-out.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task LiveCacheGoingCold_FallsBackToTheFanOut()
{
var sut = CreateSut();
_liveCache.Live = true;
await sut.GetSiteAlarmsAsync(SiteId);
await _instanceRepo.DidNotReceive().GetInstancesBySiteIdAsync(SiteId, Arg.Any<CancellationToken>());
// Aggregator died / stream degraded → the poll is the page's rebuild path again.
_liveCache.Live = false;
var result = await sut.GetSiteAlarmsAsync(SiteId);
await _instanceRepo.Received(1).GetInstancesBySiteIdAsync(SiteId, Arg.Any<CancellationToken>());
Assert.Single(result.Alarms);
}
/// <summary>Verifies that different sites do not share a memo slot.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task DifferentSites_DoNotShareAMemoSlot()
{
const int otherSite = 8;
_siteRepo.GetSiteByIdAsync(otherSite, Arg.Any<CancellationToken>())
.Returns(new Site("Plant B", "plant-b") { Id = otherSite });
_instanceRepo.GetInstancesBySiteIdAsync(otherSite, Arg.Any<CancellationToken>())
.Returns(new List<Instance>());
var sut = CreateSut();
await sut.GetSiteAlarmsAsync(SiteId);
await sut.GetSiteAlarmsAsync(otherSite);
await _instanceRepo.Received(1).GetInstancesBySiteIdAsync(SiteId, Arg.Any<CancellationToken>());
await _instanceRepo.Received(1).GetInstancesBySiteIdAsync(otherSite, Arg.Any<CancellationToken>());
}
/// <summary>Verifies that the pure methods return the same results as the direct implementation.</summary>
[Fact]
public void PureMethods_MatchTheDirectImplementation()
{
var sut = CreateSut();
var direct = new AlarmSummaryService(_instanceRepo, _siteRepo, _snapshotClient);
var alarms = new List<AlarmStateChanged>
{
new("inst-b", "B-alarm", AlarmState.Active, 900, T0),
new("inst-a", "A-alarm", AlarmState.Normal, 100, T0),
};
var shared = sut.BuildFromLiveAlarms(alarms);
var expected = direct.BuildFromLiveAlarms(alarms);
Assert.Equal(
expected.Alarms.Select(r => r.Alarm.AlarmName),
shared.Alarms.Select(r => r.Alarm.AlarmName));
var expectedRollup = direct.ComputeRollup(expected.Alarms);
var sharedRollup = sut.ComputeRollup(shared.Alarms);
Assert.Equal(expectedRollup.TotalActive, sharedRollup.TotalActive);
Assert.Equal(expectedRollup.WorstSeverity, sharedRollup.WorstSeverity);
Assert.Equal(expectedRollup.UnackedCount, sharedRollup.UnackedCount);
Assert.Equal(expectedRollup.CountsByKind, sharedRollup.CountsByKind);
}
/// <summary>Releases the resources held by this test class.</summary>
public void Dispose() => _provider.Dispose();
/// <summary>
/// Read-side stub: liveness, the published alarm snapshot, and the aggregator's
/// not-reporting set — the three things the façade reads while the cache is serving a site.
/// </summary>
private sealed class FakeLiveCache : ISiteAlarmLiveCache
{
/// <summary>Gets or sets whether the fake cache reports the site as live.</summary>
public bool Live { get; set; }
/// <summary>Gets or sets the alarms returned as the site's current alarms.</summary>
public IReadOnlyList<AlarmStateChanged> Current { get; set; } = Array.Empty<AlarmStateChanged>();
/// <summary>Gets or sets the instances returned as not reporting.</summary>
public IReadOnlyList<string> NotReporting { get; set; } = Array.Empty<string>();
/// <inheritdoc />
public IDisposable Subscribe(int siteId, Action onChanged) => new NoOp();
/// <inheritdoc />
public IReadOnlyList<AlarmStateChanged> GetCurrentAlarms(int siteId) => Current;
/// <inheritdoc />
public bool IsLive(int siteId) => Live;
/// <inheritdoc />
public IReadOnlyList<string> GetNotReportingInstances(int siteId) => NotReporting;
private sealed class NoOp : IDisposable
{
/// <summary>Does nothing; the no-op subscription holds no resources.</summary>
public void Dispose() { }
}
}
}