Files
ScadaBridge/tests/ZB.MOM.WW.ScadaBridge.DeploymentManager.Tests/FlattenSessionCacheTests.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

163 lines
7.9 KiB
C#

using NSubstitute;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Templates;
using ZB.MOM.WW.ScadaBridge.TemplateEngine.Flattening;
using ZB.MOM.WW.ScadaBridge.TemplateEngine.Validation;
using Template = ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.Template;
using TemplateAttribute = ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.TemplateAttribute;
namespace ZB.MOM.WW.ScadaBridge.DeploymentManager.Tests;
/// <summary>
/// The flatten-session cache. Pins the two properties the bulk deploy path
/// depends on — that N instances sharing a template chain load that chain ONCE per
/// session, and that a template mutation (observed through the watermark)
/// invalidates the memo so a session can never serve stale template state.
/// </summary>
public class FlattenSessionCacheTests
{
private const int TemplateId = 10;
private const int ParentTemplateId = 9;
private const int SiteId = 100;
private readonly ITemplateEngineRepository _templateRepo = Substitute.For<ITemplateEngineRepository>();
private readonly ISiteRepository _siteRepo = Substitute.For<ISiteRepository>();
private readonly ISharedSchemaRepository _sharedSchemaRepo = Substitute.For<ISharedSchemaRepository>();
private readonly TemplateGraphWatermark _watermark = new();
private readonly FlatteningPipeline _sut;
/// <summary>Initializes the test with an in-memory repository and a counting flattening pipeline.</summary>
public FlattenSessionCacheTests()
{
_sharedSchemaRepo.ListAsync(Arg.Any<CancellationToken>()).Returns([]);
_templateRepo.GetAllSharedScriptsAsync(Arg.Any<CancellationToken>()).Returns([]);
_siteRepo.GetDataConnectionsBySiteIdAsync(SiteId, Arg.Any<CancellationToken>()).Returns([]);
_sut = new FlatteningPipeline(
_templateRepo,
_siteRepo,
new FlatteningService(),
new ValidationService(),
new RevisionHashService(),
_sharedSchemaRepo,
_watermark);
}
/// <summary>
/// Seeds a two-link inheritance chain (Tank -> TankBase) and
/// <paramref name="instanceCount"/> instances that all derive from it.
/// </summary>
private void ArrangeSharedChain(int instanceCount)
{
var parent = new Template("TankBase") { Id = ParentTemplateId };
parent.Attributes.Add(new TemplateAttribute("Serial") { DataType = DataType.String, Value = "x" });
var template = new Template("Tank") { Id = TemplateId, ParentTemplateId = ParentTemplateId };
template.Attributes.Add(new TemplateAttribute("Temp") { DataType = DataType.Double, Value = "0" });
_templateRepo.GetTemplateWithChildrenAsync(TemplateId, Arg.Any<CancellationToken>()).Returns(template);
_templateRepo.GetTemplateWithChildrenAsync(ParentTemplateId, Arg.Any<CancellationToken>()).Returns(parent);
_templateRepo.GetCompositionsByTemplateIdAsync(Arg.Any<int>(), Arg.Any<CancellationToken>()).Returns([]);
for (var i = 1; i <= instanceCount; i++)
{
var instance = new Instance($"Tank-{i:00}") { Id = i, TemplateId = TemplateId, SiteId = SiteId };
_templateRepo.GetInstanceByIdAsync(i, Arg.Any<CancellationToken>()).Returns(instance);
}
}
/// <summary>Verifies that shared session, ten instances one template, loads each template once.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task SharedSession_TenInstancesOneTemplate_LoadsEachTemplateOnce()
{
const int instanceCount = 10;
ArrangeSharedChain(instanceCount);
var session = _sut.CreateSession();
for (var i = 1; i <= instanceCount; i++)
{
var result = await _sut.FlattenAndValidateAsync(i, CancellationToken.None, validateScripts: false, session);
Assert.True(result.IsSuccess);
}
// Two templates in the chain, each read exactly once across ten flattens.
await _templateRepo.Received(1).GetTemplateWithChildrenAsync(TemplateId, Arg.Any<CancellationToken>());
await _templateRepo.Received(1).GetTemplateWithChildrenAsync(ParentTemplateId, Arg.Any<CancellationToken>());
// The chain walk itself ran once, not once per instance.
Assert.Equal(1, session.ChainLoads);
Assert.Equal(2, session.TemplateLoads);
// The session-global queries were hoisted out of the per-instance loop:
// shared scripts + schema library once each, site connections once.
await _templateRepo.Received(1).GetAllSharedScriptsAsync(Arg.Any<CancellationToken>());
await _sharedSchemaRepo.Received(1).ListAsync(Arg.Any<CancellationToken>());
await _siteRepo.Received(1).GetDataConnectionsBySiteIdAsync(SiteId, Arg.Any<CancellationToken>());
}
/// <summary>Verifies that no shared session, every instance reloads the chain.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task NoSharedSession_EveryInstanceReloadsTheChain()
{
const int instanceCount = 4;
ArrangeSharedChain(instanceCount);
// Baseline: without a shared session each flatten gets its own private
// one, which is the earlier per-instance behaviour the batch path improves on.
for (var i = 1; i <= instanceCount; i++)
{
var result = await _sut.FlattenAndValidateAsync(i, CancellationToken.None, validateScripts: false);
Assert.True(result.IsSuccess);
}
await _templateRepo.Received(instanceCount)
.GetTemplateWithChildrenAsync(TemplateId, Arg.Any<CancellationToken>());
}
/// <summary>Verifies that template mutation, invalidates memo, so session never serves stale state.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task TemplateMutation_InvalidatesMemo_SoSessionNeverServesStaleState()
{
ArrangeSharedChain(instanceCount: 2);
var session = _sut.CreateSession();
Assert.True((await _sut.FlattenAndValidateAsync(1, CancellationToken.None, validateScripts: false, session)).IsSuccess);
// A template edit lands (the repository bumps the watermark on commit).
_watermark.BumpTemplate(TemplateId);
Assert.True((await _sut.FlattenAndValidateAsync(2, CancellationToken.None, validateScripts: false, session)).IsSuccess);
// The edited template was re-read rather than served from the memo. The
// untouched parent stayed cached — invalidation is per-template, not a
// whole-session reset.
await _templateRepo.Received(2).GetTemplateWithChildrenAsync(TemplateId, Arg.Any<CancellationToken>());
await _templateRepo.Received(1).GetTemplateWithChildrenAsync(ParentTemplateId, Arg.Any<CancellationToken>());
}
/// <summary>Verifies that structural mutation, invalidates cached chain membership.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task StructuralMutation_InvalidatesCachedChainMembership()
{
ArrangeSharedChain(instanceCount: 2);
var session = _sut.CreateSession();
Assert.True((await _sut.FlattenAndValidateAsync(1, CancellationToken.None, validateScripts: false, session)).IsSuccess);
Assert.Equal(1, session.ChainLoads);
// A re-parent / composition change: chain MEMBERSHIP may now differ, so the
// cached chain must be discarded even though each member's own version is
// unchanged.
_watermark.BumpTemplate(TemplateId, structural: true);
Assert.True((await _sut.FlattenAndValidateAsync(2, CancellationToken.None, validateScripts: false, session)).IsSuccess);
Assert.Equal(2, session.ChainLoads);
}
}