Files
ScadaBridge/tests/ZB.MOM.WW.ScadaBridge.TemplateEngine.Tests/Services/InstanceServiceAuditDurabilityTests.cs
T
Joseph Doherty 5ca998dc56 fix(audit): persist config audit rows written after the final save (DEP-1, MGT-1, TPL-3, WP1 task 1.4)
IAuditService.LogAsync only stages the row; every caller that audited
after its last SaveChangesAsync, outside the configuration-command
transaction, lost the row with the DI scope (rig: zero Disable/Enable/
Delete/DeployArtifacts rows, 16 Deploy rows for 62 deployments, one
Create/Instance row for ids up to 3876).

- New IAuditService.LogAndSaveAsync: stage + save, best-effort (logs and
  swallows any failure incl. cancellation, detaches the unsaved row).
- DeploymentService (deploy/failed/reconciled/lifecycle + timeouts),
  ArtifactDeploymentService (DeployArtifacts now before the best-effort
  stamp, RetryArtifactDeployment, DeploySiteSecrets), InstanceService,
  AreaService, SiteService: post-save LogAsync -> LogAndSaveAsync.
- ManagementActor: AuditAndSaveAsync for the non-configuration handlers
  (API keys, shared schemas, ES methods, data-connection move); move now
  audits the scrubbed public shape (MGT-4) so the fix does not start
  writing protocol credentials into AuditLogEntries.
- HandleCreateInstance no longer stages a second Create row on top of
  InstanceService's own.

Tests: real-context (SQLite) tests per family read the row back through
a second context - DeploymentService, ArtifactDeploymentService,
InstanceService, ManagementActor; each fails against the old code.
Test projects gain a ConfigurationDatabase + EF Sqlite reference.
2026-12-03 09:59:19 -05:00

91 lines
4.2 KiB
C#

using Moq;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;
using ZB.MOM.WW.ScadaBridge.Commons.Messages.Management;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums;
using ZB.MOM.WW.ScadaBridge.TemplateEngine.Services;
namespace ZB.MOM.WW.ScadaBridge.TemplateEngine.Tests.Services;
/// <summary>
/// Code review 2026-12-02 TPL-3: every <see cref="InstanceService"/> mutation saved its change
/// and THEN staged its audit row with <c>LogAsync</c>, so on the management/CLI path (no later
/// save) the row was discarded — the rig had one Create row for instance ids up to 3876. These
/// run the service against a REAL audit service over SQLite and read the row back through a
/// second context, so only a committed row passes. The repository stays a mock: it never
/// touches the audit context, so nothing but the audit service itself can persist the row.
/// </summary>
public class InstanceServiceAuditDurabilityTests : IDisposable
{
private readonly Mock<ITemplateEngineRepository> _repoMock = new();
private readonly RealAuditDatabase _db = new();
private readonly InstanceService _sut;
/// <summary>Builds the service over a mocked repository and a real audit service.</summary>
public InstanceServiceAuditDurabilityTests()
{
_repoMock.Setup(r => r.SaveChangesAsync(It.IsAny<CancellationToken>())).ReturnsAsync(1);
_sut = new InstanceService(_repoMock.Object, _db.AuditService);
}
/// <inheritdoc />
public void Dispose() => _db.Dispose();
/// <summary>Create persists its audit row (the CLI <c>instance create</c> path).</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task CreateInstance_AuditRowIsPersisted()
{
_repoMock.Setup(r => r.GetTemplateByIdAsync(1, It.IsAny<CancellationToken>()))
.ReturnsAsync(new Template("T") { Id = 1 });
_repoMock.Setup(r => r.GetInstanceByUniqueNameAsync("Inst1", It.IsAny<CancellationToken>()))
.ReturnsAsync((Instance?)null);
var result = await _sut.CreateInstanceAsync("Inst1", 1, 1, null, "admin");
Assert.True(result.IsSuccess);
var row = Assert.Single(await _db.PersistedRowsAsync());
Assert.Equal(("Create", "Instance", "Inst1", "admin"), (row.Action, row.EntityType, row.EntityName, row.User));
}
/// <summary>SetConnectionBindings persists its audit row (the CLI <c>instance set-bindings</c> path).</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task SetConnectionBindings_AuditRowIsPersisted()
{
_repoMock.Setup(r => r.GetInstanceByIdAsync(1, It.IsAny<CancellationToken>()))
.ReturnsAsync(new Instance("Inst1") { Id = 1 });
_repoMock.Setup(r => r.GetBindingsByInstanceIdAsync(1, It.IsAny<CancellationToken>()))
.ReturnsAsync(new List<InstanceConnectionBinding>());
var result = await _sut.SetConnectionBindingsAsync(1, [new ConnectionBinding("Temp", 100)], "admin");
Assert.True(result.IsSuccess);
Assert.Equal("SetConnectionBindings", Assert.Single(await _db.PersistedRowsAsync()).Action);
}
/// <summary>Enable / Disable / Delete each persist their audit row.</summary>
/// <param name="action">The audited action.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
[Theory]
[InlineData("Enable")]
[InlineData("Disable")]
[InlineData("Delete")]
public async Task StateChanges_AuditRowIsPersisted(string action)
{
_repoMock.Setup(r => r.GetInstanceByIdAsync(1, It.IsAny<CancellationToken>()))
.ReturnsAsync(new Instance("Inst1") { Id = 1, State = InstanceState.Disabled });
var ok = action switch
{
"Enable" => (await _sut.EnableAsync(1, "admin")).IsSuccess,
"Disable" => (await _sut.DisableAsync(1, "admin")).IsSuccess,
_ => (await _sut.DeleteAsync(1, "admin")).IsSuccess,
};
Assert.True(ok);
Assert.Equal(action, Assert.Single(await _db.PersistedRowsAsync()).Action);
}
}