Merge branch 'review/wp2' into review/integration
This commit is contained in:
@@ -0,0 +1,98 @@
|
||||
using System.CommandLine;
|
||||
using ZB.MOM.WW.ScadaBridge.CLI.Commands;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Messages.Management;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.CLI.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// CLI-2 (WP2 task 2.8): <c>site update</c>, <c>data-connection update</c> and
|
||||
/// <c>api-method update</c> send only the options actually passed. Before the fix an
|
||||
/// omitted option was sent as null (or as a default: <c>--failover-retry-count</c> 3,
|
||||
/// <c>--timeout</c> 30) and the server overwrote the stored value — e.g.
|
||||
/// <c>site update --id 3 --name X</c> nulled both gRPC addresses. The server now treats
|
||||
/// null as "keep"; these tests pin that the CLI sends null for every omitted option.
|
||||
/// </summary>
|
||||
public class PartialUpdateCommandTests
|
||||
{
|
||||
private static readonly Option<string> Url = new("--url") { Recursive = true };
|
||||
private static readonly Option<string> Username = new("--username") { Recursive = true };
|
||||
private static readonly Option<string> Password = new("--password") { Recursive = true };
|
||||
private static readonly Option<string> Format = CliOptions.CreateFormatOption();
|
||||
|
||||
private static async Task<T> ParseAsync<T>(
|
||||
Func<Option<string>, Option<string>, Option<string>, Option<string>, Func<object, int>, Command> build,
|
||||
params string[] args)
|
||||
{
|
||||
var captured = new List<object>();
|
||||
var root = new RootCommand { Url, Username, Password, Format };
|
||||
root.Add(build(Url, Format, Username, Password, cmd => { captured.Add(cmd); return 0; }));
|
||||
var exit = await root.Parse(args).InvokeAsync();
|
||||
Assert.Equal(0, exit);
|
||||
return Assert.IsType<T>(Assert.Single(captured));
|
||||
}
|
||||
|
||||
/// <summary>A name-only site update leaves every other field null (= unchanged).</summary>
|
||||
[Fact]
|
||||
public async Task SiteUpdate_NameOnly_SendsNullForEveryOtherField()
|
||||
{
|
||||
var cmd = await ParseAsync<UpdateSiteCommand>(SiteCommands.BuildUpdate, "update", "--id", "3", "--name", "Plant 3");
|
||||
Assert.Equal(new UpdateSiteCommand(3, "Plant 3", null, null, null, null, null), cmd);
|
||||
}
|
||||
|
||||
/// <summary>A site update can change one address without supplying the name.</summary>
|
||||
[Fact]
|
||||
public async Task SiteUpdate_AddressOnly_SendsNullName()
|
||||
{
|
||||
var cmd = await ParseAsync<UpdateSiteCommand>(SiteCommands.BuildUpdate,
|
||||
"update", "--id", "3", "--grpc-node-a-address", "http://a:8083");
|
||||
Assert.Null(cmd.Name);
|
||||
Assert.Equal("http://a:8083", cmd.GrpcNodeAAddress);
|
||||
Assert.Null(cmd.GrpcNodeBAddress);
|
||||
}
|
||||
|
||||
/// <summary>An explicitly empty option is sent as "" (the server clears the field).</summary>
|
||||
[Fact]
|
||||
public async Task SiteUpdate_EmptyDescription_SendsEmptyStringToClear()
|
||||
{
|
||||
var cmd = await ParseAsync<UpdateSiteCommand>(SiteCommands.BuildUpdate, "update", "--id", "3", "--description", "");
|
||||
Assert.Equal("", cmd.Description);
|
||||
Assert.Null(cmd.Name);
|
||||
}
|
||||
|
||||
/// <summary>A name-only data-connection update sends no protocol, configs or retry count.</summary>
|
||||
[Fact]
|
||||
public async Task DataConnectionUpdate_NameOnly_SendsNullForEveryOtherField()
|
||||
{
|
||||
var cmd = await ParseAsync<UpdateDataConnectionCommand>(DataConnectionCommands.BuildUpdate,
|
||||
"update", "--id", "7", "--name", "X");
|
||||
Assert.Equal(new UpdateDataConnectionCommand(7, "X", null, null, null, null), cmd);
|
||||
}
|
||||
|
||||
/// <summary>A passed retry count and protocol are forwarded.</summary>
|
||||
[Fact]
|
||||
public async Task DataConnectionUpdate_PassedOptions_AreForwarded()
|
||||
{
|
||||
var cmd = await ParseAsync<UpdateDataConnectionCommand>(DataConnectionCommands.BuildUpdate,
|
||||
"update", "--id", "7", "--protocol", "OpcUa", "--failover-retry-count", "5", "--backup-config", "");
|
||||
Assert.Equal(new UpdateDataConnectionCommand(7, null, "OpcUa", null, "", 5), cmd);
|
||||
}
|
||||
|
||||
/// <summary>A script-only api-method update keeps the timeout and both definitions.</summary>
|
||||
[Fact]
|
||||
public async Task ApiMethodUpdate_ScriptOnly_SendsNullTimeoutAndDefinitions()
|
||||
{
|
||||
var cmd = await ParseAsync<UpdateApiMethodCommand>(ApiMethodCommands.BuildUpdate,
|
||||
"update", "--id", "5", "--script", "return 1;");
|
||||
Assert.Equal(new UpdateApiMethodCommand(5, "return 1;", null, null, null, null), cmd);
|
||||
}
|
||||
|
||||
/// <summary>A timeout-only api-method update sends no script.</summary>
|
||||
[Fact]
|
||||
public async Task ApiMethodUpdate_TimeoutOnly_SendsNullScript()
|
||||
{
|
||||
var cmd = await ParseAsync<UpdateApiMethodCommand>(ApiMethodCommands.BuildUpdate,
|
||||
"update", "--id", "5", "--timeout", "120");
|
||||
Assert.Null(cmd.Script);
|
||||
Assert.Equal(120, cmd.TimeoutSeconds);
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,9 @@ using ZB.MOM.WW.ScadaBridge.CLI.Commands;
|
||||
namespace ZB.MOM.WW.ScadaBridge.CLI.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Regression tests for the update commands. The <c>Update*Command</c> records in Commons carry
|
||||
/// Regression tests for the update commands. Site, data-connection and api-method updates are
|
||||
/// preserve-if-null partial updates (CLI-2, see <see cref="PartialUpdateCommandTests"/>); the
|
||||
/// remaining <c>Update*Command</c> records in Commons carry
|
||||
/// non-nullable "core" fields (e.g. <c>string Name</c>, <c>string Protocol</c>,
|
||||
/// <c>string Script</c>) — an update is a <em>whole-entity replace</em>, not a sparse
|
||||
/// patch. The CLI must therefore mark those core flags as <c>Required</c>: making them
|
||||
@@ -57,15 +59,24 @@ public class UpdateCommandContractTests
|
||||
public void TemplateScriptUpdate_CoreFieldsRequired()
|
||||
=> AssertRequired(UpdateCommand(TemplateCommands.Build(Url, Format, Username, Password), "script", "update"), "--name", "--code");
|
||||
|
||||
/// <summary>Verifies that the site update command marks its core fields as required.</summary>
|
||||
/// <summary>CLI-2: site update is a preserve-if-null partial update, so only <c>--id</c> is required.</summary>
|
||||
[Fact]
|
||||
public void SiteUpdate_CoreFieldsRequired()
|
||||
=> AssertRequired(UpdateCommand(SiteCommands.Build(Url, Format, Username, Password), "update"), "--name");
|
||||
public void SiteUpdate_IsPartial_OnlyIdRequired()
|
||||
{
|
||||
var update = UpdateCommand(SiteCommands.Build(Url, Format, Username, Password), "update");
|
||||
AssertRequired(update, "--id");
|
||||
AssertOptional(update, "--name", "--description", "--node-a-address", "--node-b-address",
|
||||
"--grpc-node-a-address", "--grpc-node-b-address");
|
||||
}
|
||||
|
||||
/// <summary>Verifies that the data connection update command marks its core fields as required.</summary>
|
||||
/// <summary>CLI-2: data-connection update is a preserve-if-null partial update, so only <c>--id</c> is required.</summary>
|
||||
[Fact]
|
||||
public void DataConnectionUpdate_CoreFieldsRequired()
|
||||
=> AssertRequired(UpdateCommand(DataConnectionCommands.Build(Url, Format, Username, Password), "update"), "--name", "--protocol");
|
||||
public void DataConnectionUpdate_IsPartial_OnlyIdRequired()
|
||||
{
|
||||
var update = UpdateCommand(DataConnectionCommands.Build(Url, Format, Username, Password), "update");
|
||||
AssertRequired(update, "--id");
|
||||
AssertOptional(update, "--name", "--protocol", "--primary-config", "--backup-config", "--failover-retry-count");
|
||||
}
|
||||
|
||||
/// <summary>Verifies that the external system update command marks its core fields as required.</summary>
|
||||
[Fact]
|
||||
@@ -110,10 +121,25 @@ public class UpdateCommandContractTests
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Verifies that the API method update command marks its script as required.</summary>
|
||||
/// <summary>CLI-2: api-method update is a preserve-if-null partial update, so only <c>--id</c> is required.</summary>
|
||||
[Fact]
|
||||
public void ApiMethodUpdate_CoreFieldsRequired()
|
||||
=> AssertRequired(UpdateCommand(ApiMethodCommands.Build(Url, Format, Username, Password), "update"), "--script");
|
||||
public void ApiMethodUpdate_IsPartial_OnlyIdRequired()
|
||||
{
|
||||
var update = UpdateCommand(ApiMethodCommands.Build(Url, Format, Username, Password), "update");
|
||||
AssertRequired(update, "--id");
|
||||
AssertOptional(update, "--script", "--timeout", "--parameters", "--return-def", "--trace-all-calls");
|
||||
}
|
||||
|
||||
private static void AssertOptional(Command command, params string[] optionNames)
|
||||
{
|
||||
foreach (var name in optionNames)
|
||||
{
|
||||
var option = command.Options.SingleOrDefault(o => o.Name == name);
|
||||
Assert.True(option != null, $"'{command.Name}' is missing expected option '{name}'.");
|
||||
Assert.False(option!.Required, $"'{command.Name}' option '{name}' must be optional (partial update).");
|
||||
Assert.False(option.HasDefaultValue, $"'{command.Name}' option '{name}' must have no default — an omitted option must travel as null.");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Verifies that the external system method update command keeps all of its fields optional because it is a sparse update.</summary>
|
||||
[Fact]
|
||||
|
||||
@@ -96,7 +96,7 @@ public class FlowDebuggerDrillinTests : BunitContext
|
||||
Assert.Contains("7–10 audit rows per call", markup);
|
||||
// Load, update and create paths all carry the flag.
|
||||
Assert.Contains("_traceAllCalls = _existing.TraceAllCalls;", markup);
|
||||
Assert.Contains("new UpdateApiMethodCommand(_existing.Id, _script, _timeoutSeconds, _params?.Trim(), _returns?.Trim(), _traceAllCalls)", markup);
|
||||
Assert.Contains("new UpdateApiMethodCommand(_existing.Id, _script, _timeoutSeconds, _params?.Trim() ?? \"\", _returns?.Trim() ?? \"\", _traceAllCalls)", markup);
|
||||
Assert.Contains("new CreateApiMethodCommand(methodName, _script, _timeoutSeconds, _params?.Trim(), _returns?.Trim(), _traceAllCalls)", markup);
|
||||
}
|
||||
}
|
||||
|
||||
+72
-3
@@ -434,6 +434,75 @@ public class TransportImportPageTests : BunitContext
|
||||
Assert.Empty(cut.FindAll("[data-testid='map-section']"));
|
||||
}
|
||||
|
||||
/// <summary>TRN-9: Rename is not offered for a data connection row, but still is for a template.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task Rename_is_not_offered_for_unsupported_entity_types()
|
||||
{
|
||||
var session = BuildEncryptedSession(sourceEnv: "prod-cluster");
|
||||
var preview = new ImportPreview(session.SessionId, new List<ImportPreviewItem>
|
||||
{
|
||||
new("DataConnection", "site-a/opc-a", null, null, ConflictKind.Modified, "{}", null),
|
||||
new("Template", "Pump", null, null, ConflictKind.Modified, "{}", null),
|
||||
});
|
||||
_importer.PreviewAsync(session.SessionId, Arg.Any<CancellationToken>()).Returns(preview);
|
||||
|
||||
var cut = Render<TransportImportPage>();
|
||||
await cut.InvokeAsync(() => SetField(cut.Instance, "_session", session));
|
||||
await cut.InvokeAsync(async () =>
|
||||
await InvokeAsyncMethod(cut.Instance, "LoadPreviewAndAdvanceAsync"));
|
||||
cut.Render();
|
||||
|
||||
Assert.Empty(cut.FindAll("input[id='res-DataConnection-site-a/opc-a-Rename']"));
|
||||
Assert.NotEmpty(cut.FindAll("input[id='res-DataConnection-site-a/opc-a-Overwrite']"));
|
||||
Assert.NotEmpty(cut.FindAll("input[id='res-Template-Pump-Rename']"));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// TRN-3: with the Map step redirecting site-a to site-b, the Confirm gate re-runs the
|
||||
/// preview under that mapping, so a connection blocker the redirect resolves no longer
|
||||
/// blocks the import.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task Confirm_reruns_preview_under_redirect_mapping()
|
||||
{
|
||||
_siteRepo.GetAllSitesAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(new List<Site> { new("Site B", "site-b") { Id = 7 } });
|
||||
_siteRepo.GetDataConnectionsBySiteIdAsync(7, Arg.Any<CancellationToken>())
|
||||
.Returns(new List<DataConnection> { new("opc-a", "OpcUa", 7) { Id = 11 } });
|
||||
|
||||
var session = BuildEncryptedSession(sourceEnv: "prod-cluster");
|
||||
var blocked = new ImportPreview(
|
||||
session.SessionId,
|
||||
new List<ImportPreviewItem>
|
||||
{
|
||||
new("Instance", "site-a/opc-a", null, null, ConflictKind.Blocker, null, "Connection 'site-a/opc-a' unresolved"),
|
||||
},
|
||||
new List<RequiredSiteMapping> { new("site-a", "Site A", null) },
|
||||
new List<RequiredConnectionMapping> { new("site-a", "opc-a", null) });
|
||||
var resolved = new ImportPreview(
|
||||
session.SessionId,
|
||||
new List<ImportPreviewItem> { new("Instance", "Pump-01", null, null, ConflictKind.New, null, null) },
|
||||
new List<RequiredSiteMapping> { new("site-a", "Site A", "site-b") },
|
||||
new List<RequiredConnectionMapping> { new("site-a", "opc-a", "opc-a") });
|
||||
_importer.PreviewAsync(session.SessionId, Arg.Any<CancellationToken>()).Returns(blocked);
|
||||
_importer.PreviewAsync(session.SessionId, Arg.Any<CancellationToken>(), Arg.Is<BundleNameMap?>(m => m != null))
|
||||
.Returns(resolved);
|
||||
|
||||
var cut = Render<TransportImportPage>();
|
||||
await cut.InvokeAsync(() => SetField(cut.Instance, "_session", session));
|
||||
await cut.InvokeAsync(async () =>
|
||||
await InvokeAsyncMethod(cut.Instance, "LoadPreviewAndAdvanceAsync"));
|
||||
await cut.InvokeAsync(async () =>
|
||||
await InvokeAsyncMethod(cut.Instance, "OnSiteChoiceChangedAsync", "site-a", "site-b"));
|
||||
await cut.InvokeAsync(async () => await InvokeAsyncMethod(cut.Instance, "GoToConfirm"));
|
||||
|
||||
Assert.Equal(
|
||||
TransportImportPage.ImportWizardStep.Confirm,
|
||||
GetField<TransportImportPage.ImportWizardStep>(cut.Instance, "_step"));
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────
|
||||
// Test 9: the operator's Map choices fold into the BundleNameMap
|
||||
// passed to ApplyAsync — a chosen target → MapToExisting, "Create new" →
|
||||
@@ -773,7 +842,7 @@ public class TransportImportPageTests : BunitContext
|
||||
=> throw new NotSupportedException("These tests seed sessions via OpenSession().");
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<ImportPreview> PreviewAsync(Guid sessionId, CancellationToken ct = default)
|
||||
public Task<ImportPreview> PreviewAsync(Guid sessionId, CancellationToken ct = default, BundleNameMap? nameMap = null)
|
||||
=> Task.FromResult(new ImportPreview(sessionId, new List<ImportPreviewItem>()));
|
||||
|
||||
/// <inheritdoc />
|
||||
@@ -1025,7 +1094,7 @@ public class TransportImportPageTests : BunitContext
|
||||
return (T)field.GetValue(obj)!;
|
||||
}
|
||||
|
||||
private static async Task InvokeAsyncMethod(object obj, string name)
|
||||
private static async Task InvokeAsyncMethod(object obj, string name, params object?[] args)
|
||||
{
|
||||
var method = obj.GetType().GetMethod(
|
||||
name,
|
||||
@@ -1033,7 +1102,7 @@ public class TransportImportPageTests : BunitContext
|
||||
| System.Reflection.BindingFlags.NonPublic
|
||||
| System.Reflection.BindingFlags.Public)
|
||||
?? throw new InvalidOperationException($"Method '{name}' not found on {obj.GetType()}.");
|
||||
var task = (Task)method.Invoke(obj, Array.Empty<object?>())!;
|
||||
var task = (Task)method.Invoke(obj, args)!;
|
||||
await task;
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -93,7 +93,7 @@ public class TransportImportSessionDisposeRaceTests : BunitContext
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<ImportPreview> PreviewAsync(Guid sessionId, CancellationToken ct = default)
|
||||
public Task<ImportPreview> PreviewAsync(Guid sessionId, CancellationToken ct = default, BundleNameMap? nameMap = null)
|
||||
=> throw new NotSupportedException("Not exercised by these tests.");
|
||||
|
||||
/// <inheritdoc />
|
||||
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Deployment;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests.Configurations;
|
||||
|
||||
/// <summary>
|
||||
/// DEP-3 (WP2 task 2.9): <c>SystemArtifactDeploymentRecord.PerSiteStatus</c> holds one
|
||||
/// serialized result per site (~155 chars for a clean site, far more with error text), so a
|
||||
/// 4000-character cap made Deploy Artifacts over ~25 sites fail AFTER every site had applied,
|
||||
/// with nothing stamped. The column is unbounded (<c>nvarchar(max)</c>).
|
||||
/// </summary>
|
||||
public class SystemArtifactDeploymentRecordConfigurationTests : IDisposable
|
||||
{
|
||||
private readonly ScadaBridgeDbContext _context = SqliteTestHelper.CreateInMemoryContext();
|
||||
|
||||
/// <summary>Releases the resources held by this test class.</summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_context.Database.CloseConnection();
|
||||
_context.Dispose();
|
||||
}
|
||||
|
||||
/// <summary>The PerSiteStatus property has no maximum length.</summary>
|
||||
[Fact]
|
||||
public void PerSiteStatus_IsUnbounded()
|
||||
{
|
||||
var property = _context.Model.FindEntityType(typeof(SystemArtifactDeploymentRecord))!
|
||||
.FindProperty(nameof(SystemArtifactDeploymentRecord.PerSiteStatus))!;
|
||||
|
||||
Assert.Null(property.GetMaxLength());
|
||||
}
|
||||
|
||||
/// <summary>A status payload well past the old 4000-character cap round-trips intact.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task PerSiteStatus_LargePayload_RoundTrips()
|
||||
{
|
||||
var status = new string('x', 20_000);
|
||||
var record = new SystemArtifactDeploymentRecord("Artifacts", "alice") { PerSiteStatus = status };
|
||||
_context.SystemArtifactDeploymentRecords.Add(record);
|
||||
await _context.SaveChangesAsync();
|
||||
_context.ChangeTracker.Clear();
|
||||
|
||||
var loaded = await _context.SystemArtifactDeploymentRecords.FindAsync(record.Id);
|
||||
Assert.Equal(status, loaded!.PerSiteStatus);
|
||||
}
|
||||
}
|
||||
@@ -4499,7 +4499,8 @@ public class ManagementActorTests : TestKit, IDisposable
|
||||
Manifest = null!,
|
||||
ExpiresAt = DateTimeOffset.UtcNow.AddMinutes(5),
|
||||
});
|
||||
importer.PreviewAsync(sessionId, Arg.Any<CancellationToken>())
|
||||
// TRN-3: the preview may run under the operator's explicit redirects, so match any map.
|
||||
importer.PreviewAsync(sessionId, Arg.Any<CancellationToken>(), Arg.Any<Commons.Types.Transport.BundleNameMap?>())
|
||||
.Returns(new Commons.Types.Transport.ImportPreview(
|
||||
sessionId,
|
||||
Array.Empty<Commons.Types.Transport.ImportPreviewItem>(),
|
||||
@@ -4522,6 +4523,87 @@ public class ManagementActorTests : TestKit, IDisposable
|
||||
return (sessionId, () => captured);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// TRN-3: an explicit --map-site / --map-connection redirect reaches the PREVIEW, so its
|
||||
/// unresolved-connection blockers and auto-matches are computed against the mapped target.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void ImportBundleCommand_ExplicitRedirects_ArePassedToThePreview()
|
||||
{
|
||||
var (_, importer) = AddBundleSubstitutes();
|
||||
var (sessionId, _) = ConfigureImportForMapping(
|
||||
importer,
|
||||
new[] { new Commons.Types.Transport.RequiredSiteMapping("site-a", "Site A", AutoMatchTargetIdentifier: null) },
|
||||
new[] { new Commons.Types.Transport.RequiredConnectionMapping("site-a", "OPC1", AutoMatchTargetName: null) });
|
||||
Commons.Types.Transport.BundleNameMap? previewMap = null;
|
||||
importer.When(i => i.PreviewAsync(sessionId, Arg.Any<CancellationToken>(),
|
||||
Arg.Any<Commons.Types.Transport.BundleNameMap?>()))
|
||||
.Do(ci => previewMap = ci.ArgAt<Commons.Types.Transport.BundleNameMap?>(2));
|
||||
|
||||
var cmd = new ImportBundleCommand(
|
||||
Convert.ToBase64String(new byte[] { 0x01 }), null, "overwrite",
|
||||
SiteMappings: new[] { new SiteMappingSpec("site-a", "site-x") },
|
||||
ConnectionMappings: new[] { new ConnectionMappingSpec("site-a", "OPC1", "OPC1") });
|
||||
CreateActor().Tell(Envelope(cmd, "Administrator"));
|
||||
|
||||
ExpectMsg<ManagementSuccess>(TimeSpan.FromSeconds(5));
|
||||
Assert.NotNull(previewMap);
|
||||
var site = Assert.Single(previewMap!.Sites);
|
||||
Assert.Equal(("site-a", Commons.Types.Transport.MappingAction.MapToExisting, "site-x"),
|
||||
(site.SourceSiteIdentifier, site.Action, site.TargetSiteIdentifier));
|
||||
Assert.Equal("OPC1", Assert.Single(previewMap.Connections).TargetConnectionName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// TRN-9: --conflict-policy rename falls back to Skip (with a warning) for a site, data
|
||||
/// connection, SMTP or SMS configuration, and still renames a template.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void ImportBundleCommand_RenamePolicy_FallsBackToSkipForUnsupportedTypes()
|
||||
{
|
||||
var (_, importer) = AddBundleSubstitutes();
|
||||
var sessionId = Guid.NewGuid();
|
||||
importer.LoadAsync(Arg.Any<Stream>(), Arg.Any<string?>(), Arg.Any<CancellationToken>(), Arg.Any<string?>())
|
||||
.Returns(new Commons.Types.Transport.BundleSession
|
||||
{
|
||||
SessionId = sessionId,
|
||||
Manifest = null!,
|
||||
ExpiresAt = DateTimeOffset.UtcNow.AddMinutes(5),
|
||||
});
|
||||
Commons.Types.Transport.ImportPreviewItem Modified(string type, string name) =>
|
||||
new(type, name, null, null, Commons.Types.Transport.ConflictKind.Modified, "{}", null);
|
||||
importer.PreviewAsync(sessionId, Arg.Any<CancellationToken>(), Arg.Any<Commons.Types.Transport.BundleNameMap?>())
|
||||
.Returns(new Commons.Types.Transport.ImportPreview(sessionId, new[]
|
||||
{
|
||||
Modified("SmtpConfiguration", "smtp.example.com"),
|
||||
Modified("Template", "Pump"),
|
||||
}));
|
||||
IReadOnlyList<Commons.Types.Transport.ImportResolution>? captured = null;
|
||||
importer.ApplyAsync(
|
||||
Arg.Any<Guid>(),
|
||||
Arg.Do<IReadOnlyList<Commons.Types.Transport.ImportResolution>>(r => captured = r),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<CancellationToken>(),
|
||||
Arg.Any<Commons.Types.Transport.BundleNameMap?>())
|
||||
.Returns(new Commons.Types.Transport.ImportResult(
|
||||
BundleImportId: Guid.NewGuid(),
|
||||
Added: 0, Overwritten: 0, Skipped: 1, Renamed: 1,
|
||||
StaleInstanceIds: Array.Empty<int>(),
|
||||
AuditEventCorrelation: "correlation"));
|
||||
|
||||
CreateActor().Tell(Envelope(
|
||||
new ImportBundleCommand(Convert.ToBase64String(new byte[] { 0x01 }), null, "rename"), "Administrator"));
|
||||
|
||||
var success = ExpectMsg<ManagementSuccess>(TimeSpan.FromSeconds(5));
|
||||
Assert.NotNull(captured);
|
||||
var smtp = captured!.Single(r => r.EntityType == "SmtpConfiguration");
|
||||
Assert.Equal(Commons.Types.Transport.ResolutionAction.Skip, smtp.Action);
|
||||
Assert.Null(smtp.RenameTo);
|
||||
var template = captured.Single(r => r.EntityType == "Template");
|
||||
Assert.Equal(Commons.Types.Transport.ResolutionAction.Rename, template.Action);
|
||||
Assert.Contains("Rename is not supported", success.JsonData);
|
||||
}
|
||||
|
||||
/// <summary>Verifies that import bundle command, when explicit spec, overrides auto match.</summary>
|
||||
[Fact]
|
||||
public void ImportBundleCommand_ExplicitSpec_OverridesAutoMatch()
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
using System.Text.Json;
|
||||
using Akka.Actor;
|
||||
using Akka.TestKit.Xunit2;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using NSubstitute;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Entities.InboundApi;
|
||||
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.Messages.Management;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.ManagementService.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// CLI-2 (WP2 task 2.8): the site, data-connection and api-method update handlers are
|
||||
/// preserve-if-null. A null command field keeps the stored value; an empty string
|
||||
/// clears an optional field. Before the fix every field was assigned unconditionally,
|
||||
/// so <c>site update --id 3 --name X</c> nulled both gRPC addresses and
|
||||
/// <c>api-method update --script …</c> reset the timeout to 30 and dropped both
|
||||
/// definitions.
|
||||
/// </summary>
|
||||
public class PartialUpdateHandlerTests : TestKit, IDisposable
|
||||
{
|
||||
private readonly ServiceCollection _services = new ServiceCollection().AddTestConfigurationTransaction();
|
||||
private readonly ISiteRepository _siteRepo = Substitute.For<ISiteRepository>();
|
||||
private readonly IInboundApiRepository _apiRepo = Substitute.For<IInboundApiRepository>();
|
||||
|
||||
/// <summary>Initializes the harness with stubbed repositories.</summary>
|
||||
public PartialUpdateHandlerTests()
|
||||
{
|
||||
_services.AddScoped(_ => _siteRepo);
|
||||
_services.AddScoped(_ => _apiRepo);
|
||||
_services.AddScoped(_ => Substitute.For<IAuditService>());
|
||||
_apiRepo.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(1);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
void IDisposable.Dispose() => Shutdown();
|
||||
|
||||
private IActorRef CreateActor() =>
|
||||
Sys.ActorOf(Props.Create(() => new ManagementActor(
|
||||
_services.BuildServiceProvider(), NullLogger<ManagementActor>.Instance)));
|
||||
|
||||
private static ManagementEnvelope Admin(object command) =>
|
||||
new(new AuthenticatedUser("admin", "Admin", new[] { "Administrator", "Designer" }, Array.Empty<string>()),
|
||||
command, Guid.NewGuid().ToString("N"));
|
||||
|
||||
private static Site StoredSite() => new("Plant", "site-3")
|
||||
{
|
||||
Id = 3,
|
||||
Description = "desc",
|
||||
NodeAAddress = "akka.tcp://scadabridge@a:8081",
|
||||
NodeBAddress = "akka.tcp://scadabridge@b:8081",
|
||||
GrpcNodeAAddress = "http://a:8083",
|
||||
GrpcNodeBAddress = "http://b:8083",
|
||||
};
|
||||
|
||||
/// <summary>A name-only site update keeps the description and all four addresses.</summary>
|
||||
[Fact]
|
||||
public void UpdateSite_NameOnly_PreservesEveryOtherField()
|
||||
{
|
||||
var site = StoredSite();
|
||||
_siteRepo.GetSiteByIdAsync(3, Arg.Any<CancellationToken>()).Returns(site);
|
||||
|
||||
CreateActor().Tell(Admin(new UpdateSiteCommand(3, "Plant 3", null)));
|
||||
ExpectMsg<ManagementSuccess>(TimeSpan.FromSeconds(10));
|
||||
|
||||
Assert.Equal("Plant 3", site.Name);
|
||||
Assert.Equal("desc", site.Description);
|
||||
Assert.Equal("akka.tcp://scadabridge@a:8081", site.NodeAAddress);
|
||||
Assert.Equal("akka.tcp://scadabridge@b:8081", site.NodeBAddress);
|
||||
Assert.Equal("http://a:8083", site.GrpcNodeAAddress);
|
||||
Assert.Equal("http://b:8083", site.GrpcNodeBAddress);
|
||||
}
|
||||
|
||||
/// <summary>An address-only site update keeps the name; an empty string clears a field.</summary>
|
||||
[Fact]
|
||||
public void UpdateSite_EmptyString_ClearsField_NullNameKeepsName()
|
||||
{
|
||||
var site = StoredSite();
|
||||
_siteRepo.GetSiteByIdAsync(3, Arg.Any<CancellationToken>()).Returns(site);
|
||||
|
||||
CreateActor().Tell(Admin(new UpdateSiteCommand(3, null, "", GrpcNodeBAddress: "")));
|
||||
ExpectMsg<ManagementSuccess>(TimeSpan.FromSeconds(10));
|
||||
|
||||
Assert.Equal("Plant", site.Name);
|
||||
Assert.Null(site.Description);
|
||||
Assert.Null(site.GrpcNodeBAddress);
|
||||
Assert.Equal("http://a:8083", site.GrpcNodeAAddress);
|
||||
}
|
||||
|
||||
/// <summary>A preserved address is still validated; a malformed incoming one is refused.</summary>
|
||||
[Fact]
|
||||
public void UpdateSite_MalformedIncomingAddress_IsRefused()
|
||||
{
|
||||
var site = StoredSite();
|
||||
_siteRepo.GetSiteByIdAsync(3, Arg.Any<CancellationToken>()).Returns(site);
|
||||
|
||||
CreateActor().Tell(Admin(new UpdateSiteCommand(3, null, null, GrpcNodeAAddress: "a:8083")));
|
||||
var error = ExpectMsg<ManagementError>(TimeSpan.FromSeconds(10));
|
||||
|
||||
Assert.Contains("GrpcNodeAAddress", error.Error);
|
||||
Assert.Equal("http://a:8083", site.GrpcNodeAAddress);
|
||||
}
|
||||
|
||||
/// <summary>A name-only data-connection update keeps protocol, both configs and the retry count.</summary>
|
||||
[Fact]
|
||||
public void UpdateDataConnection_NameOnly_PreservesConfigsAndRetryCount()
|
||||
{
|
||||
var conn = new DataConnection("c1", "OpcUa", 1)
|
||||
{
|
||||
Id = 7,
|
||||
PrimaryConfiguration = """{"Endpoint":"opc.tcp://p","UserIdentity":{"Password":"pw"}}""",
|
||||
BackupConfiguration = """{"Endpoint":"opc.tcp://b"}""",
|
||||
FailoverRetryCount = 9,
|
||||
};
|
||||
_siteRepo.GetDataConnectionByIdAsync(7, Arg.Any<CancellationToken>()).Returns(conn);
|
||||
|
||||
CreateActor().Tell(Admin(new UpdateDataConnectionCommand(7, "renamed", null, null)));
|
||||
ExpectMsg<ManagementSuccess>(TimeSpan.FromSeconds(10));
|
||||
|
||||
Assert.Equal("renamed", conn.Name);
|
||||
Assert.Equal("OpcUa", conn.Protocol);
|
||||
Assert.Contains("\"pw\"", conn.PrimaryConfiguration);
|
||||
Assert.Equal("""{"Endpoint":"opc.tcp://b"}""", conn.BackupConfiguration);
|
||||
Assert.Equal(9, conn.FailoverRetryCount);
|
||||
}
|
||||
|
||||
/// <summary>An empty backup configuration removes the backup endpoint.</summary>
|
||||
[Fact]
|
||||
public void UpdateDataConnection_EmptyBackup_RemovesBackup()
|
||||
{
|
||||
var conn = new DataConnection("c1", "OpcUa", 1)
|
||||
{
|
||||
Id = 7,
|
||||
PrimaryConfiguration = """{"Endpoint":"opc.tcp://p"}""",
|
||||
BackupConfiguration = """{"Endpoint":"opc.tcp://b"}""",
|
||||
};
|
||||
_siteRepo.GetDataConnectionByIdAsync(7, Arg.Any<CancellationToken>()).Returns(conn);
|
||||
|
||||
CreateActor().Tell(Admin(new UpdateDataConnectionCommand(7, null, null, null, "", 3)));
|
||||
ExpectMsg<ManagementSuccess>(TimeSpan.FromSeconds(10));
|
||||
|
||||
Assert.Null(conn.BackupConfiguration);
|
||||
Assert.Equal("""{"Endpoint":"opc.tcp://p"}""", conn.PrimaryConfiguration);
|
||||
Assert.Equal(3, conn.FailoverRetryCount);
|
||||
}
|
||||
|
||||
/// <summary>A script-only api-method update keeps the timeout and both definitions.</summary>
|
||||
[Fact]
|
||||
public void UpdateApiMethod_ScriptOnly_PreservesTimeoutAndDefinitions()
|
||||
{
|
||||
var method = new ApiMethod("M", "return 1;")
|
||||
{
|
||||
Id = 5,
|
||||
TimeoutSeconds = 120,
|
||||
ParameterDefinitions = """[{"name":"x","type":"Integer"}]""",
|
||||
ReturnDefinition = """[{"name":"y","type":"Integer"}]""",
|
||||
};
|
||||
_apiRepo.GetApiMethodByIdAsync(5, Arg.Any<CancellationToken>()).Returns(method);
|
||||
|
||||
CreateActor().Tell(Admin(new UpdateApiMethodCommand(5, "return 2;", null, null, null)));
|
||||
ExpectMsg<ManagementSuccess>(TimeSpan.FromSeconds(10));
|
||||
|
||||
Assert.Equal("return 2;", method.Script);
|
||||
Assert.Equal(120, method.TimeoutSeconds);
|
||||
Assert.Equal("""[{"name":"x","type":"Integer"}]""", method.ParameterDefinitions);
|
||||
Assert.Equal("""[{"name":"y","type":"Integer"}]""", method.ReturnDefinition);
|
||||
}
|
||||
|
||||
/// <summary>A timeout-only api-method update keeps the script; "" clears a definition.</summary>
|
||||
[Fact]
|
||||
public void UpdateApiMethod_TimeoutOnly_KeepsScript_EmptyClearsDefinition()
|
||||
{
|
||||
var method = new ApiMethod("M", "return 1;")
|
||||
{
|
||||
Id = 5,
|
||||
TimeoutSeconds = 30,
|
||||
ParameterDefinitions = """[{"name":"x","type":"Integer"}]""",
|
||||
};
|
||||
_apiRepo.GetApiMethodByIdAsync(5, Arg.Any<CancellationToken>()).Returns(method);
|
||||
|
||||
CreateActor().Tell(Admin(new UpdateApiMethodCommand(5, null, 90, "", null)));
|
||||
ExpectMsg<ManagementSuccess>(TimeSpan.FromSeconds(10));
|
||||
|
||||
Assert.Equal("return 1;", method.Script);
|
||||
Assert.Equal(90, method.TimeoutSeconds);
|
||||
Assert.Null(method.ParameterDefinitions);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Wire compatibility: an older CLI always sends every field (non-null ints included);
|
||||
/// that payload must still deserialize into the now-nullable records with its values.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void OlderClientPayloads_StillDeserialize()
|
||||
{
|
||||
var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
|
||||
|
||||
var dc = JsonSerializer.Deserialize<UpdateDataConnectionCommand>(
|
||||
"""{"DataConnectionId":7,"Name":"X","Protocol":"OpcUa","PrimaryConfiguration":"{}","BackupConfiguration":null,"FailoverRetryCount":3}""",
|
||||
options)!;
|
||||
Assert.Equal(new UpdateDataConnectionCommand(7, "X", "OpcUa", "{}", null, 3), dc);
|
||||
|
||||
var api = JsonSerializer.Deserialize<UpdateApiMethodCommand>(
|
||||
"""{"ApiMethodId":5,"Script":"return 1;","TimeoutSeconds":30,"ParameterDefinitions":null,"ReturnDefinition":null}""",
|
||||
options)!;
|
||||
Assert.Equal(new UpdateApiMethodCommand(5, "return 1;", 30, null, null), api);
|
||||
|
||||
var site = JsonSerializer.Deserialize<UpdateSiteCommand>(
|
||||
"""{"SiteId":3,"Name":"S","Description":null}""", options)!;
|
||||
Assert.Equal(new UpdateSiteCommand(3, "S", null), site);
|
||||
}
|
||||
}
|
||||
+279
@@ -0,0 +1,279 @@
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums;
|
||||
using ZB.MOM.WW.ScadaBridge.TemplateEngine.Flattening;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.TemplateEngine.Tests.Flattening;
|
||||
|
||||
/// <summary>
|
||||
/// WP2 tasks 2.2/2.3 — alarm on-trigger script references are resolved by NAME within
|
||||
/// the alarm's own composition chain, not through a flatten-wide script-id map.
|
||||
/// TPL-1: two slots of one module share the base script row id, so the global map made
|
||||
/// every slot's alarm run the LAST slot's script. TPL-2: a derived script override has
|
||||
/// a different row id, so the base alarm lost its on-trigger script. TPL-5: a nested
|
||||
/// slot visited twice under one prefix let the base pass overwrite a slot-level
|
||||
/// override. The fixes change the revision hash of affected configurations by design.
|
||||
/// </summary>
|
||||
public class AlarmOnTriggerScriptResolutionTests
|
||||
{
|
||||
private readonly FlatteningService _sut = new();
|
||||
|
||||
private static Instance CreateInstance(int templateId = 1) =>
|
||||
new("TestInstance") { Id = 1, TemplateId = templateId, SiteId = 1 };
|
||||
|
||||
private static Template CreateTemplate(int id, string name, int? parentId = null) =>
|
||||
new(name) { Id = id, ParentTemplateId = parentId };
|
||||
|
||||
private static TemplateAlarm Alarm(string name, int? scriptId, bool inherited = false) => new(name)
|
||||
{
|
||||
TriggerType = AlarmTriggerType.RangeViolation,
|
||||
TriggerConfiguration = "{\"attributeName\":\"Temp\",\"high\":100}",
|
||||
PriorityLevel = 1,
|
||||
OnTriggerScriptId = scriptId,
|
||||
IsInherited = inherited,
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Builds the slot-derived template the composition service creates for a slot:
|
||||
/// a child of <paramref name="baseTemplate"/> whose members are IsInherited
|
||||
/// placeholders (placeholder alarms keep pointing at the BASE script id).
|
||||
/// </summary>
|
||||
private static Template SlotDerived(int id, Template baseTemplate, int scriptPlaceholderId)
|
||||
{
|
||||
var t = CreateTemplate(id, $"{baseTemplate.Name}_slot{id}", baseTemplate.Id);
|
||||
foreach (var s in baseTemplate.Scripts)
|
||||
t.Scripts.Add(new TemplateScript(s.Name, s.Code) { Id = scriptPlaceholderId++, IsInherited = true });
|
||||
foreach (var a in baseTemplate.Alarms)
|
||||
t.Alarms.Add(Alarm(a.Name, a.OnTriggerScriptId, inherited: true));
|
||||
return t;
|
||||
}
|
||||
|
||||
/// <summary>TPL-1: each slot's alarm runs its OWN slot's script.</summary>
|
||||
[Fact]
|
||||
public void TwoSlotsOfOneModule_EachAlarmResolvesItsOwnSlotScript()
|
||||
{
|
||||
var pump = CreateTemplate(10, "Pump");
|
||||
pump.Scripts.Add(new TemplateScript("OnHigh", "// on high") { Id = 100 });
|
||||
pump.Alarms.Add(Alarm("HighTemp", 100));
|
||||
var pump1 = SlotDerived(11, pump, 110);
|
||||
var pump2 = SlotDerived(12, pump, 120);
|
||||
var skid = CreateTemplate(1, "Skid");
|
||||
|
||||
var compositions = new Dictionary<int, IReadOnlyList<TemplateComposition>>
|
||||
{
|
||||
[1] = new List<TemplateComposition>
|
||||
{
|
||||
new("Pump1") { ComposedTemplateId = 11 },
|
||||
new("Pump2") { ComposedTemplateId = 12 },
|
||||
},
|
||||
};
|
||||
var chains = new Dictionary<int, IReadOnlyList<Template>>
|
||||
{
|
||||
[11] = [pump1, pump],
|
||||
[12] = [pump2, pump],
|
||||
};
|
||||
|
||||
var result = _sut.Flatten(CreateInstance(), [skid], compositions, chains, new Dictionary<int, DataConnection>());
|
||||
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal("Pump1.OnHigh", result.Value.Alarms.Single(a => a.CanonicalName == "Pump1.HighTemp").OnTriggerScriptCanonicalName);
|
||||
Assert.Equal("Pump2.OnHigh", result.Value.Alarms.Single(a => a.CanonicalName == "Pump2.HighTemp").OnTriggerScriptCanonicalName);
|
||||
}
|
||||
|
||||
/// <summary>TPL-1 with the base template composed directly into two slots (one shared chain).</summary>
|
||||
[Fact]
|
||||
public void SameTemplateComposedDirectlyTwice_EachAlarmResolvesItsOwnSlotScript()
|
||||
{
|
||||
var pump = CreateTemplate(10, "Pump");
|
||||
pump.Scripts.Add(new TemplateScript("OnHigh", "// on high") { Id = 100 });
|
||||
pump.Alarms.Add(Alarm("HighTemp", 100));
|
||||
var skid = CreateTemplate(1, "Skid");
|
||||
|
||||
var compositions = new Dictionary<int, IReadOnlyList<TemplateComposition>>
|
||||
{
|
||||
[1] = new List<TemplateComposition>
|
||||
{
|
||||
new("A") { ComposedTemplateId = 10 },
|
||||
new("B") { ComposedTemplateId = 10 },
|
||||
},
|
||||
};
|
||||
var chains = new Dictionary<int, IReadOnlyList<Template>> { [10] = [pump] };
|
||||
|
||||
var result = _sut.Flatten(CreateInstance(), [skid], compositions, chains, new Dictionary<int, DataConnection>());
|
||||
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal("A.OnHigh", result.Value.Alarms.Single(a => a.CanonicalName == "A.HighTemp").OnTriggerScriptCanonicalName);
|
||||
Assert.Equal("B.OnHigh", result.Value.Alarms.Single(a => a.CanonicalName == "B.HighTemp").OnTriggerScriptCanonicalName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// TPL-5: a slot-level override that clears a nested alarm's on-trigger script is
|
||||
/// not overwritten by the second (base) visit of the same nested slot.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void NestedSlotOverride_ClearingOnTriggerScript_IsNotOverwrittenByBasePass()
|
||||
{
|
||||
// Motor(5) has OnOverload(500) and alarm Overload -> 500.
|
||||
var motor = CreateTemplate(5, "Motor");
|
||||
motor.Scripts.Add(new TemplateScript("OnOverload", "// overload") { Id = 500 });
|
||||
motor.Alarms.Add(Alarm("Overload", 500));
|
||||
// Pump(3) composes Motor via its slot-derived Motor (6).
|
||||
var pump = CreateTemplate(3, "Pump");
|
||||
var pumpMotor = SlotDerived(6, motor, 600);
|
||||
// Skid's slot Pump1 is a slot-derived Pump (2) with its own slot-derived Motor (7, child of 6),
|
||||
// on which the operator overrode Overload to have NO on-trigger script.
|
||||
var pump1 = CreateTemplate(2, "Pump_slot2", 3);
|
||||
var pump1Motor = SlotDerived(7, pumpMotor, 700);
|
||||
pump1Motor.ParentTemplateId = 6;
|
||||
pump1Motor.Alarms.Clear();
|
||||
pump1Motor.Alarms.Add(Alarm("Overload", scriptId: null, inherited: false));
|
||||
var skid = CreateTemplate(1, "Skid");
|
||||
|
||||
var compositions = new Dictionary<int, IReadOnlyList<TemplateComposition>>
|
||||
{
|
||||
[1] = new List<TemplateComposition> { new("Pump1") { ComposedTemplateId = 2 } },
|
||||
[2] = new List<TemplateComposition> { new("Motor") { ComposedTemplateId = 7 } },
|
||||
[3] = new List<TemplateComposition> { new("Motor") { ComposedTemplateId = 6 } },
|
||||
};
|
||||
var chains = new Dictionary<int, IReadOnlyList<Template>>
|
||||
{
|
||||
[2] = [pump1, pump],
|
||||
[7] = [pump1Motor, pumpMotor, motor],
|
||||
[6] = [pumpMotor, motor],
|
||||
};
|
||||
|
||||
var result = _sut.Flatten(CreateInstance(), [skid], compositions, chains, new Dictionary<int, DataConnection>());
|
||||
|
||||
Assert.True(result.IsSuccess);
|
||||
var alarm = result.Value.Alarms.Single(a => a.CanonicalName == "Pump1.Motor.Overload");
|
||||
Assert.Null(alarm.OnTriggerScriptCanonicalName);
|
||||
}
|
||||
|
||||
/// <summary>TPL-5: a slot-level override that re-points the nested alarm keeps the new script.</summary>
|
||||
[Fact]
|
||||
public void NestedSlotOverride_RepointingOnTriggerScript_Wins()
|
||||
{
|
||||
var motor = CreateTemplate(5, "Motor");
|
||||
motor.Scripts.Add(new TemplateScript("OnOverload", "// overload") { Id = 500 });
|
||||
motor.Scripts.Add(new TemplateScript("OnOverloadAlt", "// alt") { Id = 501 });
|
||||
motor.Alarms.Add(Alarm("Overload", 500));
|
||||
var pump = CreateTemplate(3, "Pump");
|
||||
var pumpMotor = SlotDerived(6, motor, 600);
|
||||
var pump1 = CreateTemplate(2, "Pump_slot2", 3);
|
||||
var pump1Motor = SlotDerived(7, pumpMotor, 700);
|
||||
pump1Motor.ParentTemplateId = 6;
|
||||
pump1Motor.Alarms.Clear();
|
||||
pump1Motor.Alarms.Add(Alarm("Overload", scriptId: 501, inherited: false));
|
||||
var skid = CreateTemplate(1, "Skid");
|
||||
|
||||
var compositions = new Dictionary<int, IReadOnlyList<TemplateComposition>>
|
||||
{
|
||||
[1] = new List<TemplateComposition> { new("Pump1") { ComposedTemplateId = 2 } },
|
||||
[2] = new List<TemplateComposition> { new("Motor") { ComposedTemplateId = 7 } },
|
||||
[3] = new List<TemplateComposition> { new("Motor") { ComposedTemplateId = 6 } },
|
||||
};
|
||||
var chains = new Dictionary<int, IReadOnlyList<Template>>
|
||||
{
|
||||
[2] = [pump1, pump],
|
||||
[7] = [pump1Motor, pumpMotor, motor],
|
||||
[6] = [pumpMotor, motor],
|
||||
};
|
||||
|
||||
var result = _sut.Flatten(CreateInstance(), [skid], compositions, chains, new Dictionary<int, DataConnection>());
|
||||
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal("Pump1.Motor.OnOverloadAlt",
|
||||
result.Value.Alarms.Single(a => a.CanonicalName == "Pump1.Motor.Overload").OnTriggerScriptCanonicalName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// TPL-2: a derived template that overrides the on-trigger script (a new row with a
|
||||
/// different id) keeps the base alarm's link, and the overridden code is what runs.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void DerivedScriptOverride_KeepsBaseAlarmOnTriggerLink()
|
||||
{
|
||||
var tank = CreateTemplate(1, "Tank");
|
||||
tank.Scripts.Add(new TemplateScript("OnHighLevel", "// base") { Id = 10 });
|
||||
tank.Alarms.Add(Alarm("HighLevel", 10));
|
||||
var heater = CreateTemplate(2, "TankWithHeater", 1);
|
||||
heater.Scripts.Add(new TemplateScript("OnHighLevel", "// derived") { Id = 20, IsInherited = false });
|
||||
heater.Alarms.Add(Alarm("HighLevel", 10, inherited: true));
|
||||
|
||||
var result = _sut.Flatten(CreateInstance(templateId: 2), [heater, tank],
|
||||
new Dictionary<int, IReadOnlyList<TemplateComposition>>(),
|
||||
new Dictionary<int, IReadOnlyList<Template>>(),
|
||||
new Dictionary<int, DataConnection>());
|
||||
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal("OnHighLevel", result.Value.Alarms.Single(a => a.CanonicalName == "HighLevel").OnTriggerScriptCanonicalName);
|
||||
Assert.Equal("// derived", result.Value.Scripts.Single(s => s.CanonicalName == "OnHighLevel").Code);
|
||||
}
|
||||
|
||||
/// <summary>TPL-2 for a composed module: a derived-module override keeps the slot alarm's link.</summary>
|
||||
[Fact]
|
||||
public void DerivedScriptOverride_InComposedModule_KeepsLink()
|
||||
{
|
||||
var pump = CreateTemplate(10, "Pump");
|
||||
pump.Scripts.Add(new TemplateScript("OnHigh", "// base") { Id = 100 });
|
||||
pump.Alarms.Add(Alarm("HighTemp", 100));
|
||||
var slot = SlotDerived(11, pump, 110);
|
||||
slot.Scripts.Clear();
|
||||
slot.Scripts.Add(new TemplateScript("OnHigh", "// slot override") { Id = 111, IsInherited = false });
|
||||
var skid = CreateTemplate(1, "Skid");
|
||||
|
||||
var result = _sut.Flatten(CreateInstance(), [skid],
|
||||
new Dictionary<int, IReadOnlyList<TemplateComposition>>
|
||||
{
|
||||
[1] = new List<TemplateComposition> { new("P") { ComposedTemplateId = 11 } },
|
||||
},
|
||||
new Dictionary<int, IReadOnlyList<Template>> { [11] = [slot, pump] },
|
||||
new Dictionary<int, DataConnection>());
|
||||
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal("P.OnHigh", result.Value.Alarms.Single(a => a.CanonicalName == "P.HighTemp").OnTriggerScriptCanonicalName);
|
||||
Assert.Equal("// slot override", result.Value.Scripts.Single(s => s.CanonicalName == "P.OnHigh").Code);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Legacy fallback kept: an alarm whose on-trigger script id is not a script row of its
|
||||
/// own chain (here a root alarm pointing at a composed module's script) still resolves
|
||||
/// through the flatten-wide id map, as before.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void OutOfChainScriptId_StillResolvesThroughLegacyIdMap()
|
||||
{
|
||||
var pump = CreateTemplate(2, "Pump");
|
||||
pump.Scripts.Add(new TemplateScript("Handler", "// h") { Id = 60 });
|
||||
var station = CreateTemplate(1, "Station");
|
||||
station.Alarms.Add(Alarm("StationAlarm", 60));
|
||||
|
||||
var result = _sut.Flatten(CreateInstance(), [station],
|
||||
new Dictionary<int, IReadOnlyList<TemplateComposition>>
|
||||
{
|
||||
[1] = new List<TemplateComposition> { new("Main") { ComposedTemplateId = 2 } },
|
||||
},
|
||||
new Dictionary<int, IReadOnlyList<Template>> { [2] = [pump] },
|
||||
new Dictionary<int, DataConnection>());
|
||||
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal("Main.Handler", result.Value.Alarms.Single(a => a.CanonicalName == "StationAlarm").OnTriggerScriptCanonicalName);
|
||||
}
|
||||
|
||||
/// <summary>A dangling on-trigger script id still resolves to null.</summary>
|
||||
[Fact]
|
||||
public void DanglingScriptId_ResolvesToNull()
|
||||
{
|
||||
var t = CreateTemplate(1, "T");
|
||||
t.Alarms.Add(Alarm("A", 999));
|
||||
|
||||
var result = _sut.Flatten(CreateInstance(), [t],
|
||||
new Dictionary<int, IReadOnlyList<TemplateComposition>>(),
|
||||
new Dictionary<int, IReadOnlyList<Template>>(),
|
||||
new Dictionary<int, DataConnection>());
|
||||
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Null(result.Value.Alarms.Single().OnTriggerScriptCanonicalName);
|
||||
}
|
||||
}
|
||||
+182
@@ -0,0 +1,182 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Diagnostics;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates;
|
||||
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.Types.Templates;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Types.Transport;
|
||||
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase;
|
||||
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Repositories;
|
||||
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Services;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.Transport.IntegrationTests.Import;
|
||||
|
||||
/// <summary>
|
||||
/// WP2 task 2.6 — template Overwrite and the composition rewire.
|
||||
/// TRN-4: a bundle template with no compositions skipped the clear, so the target's
|
||||
/// slots survived an Overwrite the preview said would remove them.
|
||||
/// TRN-5: the rewire deleted a removed slot's row without its slot-owned derived
|
||||
/// template, leaving an orphan with a dangling <c>OwnerCompositionId</c>.
|
||||
/// </summary>
|
||||
public sealed class CompositionOverwriteTests : IDisposable
|
||||
{
|
||||
private readonly ServiceProvider _provider;
|
||||
|
||||
/// <summary>Builds an in-memory configuration database plus the Transport services.</summary>
|
||||
public CompositionOverwriteTests()
|
||||
{
|
||||
var services = new ServiceCollection();
|
||||
services.AddSingleton<IConfiguration>(new ConfigurationBuilder().AddInMemoryCollection().Build());
|
||||
var dbName = $"CompositionOverwriteTests_{Guid.NewGuid()}";
|
||||
services.AddDbContext<ScadaBridgeDbContext>(opts => opts
|
||||
.UseInMemoryDatabase(dbName)
|
||||
.ConfigureWarnings(w => w.Ignore(InMemoryEventId.TransactionIgnoredWarning)));
|
||||
services.AddSingleton<ITemplateGraphWatermark, TemplateGraphWatermark>();
|
||||
services.AddScoped<ITemplateEngineRepository, TemplateEngineRepository>();
|
||||
services.AddScoped<IExternalSystemRepository, ExternalSystemRepository>();
|
||||
services.AddScoped<INotificationRepository, NotificationRepository>();
|
||||
services.AddScoped<IInboundApiRepository, InboundApiRepository>();
|
||||
services.AddScoped<ISiteRepository, SiteRepository>();
|
||||
services.AddScoped<IAuditCorrelationContext, AuditCorrelationContext>();
|
||||
services.AddScoped<IAuditService, AuditService>();
|
||||
services.AddTransport();
|
||||
_provider = services.BuildServiceProvider();
|
||||
}
|
||||
|
||||
/// <summary>Releases the resources held by this instance.</summary>
|
||||
public void Dispose() => _provider.Dispose();
|
||||
|
||||
/// <summary>TRN-4: Overwrite with a composition-less bundle template removes the target's slots.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task Overwrite_with_no_bundle_compositions_removes_target_compositions()
|
||||
{
|
||||
await SeedAsync(ctx =>
|
||||
{
|
||||
ctx.Templates.Add(new Template("B"));
|
||||
ctx.Templates.Add(new Template("A"));
|
||||
});
|
||||
var bundle = await ExportAllTemplatesAsync();
|
||||
|
||||
// Target: A now composes B as b1.
|
||||
await SeedAsync(ctx =>
|
||||
{
|
||||
var a = ctx.Templates.Single(t => t.Name == "A");
|
||||
var b = ctx.Templates.Single(t => t.Name == "B");
|
||||
ctx.TemplateCompositions.Add(new TemplateComposition("b1") { TemplateId = a.Id, ComposedTemplateId = b.Id });
|
||||
});
|
||||
|
||||
await ImportOverwriteAsync(bundle, "A", "B");
|
||||
|
||||
await using var scope = _provider.CreateAsyncScope();
|
||||
var ctx = scope.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>();
|
||||
var aId = await ctx.Templates.Where(t => t.Name == "A").Select(t => t.Id).SingleAsync();
|
||||
Assert.False(await ctx.TemplateCompositions.AnyAsync(c => c.TemplateId == aId));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// TRN-5: target owner has slot S1 with a slot-owned derived template; the bundle
|
||||
/// owner has only S2. Overwrite removes S1 AND its derived template.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task Overwrite_removing_a_slot_deletes_its_slot_owned_derived_template()
|
||||
{
|
||||
// Source: A composes B directly as S2.
|
||||
await SeedAsync(ctx =>
|
||||
{
|
||||
ctx.Templates.Add(new Template("B"));
|
||||
ctx.Templates.Add(new Template("A"));
|
||||
});
|
||||
await SeedAsync(ctx =>
|
||||
{
|
||||
var a = ctx.Templates.Single(t => t.Name == "A");
|
||||
var b = ctx.Templates.Single(t => t.Name == "B");
|
||||
ctx.TemplateCompositions.Add(new TemplateComposition("S2") { TemplateId = a.Id, ComposedTemplateId = b.Id });
|
||||
});
|
||||
var bundle = await ExportAllTemplatesAsync();
|
||||
|
||||
// Target: drop S2; A instead owns slot S1 whose composed template is a
|
||||
// slot-owned derived template of B.
|
||||
await SeedAsync(ctx =>
|
||||
{
|
||||
ctx.TemplateCompositions.RemoveRange(ctx.TemplateCompositions);
|
||||
});
|
||||
int derivedId = 0;
|
||||
await SeedAsync(ctx =>
|
||||
{
|
||||
var a = ctx.Templates.Single(t => t.Name == "A");
|
||||
var b = ctx.Templates.Single(t => t.Name == "B");
|
||||
var derived = new Template("A.S1") { ParentTemplateId = b.Id, IsDerived = true };
|
||||
ctx.Templates.Add(derived);
|
||||
ctx.SaveChanges();
|
||||
var slot = new TemplateComposition("S1") { TemplateId = a.Id, ComposedTemplateId = derived.Id };
|
||||
ctx.TemplateCompositions.Add(slot);
|
||||
ctx.SaveChanges();
|
||||
derived.OwnerCompositionId = slot.Id;
|
||||
derivedId = derived.Id;
|
||||
});
|
||||
|
||||
await ImportOverwriteAsync(bundle, "A", "B");
|
||||
|
||||
await using var scope = _provider.CreateAsyncScope();
|
||||
var ctx = scope.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>();
|
||||
var aId = await ctx.Templates.Where(t => t.Name == "A").Select(t => t.Id).SingleAsync();
|
||||
var slots = await ctx.TemplateCompositions.Where(c => c.TemplateId == aId).Select(c => c.InstanceName).ToListAsync();
|
||||
Assert.Equal(new[] { "S2" }, slots);
|
||||
Assert.False(await ctx.Templates.AnyAsync(t => t.Id == derivedId),
|
||||
"the removed slot's derived template must be deleted with it");
|
||||
}
|
||||
|
||||
private async Task SeedAsync(Action<ScadaBridgeDbContext> seed)
|
||||
{
|
||||
await using var scope = _provider.CreateAsyncScope();
|
||||
var ctx = scope.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>();
|
||||
seed(ctx);
|
||||
await ctx.SaveChangesAsync();
|
||||
}
|
||||
|
||||
private async Task<byte[]> ExportAllTemplatesAsync()
|
||||
{
|
||||
await using var scope = _provider.CreateAsyncScope();
|
||||
var exporter = scope.ServiceProvider.GetRequiredService<IBundleExporter>();
|
||||
var ctx = scope.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>();
|
||||
var templateIds = await ctx.Templates.Select(t => t.Id).ToListAsync();
|
||||
var selection = new ExportSelection(
|
||||
TemplateIds: templateIds,
|
||||
SharedScriptIds: Array.Empty<int>(),
|
||||
ExternalSystemIds: Array.Empty<int>(),
|
||||
DatabaseConnectionIds: Array.Empty<int>(),
|
||||
NotificationListIds: Array.Empty<int>(),
|
||||
SmtpConfigurationIds: Array.Empty<int>(),
|
||||
ApiMethodIds: Array.Empty<int>(),
|
||||
IncludeDependencies: false);
|
||||
var stream = await exporter.ExportAsync(selection, user: "alice", sourceEnvironment: "dev",
|
||||
passphrase: null, cancellationToken: CancellationToken.None);
|
||||
using var ms = new MemoryStream();
|
||||
await stream.CopyToAsync(ms);
|
||||
return ms.ToArray();
|
||||
}
|
||||
|
||||
private async Task ImportOverwriteAsync(byte[] bundle, params string[] templateNames)
|
||||
{
|
||||
Guid sessionId;
|
||||
await using (var scope = _provider.CreateAsyncScope())
|
||||
{
|
||||
var importer = scope.ServiceProvider.GetRequiredService<IBundleImporter>();
|
||||
using var input = new MemoryStream(bundle, writable: false);
|
||||
sessionId = (await importer.LoadAsync(input, passphrase: null)).SessionId;
|
||||
}
|
||||
|
||||
await using (var scope = _provider.CreateAsyncScope())
|
||||
{
|
||||
var importer = scope.ServiceProvider.GetRequiredService<IBundleImporter>();
|
||||
await importer.ApplyAsync(sessionId,
|
||||
templateNames.Select(n => new ImportResolution("Template", n, ResolutionAction.Overwrite, null)).ToList(),
|
||||
user: "bob");
|
||||
}
|
||||
}
|
||||
}
|
||||
+520
@@ -0,0 +1,520 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Diagnostics;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates;
|
||||
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.Types.Enums;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Types.Templates;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Types.Transport;
|
||||
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase;
|
||||
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Repositories;
|
||||
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Services;
|
||||
using ZB.MOM.WW.ScadaBridge.Transport.Serialization;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.Transport.IntegrationTests.Import;
|
||||
|
||||
/// <summary>
|
||||
/// WP2 tasks 2.4 + 2.5 against the real importer and an EF context:
|
||||
/// TRN-2 (a changed secret-bearing value reads Modified, value-free), TRN-6 (instance diff
|
||||
/// compares the bound connection, not State), TRN-3 (preview honours the name map; CreateNew
|
||||
/// against an existing same-name row maps to it), TRN-7 (site-scoped and template-reference
|
||||
/// lookups are case-insensitive), TRN-8 (areas resolve by full path), TRN-9 (Rename is
|
||||
/// rejected for sites / data connections / SMTP / SMS).
|
||||
/// </summary>
|
||||
public sealed class ImportMappingAndIdentityTests : IDisposable
|
||||
{
|
||||
private readonly ServiceProvider _provider;
|
||||
|
||||
/// <summary>Builds an in-memory configuration database plus the Transport services.</summary>
|
||||
public ImportMappingAndIdentityTests()
|
||||
{
|
||||
var services = new ServiceCollection();
|
||||
services.AddSingleton<Microsoft.AspNetCore.DataProtection.IDataProtectionProvider>(
|
||||
new Microsoft.AspNetCore.DataProtection.EphemeralDataProtectionProvider());
|
||||
services.AddSingleton<IConfiguration>(new ConfigurationBuilder().AddInMemoryCollection().Build());
|
||||
var dbName = $"ImportMappingAndIdentityTests_{Guid.NewGuid()}";
|
||||
services.AddDbContext<ScadaBridgeDbContext>(opts => opts
|
||||
.UseInMemoryDatabase(dbName)
|
||||
.ConfigureWarnings(w => w.Ignore(InMemoryEventId.TransactionIgnoredWarning)));
|
||||
services.AddSingleton<ITemplateGraphWatermark, TemplateGraphWatermark>();
|
||||
services.AddScoped<ITemplateEngineRepository, TemplateEngineRepository>();
|
||||
services.AddScoped<IExternalSystemRepository, ExternalSystemRepository>();
|
||||
services.AddScoped<INotificationRepository, NotificationRepository>();
|
||||
services.AddScoped<IInboundApiRepository, InboundApiRepository>();
|
||||
services.AddScoped<ISiteRepository, SiteRepository>();
|
||||
services.AddScoped<IAuditCorrelationContext, AuditCorrelationContext>();
|
||||
services.AddScoped<IAuditService, AuditService>();
|
||||
services.AddTransport();
|
||||
_provider = services.BuildServiceProvider();
|
||||
}
|
||||
|
||||
/// <summary>Releases the resources held by this instance.</summary>
|
||||
public void Dispose() => _provider.Dispose();
|
||||
|
||||
// ── TRN-2 / TRN-6 (task 2.4) ─────────────────────────────────────────────
|
||||
|
||||
/// <summary>TRN-2: a target whose connection endpoint changed previews Modified, never echoing the config.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task Preview_changed_connection_configuration_is_Modified_without_echo()
|
||||
{
|
||||
await SeedSiteAsync("plant-1", ("OPC1", "{\"endpoint\":\"opc.tcp://source-host:4840\"}"));
|
||||
var sessionId = await ExportSitesAndLoadAsync();
|
||||
await MutateAsync(ctx => ctx.DataConnections.Single().PrimaryConfiguration = "{\"endpoint\":\"opc.tcp://target-host:4840\"}");
|
||||
|
||||
var preview = await PreviewAsync(sessionId);
|
||||
|
||||
var item = preview.Items.Single(i => i.EntityType == "DataConnection");
|
||||
Assert.Equal(ConflictKind.Modified, item.Kind);
|
||||
using var diff = System.Text.Json.JsonDocument.Parse(item.FieldDiffJson!);
|
||||
var change = diff.RootElement.GetProperty("changes").EnumerateArray()
|
||||
.Single(c => c.GetProperty("field").GetString() == "Secrets.PrimaryConfiguration");
|
||||
Assert.Equal("<changed>", change.GetProperty("newValue").GetString());
|
||||
Assert.DoesNotContain("source-host", item.FieldDiffJson);
|
||||
Assert.DoesNotContain("target-host", item.FieldDiffJson);
|
||||
}
|
||||
|
||||
/// <summary>TRN-6: rebinding an attribute to another connection previews Modified; a State-only change is Identical.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task Preview_instance_diff_covers_bound_connection_and_ignores_state()
|
||||
{
|
||||
await SeedSiteAsync("plant-1", ("OPC1", "{}"), ("OPC2", "{}"));
|
||||
await SeedInstanceAsync("plant-1", "Pump-01", boundTo: "OPC1");
|
||||
var sessionId = await ExportSitesAndLoadAsync();
|
||||
|
||||
// State only: Identical.
|
||||
await MutateAsync(ctx => ctx.Instances.Single().State = InstanceState.Disabled);
|
||||
var stateOnly = await PreviewAsync(sessionId);
|
||||
Assert.Equal(ConflictKind.Identical, stateOnly.Items.Single(i => i.EntityType == "Instance").Kind);
|
||||
|
||||
// Rebind OPC1 -> OPC2 on the target: Modified.
|
||||
await MutateAsync(ctx =>
|
||||
{
|
||||
var opc2 = ctx.DataConnections.Single(c => c.Name == "OPC2");
|
||||
ctx.InstanceConnectionBindings.Single().DataConnectionId = opc2.Id;
|
||||
});
|
||||
var rebound = await PreviewAsync(sessionId);
|
||||
var item = rebound.Items.Single(i => i.EntityType == "Instance");
|
||||
Assert.Equal(ConflictKind.Modified, item.Kind);
|
||||
Assert.Contains("ConnectionBindings", item.FieldDiffJson);
|
||||
}
|
||||
|
||||
// ── TRN-3 (task 2.5) ─────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// TRN-3 scenario A: an instance-only bundle for site-a bound to OPC1, imported with
|
||||
/// site-a mapped to site-x (which has OPC1). The unmapped preview blocks; the mapped
|
||||
/// preview does not, auto-matches the connection on the mapped site, and the apply binds it.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task Preview_with_site_map_resolves_connection_on_the_mapped_site()
|
||||
{
|
||||
await SeedTemplateAsync("Pump");
|
||||
await SeedSiteAsync("site-x", ("OPC1", "{}"));
|
||||
var sessionId = await PackAndLoadAsync(Content(instances:
|
||||
[
|
||||
Instance("Pump-01", "site-a", bindings: [new InstanceConnectionBindingDto("Flow", "OPC1", "ns=2;s=Flow")]),
|
||||
]));
|
||||
|
||||
var unmapped = await PreviewAsync(sessionId);
|
||||
Assert.Contains(unmapped.Items, i => i.Kind == ConflictKind.Blocker && i.Name == "site-a/OPC1");
|
||||
|
||||
var map = new BundleNameMap(
|
||||
[new SiteMapping("site-a", MappingAction.MapToExisting, "site-x")],
|
||||
Array.Empty<ConnectionMapping>());
|
||||
var mapped = await PreviewAsync(sessionId, map);
|
||||
Assert.DoesNotContain(mapped.Items, i => i.Kind == ConflictKind.Blocker);
|
||||
Assert.Equal("site-x", mapped.RequiredSiteMappings.Single().AutoMatchTargetIdentifier);
|
||||
Assert.Equal("OPC1", mapped.RequiredConnectionMappings.Single().AutoMatchTargetName);
|
||||
|
||||
await ApplyAsync(sessionId,
|
||||
[new ImportResolution("Instance", "Pump-01", ResolutionAction.Add, null)],
|
||||
map with
|
||||
{
|
||||
Connections = [new ConnectionMapping("site-a", "OPC1", MappingAction.MapToExisting, "OPC1")],
|
||||
});
|
||||
|
||||
await using var scope = _provider.CreateAsyncScope();
|
||||
var ctx = scope.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>();
|
||||
var siteX = await ctx.Sites.SingleAsync(s => s.SiteIdentifier == "site-x");
|
||||
var opc1 = await ctx.DataConnections.SingleAsync(c => c.SiteId == siteX.Id && c.Name == "OPC1");
|
||||
var instance = await ctx.Instances.Include(i => i.ConnectionBindings).SingleAsync();
|
||||
Assert.Equal(siteX.Id, instance.SiteId);
|
||||
Assert.Equal(opc1.Id, instance.ConnectionBindings.Single().DataConnectionId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// TRN-3 scenario B: CreateNew for a carried connection whose name already exists on the
|
||||
/// mapped target site maps to the existing row instead of inserting a duplicate.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task CreateNew_connection_with_existing_name_on_mapped_site_maps_to_it()
|
||||
{
|
||||
await SeedSiteAsync("site-x", ("OPC1", "{\"endpoint\":\"target\"}"));
|
||||
var sessionId = await PackAndLoadAsync(Content(connections:
|
||||
[
|
||||
new DataConnectionDto("site-a", "OPC1", "OpcUa", 3,
|
||||
new SecretsBlock(new Dictionary<string, string> { ["PrimaryConfiguration"] = "{\"endpoint\":\"source\"}" })),
|
||||
]));
|
||||
|
||||
await ApplyAsync(sessionId,
|
||||
[new ImportResolution("DataConnection", "site-a/OPC1", ResolutionAction.Skip, null)],
|
||||
new BundleNameMap(
|
||||
[new SiteMapping("site-a", MappingAction.MapToExisting, "site-x")],
|
||||
[new ConnectionMapping("site-a", "OPC1", MappingAction.CreateNew, null)]));
|
||||
|
||||
await using var scope = _provider.CreateAsyncScope();
|
||||
var ctx = scope.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>();
|
||||
var conn = await ctx.DataConnections.SingleAsync();
|
||||
Assert.Equal("{\"endpoint\":\"target\"}", conn.PrimaryConfiguration);
|
||||
}
|
||||
|
||||
// ── TRN-7 (task 2.5) ─────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// TRN-7: a bundle connection differing only in case matches the target row (preview is
|
||||
/// not New, apply does not insert a duplicate the unique (SiteId, Name) index would reject),
|
||||
/// and an instance binding naming it in a different case resolves to it. (The instance
|
||||
/// UniqueName half of TRN-7 depends on the SQL Server collation returning the case
|
||||
/// variant from the repository read, which the in-memory provider does not emulate; the
|
||||
/// importer's own lookups over that read are case-insensitive.)
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task Case_variant_connection_matches_existing_row()
|
||||
{
|
||||
await SeedTemplateAsync("Pump");
|
||||
await SeedSiteAsync("plant-1", ("OPC1", "{}"));
|
||||
var sessionId = await PackAndLoadAsync(Content(
|
||||
sites: [new SiteDto("plant-1", "plant-1", null, null, null, null, null)],
|
||||
connections: [new DataConnectionDto("plant-1", "Opc1", "OpcUa", 3,
|
||||
new SecretsBlock(new Dictionary<string, string> { ["PrimaryConfiguration"] = "{}" }))],
|
||||
instances: [Instance("Pump-01", "plant-1", bindings: [new InstanceConnectionBindingDto("Flow", "opc1", null)])]));
|
||||
|
||||
var preview = await PreviewAsync(sessionId);
|
||||
Assert.Equal(ConflictKind.Identical, preview.Items.Single(i => i.EntityType == "DataConnection").Kind);
|
||||
Assert.DoesNotContain(preview.Items, i => i.Kind == ConflictKind.Blocker);
|
||||
|
||||
await ApplyAsync(sessionId,
|
||||
[
|
||||
new ImportResolution("DataConnection", "plant-1/Opc1", ResolutionAction.Overwrite, null),
|
||||
new ImportResolution("Instance", "Pump-01", ResolutionAction.Add, null),
|
||||
],
|
||||
BundleNameMap.Empty);
|
||||
|
||||
await using var scope = _provider.CreateAsyncScope();
|
||||
var ctx = scope.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>();
|
||||
var conn = await ctx.DataConnections.SingleAsync();
|
||||
var instance = await ctx.Instances.Include(i => i.ConnectionBindings).SingleAsync();
|
||||
Assert.Equal(conn.Id, instance.ConnectionBindings.Single().DataConnectionId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// TRN-7: a child whose bundle base is 'PumpBase' resolves its inheritance edge against
|
||||
/// the target's 'pumpbase' (the base itself is not re-imported) instead of nulling it.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task Case_variant_base_template_keeps_child_inheritance_edge()
|
||||
{
|
||||
await MutateAsync(ctx => ctx.Templates.Add(new Template("PumpBase")));
|
||||
await MutateAsync(ctx => ctx.Templates.Add(new Template("Child") { ParentTemplateId = ctx.Templates.Single(t => t.Name == "PumpBase").Id }));
|
||||
var bundle = await ExportTemplatesAsync();
|
||||
await MutateAsync(ctx => ctx.Templates.Single(t => t.Name == "PumpBase").Name = "pumpbase");
|
||||
|
||||
var sessionId = await LoadAsync(bundle);
|
||||
await ApplyAsync(sessionId,
|
||||
[
|
||||
new ImportResolution("Template", "PumpBase", ResolutionAction.Skip, null),
|
||||
new ImportResolution("Template", "Child", ResolutionAction.Overwrite, null),
|
||||
],
|
||||
BundleNameMap.Empty);
|
||||
|
||||
await using var scope = _provider.CreateAsyncScope();
|
||||
var ctx = scope.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>();
|
||||
var baseId = await ctx.Templates.Where(t => t.Name == "pumpbase").Select(t => t.Id).SingleAsync();
|
||||
var child = await ctx.Templates.SingleAsync(t => t.Name == "Child");
|
||||
Assert.Equal(baseId, child.ParentTemplateId);
|
||||
}
|
||||
|
||||
// ── TRN-8 (task 2.5) ─────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>TRN-8: an instance in Line2/Cell lands in Line2/Cell, not whichever 'Cell' comes back first.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task Area_resolves_by_full_path_when_leaf_name_is_shared()
|
||||
{
|
||||
await SeedSiteAsync("plant-1", ("OPC1", "{}"));
|
||||
var (line1Cell, line2Cell) = await SeedTwoCellsAsync("plant-1");
|
||||
await SeedInstanceAsync("plant-1", "Pump-01", boundTo: "OPC1", areaId: line2Cell);
|
||||
var sessionId = await ExportSitesAndLoadAsync();
|
||||
// Target: move the instance to Line1/Cell, then Overwrite from the bundle.
|
||||
await MutateAsync(ctx => ctx.Instances.Single().AreaId = line1Cell);
|
||||
|
||||
var preview = await PreviewAsync(sessionId);
|
||||
var item = preview.Items.Single(i => i.EntityType == "Instance");
|
||||
Assert.Equal(ConflictKind.Modified, item.Kind);
|
||||
Assert.Contains("AreaPath", item.FieldDiffJson);
|
||||
|
||||
await ApplyAsync(sessionId,
|
||||
[new ImportResolution("Instance", "Pump-01", ResolutionAction.Overwrite, null)],
|
||||
BundleNameMap.Empty);
|
||||
|
||||
await using var scope = _provider.CreateAsyncScope();
|
||||
var ctx = scope.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>();
|
||||
Assert.Equal(line2Cell, (await ctx.Instances.SingleAsync()).AreaId);
|
||||
Assert.Equal(4, await ctx.Areas.CountAsync()); // Line1, Line2 and both Cells — nothing created
|
||||
|
||||
}
|
||||
|
||||
/// <summary>TRN-8: a missing nested area is created under its real parent, not at the site root.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task Missing_nested_area_is_created_under_its_parent()
|
||||
{
|
||||
await SeedTemplateAsync("Pump");
|
||||
await SeedSiteAsync("plant-1");
|
||||
var sessionId = await PackAndLoadAsync(Content(instances:
|
||||
[
|
||||
Instance("Pump-01", "plant-1") with { AreaName = "Cell", AreaPath = ["Line2", "Cell"] },
|
||||
]));
|
||||
|
||||
await ApplyAsync(sessionId, [new ImportResolution("Instance", "Pump-01", ResolutionAction.Add, null)], BundleNameMap.Empty);
|
||||
|
||||
await using var scope = _provider.CreateAsyncScope();
|
||||
var ctx = scope.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>();
|
||||
var line2 = await ctx.Areas.SingleAsync(a => a.Name == "Line2");
|
||||
var cell = await ctx.Areas.SingleAsync(a => a.Name == "Cell");
|
||||
Assert.Null(line2.ParentAreaId);
|
||||
Assert.Equal(line2.Id, cell.ParentAreaId);
|
||||
Assert.Equal(cell.Id, (await ctx.Instances.SingleAsync()).AreaId);
|
||||
}
|
||||
|
||||
/// <summary>TRN-8: a legacy (path-less) bundle with an ambiguous leaf name warns instead of guessing silently.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task Legacy_ambiguous_leaf_area_name_warns()
|
||||
{
|
||||
await SeedTemplateAsync("Pump");
|
||||
await SeedSiteAsync("plant-1");
|
||||
await SeedTwoCellsAsync("plant-1");
|
||||
var sessionId = await PackAndLoadAsync(Content(instances:
|
||||
[
|
||||
Instance("Pump-01", "plant-1") with { AreaName = "Cell" },
|
||||
]));
|
||||
|
||||
var result = await ApplyAsync(sessionId, [new ImportResolution("Instance", "Pump-01", ResolutionAction.Add, null)], BundleNameMap.Empty);
|
||||
|
||||
Assert.Contains(result.Warnings, w => w.Contains("area 'Cell' matches 2 areas"));
|
||||
}
|
||||
|
||||
// ── TRN-9 (task 2.5) ─────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>TRN-9: Rename is rejected for sites, data connections, SMTP and SMS configurations.</summary>
|
||||
/// <param name="entityType">The resolution's entity type.</param>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Theory]
|
||||
[InlineData("Site")]
|
||||
[InlineData("DataConnection")]
|
||||
[InlineData("SmtpConfiguration")]
|
||||
[InlineData("SmsConfiguration")]
|
||||
public async Task Rename_is_rejected_for_unsupported_entity_types(string entityType)
|
||||
{
|
||||
var sessionId = await PackAndLoadAsync(Content());
|
||||
var ex = await Assert.ThrowsAsync<ArgumentException>(() => ApplyAsync(sessionId,
|
||||
[new ImportResolution(entityType, "x", ResolutionAction.Rename, "y")], BundleNameMap.Empty));
|
||||
Assert.Contains("Rename is not supported", ex.Message);
|
||||
}
|
||||
|
||||
// ── helpers ──────────────────────────────────────────────────────────────
|
||||
|
||||
private async Task MutateAsync(Action<ScadaBridgeDbContext> mutate)
|
||||
{
|
||||
await using var scope = _provider.CreateAsyncScope();
|
||||
var ctx = scope.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>();
|
||||
mutate(ctx);
|
||||
await ctx.SaveChangesAsync();
|
||||
}
|
||||
|
||||
private Task SeedTemplateAsync(string name) => MutateAsync(ctx =>
|
||||
{
|
||||
var t = new Template(name);
|
||||
t.Attributes.Add(new TemplateAttribute("Flow") { Value = "0" });
|
||||
ctx.Templates.Add(t);
|
||||
});
|
||||
|
||||
private async Task SeedSiteAsync(string identifier, params (string Name, string Config)[] connections)
|
||||
{
|
||||
await MutateAsync(ctx => ctx.Sites.Add(new Site(identifier, identifier)));
|
||||
await MutateAsync(ctx =>
|
||||
{
|
||||
var site = ctx.Sites.Single(s => s.SiteIdentifier == identifier);
|
||||
foreach (var (name, config) in connections)
|
||||
ctx.DataConnections.Add(new DataConnection(name, "OpcUa", site.Id) { PrimaryConfiguration = config, FailoverRetryCount = 3 });
|
||||
});
|
||||
}
|
||||
|
||||
private async Task SeedInstanceAsync(string siteIdentifier, string name, string boundTo, int? areaId = null)
|
||||
{
|
||||
if (!await AnyTemplateAsync()) await SeedTemplateAsync("Pump");
|
||||
await MutateAsync(ctx =>
|
||||
{
|
||||
var site = ctx.Sites.Single(s => s.SiteIdentifier == siteIdentifier);
|
||||
var conn = ctx.DataConnections.Single(c => c.SiteId == site.Id && c.Name == boundTo);
|
||||
var instance = new Instance(name)
|
||||
{
|
||||
TemplateId = ctx.Templates.First().Id, SiteId = site.Id, State = InstanceState.Enabled, AreaId = areaId,
|
||||
};
|
||||
instance.ConnectionBindings.Add(new InstanceConnectionBinding("Flow")
|
||||
{
|
||||
DataConnectionId = conn.Id, DataSourceReferenceOverride = "ns=2;s=Flow",
|
||||
});
|
||||
ctx.Instances.Add(instance);
|
||||
});
|
||||
}
|
||||
|
||||
private async Task<bool> AnyTemplateAsync()
|
||||
{
|
||||
await using var scope = _provider.CreateAsyncScope();
|
||||
return await scope.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>().Templates.AnyAsync();
|
||||
}
|
||||
|
||||
private async Task<(int Line1Cell, int Line2Cell)> SeedTwoCellsAsync(string siteIdentifier)
|
||||
{
|
||||
int line1Cell = 0, line2Cell = 0;
|
||||
await MutateAsync(ctx =>
|
||||
{
|
||||
var siteId = ctx.Sites.Single(s => s.SiteIdentifier == siteIdentifier).Id;
|
||||
ctx.Areas.Add(new Area("Line1") { SiteId = siteId });
|
||||
ctx.Areas.Add(new Area("Line2") { SiteId = siteId });
|
||||
});
|
||||
await MutateAsync(ctx =>
|
||||
{
|
||||
var line1 = ctx.Areas.Single(a => a.Name == "Line1");
|
||||
var line2 = ctx.Areas.Single(a => a.Name == "Line2");
|
||||
ctx.Areas.Add(new Area("Cell") { SiteId = line1.SiteId, ParentAreaId = line1.Id });
|
||||
ctx.Areas.Add(new Area("Cell") { SiteId = line2.SiteId, ParentAreaId = line2.Id });
|
||||
});
|
||||
await using var scope = _provider.CreateAsyncScope();
|
||||
var c = scope.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>();
|
||||
var l1 = await c.Areas.SingleAsync(a => a.Name == "Line1");
|
||||
var l2 = await c.Areas.SingleAsync(a => a.Name == "Line2");
|
||||
line1Cell = (await c.Areas.SingleAsync(a => a.Name == "Cell" && a.ParentAreaId == l1.Id)).Id;
|
||||
line2Cell = (await c.Areas.SingleAsync(a => a.Name == "Cell" && a.ParentAreaId == l2.Id)).Id;
|
||||
return (line1Cell, line2Cell);
|
||||
}
|
||||
|
||||
private static InstanceDto Instance(string name, string site, IReadOnlyList<InstanceConnectionBindingDto>? bindings = null) =>
|
||||
new(name, "Pump", site, AreaName: null, InstanceState.NotDeployed,
|
||||
Array.Empty<InstanceAttributeOverrideDto>(),
|
||||
Array.Empty<InstanceAlarmOverrideDto>(),
|
||||
Array.Empty<InstanceNativeAlarmSourceOverrideDto>(),
|
||||
bindings ?? Array.Empty<InstanceConnectionBindingDto>());
|
||||
|
||||
private static BundleContentDto Content(
|
||||
IReadOnlyList<SiteDto>? sites = null,
|
||||
IReadOnlyList<DataConnectionDto>? connections = null,
|
||||
IReadOnlyList<InstanceDto>? instances = null) =>
|
||||
new(
|
||||
TemplateFolders: Array.Empty<TemplateFolderDto>(),
|
||||
Templates: Array.Empty<TemplateDto>(),
|
||||
SharedScripts: Array.Empty<SharedScriptDto>(),
|
||||
ExternalSystems: Array.Empty<ExternalSystemDto>(),
|
||||
DatabaseConnections: Array.Empty<DatabaseConnectionDto>(),
|
||||
NotificationLists: Array.Empty<NotificationListDto>(),
|
||||
SmtpConfigs: Array.Empty<SmtpConfigDto>(),
|
||||
ApiMethods: Array.Empty<ApiMethodDto>())
|
||||
{
|
||||
Sites = sites ?? Array.Empty<SiteDto>(),
|
||||
DataConnections = connections ?? Array.Empty<DataConnectionDto>(),
|
||||
Instances = instances ?? Array.Empty<InstanceDto>(),
|
||||
};
|
||||
|
||||
private async Task<Guid> PackAndLoadAsync(BundleContentDto content)
|
||||
{
|
||||
await using var scope = _provider.CreateAsyncScope();
|
||||
var manifestBuilder = scope.ServiceProvider.GetRequiredService<ManifestBuilder>();
|
||||
var serializer = scope.ServiceProvider.GetRequiredService<BundleSerializer>();
|
||||
var importer = scope.ServiceProvider.GetRequiredService<IBundleImporter>();
|
||||
var summary = new BundleSummary(
|
||||
Templates: 0, TemplateFolders: 0, SharedScripts: 0, ExternalSystems: 0, DbConnections: 0,
|
||||
NotificationLists: 0, SmtpConfigs: 0, ApiMethods: 0,
|
||||
Sites: content.Sites.Count, DataConnections: content.DataConnections.Count, Instances: content.Instances.Count);
|
||||
var manifest = manifestBuilder.Build(
|
||||
sourceEnvironment: "dev", exportedBy: "alice", scadaBridgeVersion: "1.0.0", encryption: null,
|
||||
summary: summary, contents: Array.Empty<ManifestContentEntry>(),
|
||||
contentBytes: serializer.SerializeContentBytes(content));
|
||||
await using var packed = serializer.Pack(content, manifest, passphrase: null, encryptor: null);
|
||||
using var ms = new MemoryStream();
|
||||
await packed.CopyToAsync(ms);
|
||||
ms.Position = 0;
|
||||
return (await importer.LoadAsync(ms, passphrase: null)).SessionId;
|
||||
}
|
||||
|
||||
private async Task<Guid> ExportSitesAndLoadAsync()
|
||||
{
|
||||
byte[] bytes;
|
||||
await using (var scope = _provider.CreateAsyncScope())
|
||||
{
|
||||
var exporter = scope.ServiceProvider.GetRequiredService<IBundleExporter>();
|
||||
var ctx = scope.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>();
|
||||
var selection = new ExportSelection(
|
||||
TemplateIds: Array.Empty<int>(), SharedScriptIds: Array.Empty<int>(),
|
||||
ExternalSystemIds: Array.Empty<int>(), DatabaseConnectionIds: Array.Empty<int>(),
|
||||
NotificationListIds: Array.Empty<int>(), SmtpConfigurationIds: Array.Empty<int>(),
|
||||
ApiMethodIds: Array.Empty<int>(), IncludeDependencies: true,
|
||||
SiteIds: await ctx.Sites.Select(s => s.Id).ToListAsync());
|
||||
var stream = await exporter.ExportAsync(selection, user: "alice", sourceEnvironment: "dev",
|
||||
passphrase: null, cancellationToken: CancellationToken.None);
|
||||
using var ms = new MemoryStream();
|
||||
await stream.CopyToAsync(ms);
|
||||
bytes = ms.ToArray();
|
||||
}
|
||||
return await LoadAsync(bytes);
|
||||
}
|
||||
|
||||
private async Task<byte[]> ExportTemplatesAsync()
|
||||
{
|
||||
await using var scope = _provider.CreateAsyncScope();
|
||||
var exporter = scope.ServiceProvider.GetRequiredService<IBundleExporter>();
|
||||
var ctx = scope.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>();
|
||||
var selection = new ExportSelection(
|
||||
TemplateIds: await ctx.Templates.Select(t => t.Id).ToListAsync(), SharedScriptIds: Array.Empty<int>(),
|
||||
ExternalSystemIds: Array.Empty<int>(), DatabaseConnectionIds: Array.Empty<int>(),
|
||||
NotificationListIds: Array.Empty<int>(), SmtpConfigurationIds: Array.Empty<int>(),
|
||||
ApiMethodIds: Array.Empty<int>(), IncludeDependencies: false);
|
||||
var stream = await exporter.ExportAsync(selection, user: "alice", sourceEnvironment: "dev",
|
||||
passphrase: null, cancellationToken: CancellationToken.None);
|
||||
using var ms = new MemoryStream();
|
||||
await stream.CopyToAsync(ms);
|
||||
return ms.ToArray();
|
||||
}
|
||||
|
||||
private async Task<Guid> LoadAsync(byte[] bundle)
|
||||
{
|
||||
await using var scope = _provider.CreateAsyncScope();
|
||||
using var ms = new MemoryStream(bundle, writable: false);
|
||||
return (await scope.ServiceProvider.GetRequiredService<IBundleImporter>().LoadAsync(ms, passphrase: null)).SessionId;
|
||||
}
|
||||
|
||||
private async Task<ImportPreview> PreviewAsync(Guid sessionId, BundleNameMap? map = null)
|
||||
{
|
||||
await using var scope = _provider.CreateAsyncScope();
|
||||
return await scope.ServiceProvider.GetRequiredService<IBundleImporter>().PreviewAsync(sessionId, CancellationToken.None, map);
|
||||
}
|
||||
|
||||
private async Task<ImportResult> ApplyAsync(Guid sessionId, IReadOnlyList<ImportResolution> resolutions, BundleNameMap map)
|
||||
{
|
||||
await using var scope = _provider.CreateAsyncScope();
|
||||
return await scope.ServiceProvider.GetRequiredService<IBundleImporter>()
|
||||
.ApplyAsync(sessionId, resolutions, user: "bob", ct: CancellationToken.None, nameMap: map);
|
||||
}
|
||||
}
|
||||
+173
@@ -0,0 +1,173 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Diagnostics;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Notifications;
|
||||
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.Types.Transport;
|
||||
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase;
|
||||
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Repositories;
|
||||
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Services;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Types.Templates;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.Transport.IntegrationTests.Import;
|
||||
|
||||
/// <summary>
|
||||
/// TRN-1 (WP2 task 2.1): a notification-list Overwrite must REPLACE the target's
|
||||
/// recipients with the bundle's. <c>GetListByNameAsync</c> used to load the list
|
||||
/// without its recipients, so the apply's <c>Recipients.Clear()</c> ran on an
|
||||
/// unloaded collection, deleted nothing, and the bundle's recipients were appended
|
||||
/// on top — duplicating shared recipients and keeping removed ones, with another
|
||||
/// copy added on every re-import.
|
||||
/// </summary>
|
||||
public sealed class NotificationListOverwriteTests : IDisposable
|
||||
{
|
||||
private readonly ServiceProvider _provider;
|
||||
|
||||
/// <summary>Builds an in-memory configuration database plus the Transport services.</summary>
|
||||
public NotificationListOverwriteTests()
|
||||
{
|
||||
var services = new ServiceCollection();
|
||||
services.AddSingleton<IConfiguration>(new ConfigurationBuilder().AddInMemoryCollection().Build());
|
||||
var dbName = $"NotificationListOverwriteTests_{Guid.NewGuid()}";
|
||||
services.AddDbContext<ScadaBridgeDbContext>(opts => opts
|
||||
.UseInMemoryDatabase(dbName)
|
||||
.ConfigureWarnings(w => w.Ignore(InMemoryEventId.TransactionIgnoredWarning)));
|
||||
services.AddSingleton<ITemplateGraphWatermark, TemplateGraphWatermark>();
|
||||
services.AddScoped<ITemplateEngineRepository, TemplateEngineRepository>();
|
||||
services.AddScoped<IExternalSystemRepository, ExternalSystemRepository>();
|
||||
services.AddScoped<INotificationRepository, NotificationRepository>();
|
||||
services.AddScoped<IInboundApiRepository, InboundApiRepository>();
|
||||
services.AddScoped<ISiteRepository, SiteRepository>();
|
||||
services.AddScoped<IAuditCorrelationContext, AuditCorrelationContext>();
|
||||
services.AddScoped<IAuditService, AuditService>();
|
||||
services.AddTransport();
|
||||
_provider = services.BuildServiceProvider();
|
||||
}
|
||||
|
||||
/// <summary>Releases the resources held by this instance.</summary>
|
||||
public void Dispose() => _provider.Dispose();
|
||||
|
||||
/// <summary>
|
||||
/// Target {A,B} + bundle {A,C} must end as exactly {A,C}, and a second
|
||||
/// Overwrite import of the same bundle must leave it at {A,C}.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task Overwrite_replaces_recipients_and_is_idempotent_on_reimport()
|
||||
{
|
||||
// Source state the bundle captures: {A, C}.
|
||||
await using (var scope = _provider.CreateAsyncScope())
|
||||
{
|
||||
var ctx = scope.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>();
|
||||
var list = new NotificationList("Ops");
|
||||
list.Recipients.Add(NotificationRecipient.ForEmail("A", "a@example.com"));
|
||||
list.Recipients.Add(NotificationRecipient.ForEmail("C", "c@example.com"));
|
||||
ctx.NotificationLists.Add(list);
|
||||
await ctx.SaveChangesAsync();
|
||||
}
|
||||
|
||||
var bundle = await ExportAsync();
|
||||
|
||||
// Turn the database into the target state: {A, B}.
|
||||
await using (var scope = _provider.CreateAsyncScope())
|
||||
{
|
||||
var ctx = scope.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>();
|
||||
var list = await ctx.NotificationLists.Include(l => l.Recipients).SingleAsync(l => l.Name == "Ops");
|
||||
var c = list.Recipients.Single(r => r.Name == "C");
|
||||
list.Recipients.Remove(c);
|
||||
ctx.Remove(c);
|
||||
list.Recipients.Add(NotificationRecipient.ForEmail("B", "b@example.com"));
|
||||
await ctx.SaveChangesAsync();
|
||||
}
|
||||
Assert.Equal(new[] { "A", "B" }, await RecipientNamesAsync());
|
||||
|
||||
await ImportOverwriteAsync(bundle);
|
||||
Assert.Equal(new[] { "A", "C" }, await RecipientNamesAsync());
|
||||
|
||||
// Re-import the same bundle: still exactly {A, C}, no extra copies.
|
||||
await ImportOverwriteAsync(bundle);
|
||||
Assert.Equal(new[] { "A", "C" }, await RecipientNamesAsync());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The repository method itself must return the list with its recipients — every
|
||||
/// caller (importer, delivery adapters) relies on the navigation being populated.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task GetListByNameAsync_loads_recipients()
|
||||
{
|
||||
await using (var scope = _provider.CreateAsyncScope())
|
||||
{
|
||||
var ctx = scope.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>();
|
||||
var list = new NotificationList("Ops");
|
||||
list.Recipients.Add(NotificationRecipient.ForEmail("A", "a@example.com"));
|
||||
ctx.NotificationLists.Add(list);
|
||||
await ctx.SaveChangesAsync();
|
||||
}
|
||||
|
||||
await using (var scope = _provider.CreateAsyncScope())
|
||||
{
|
||||
var repo = scope.ServiceProvider.GetRequiredService<INotificationRepository>();
|
||||
var loaded = await repo.GetListByNameAsync("Ops");
|
||||
Assert.NotNull(loaded);
|
||||
Assert.Single(loaded!.Recipients);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<byte[]> ExportAsync()
|
||||
{
|
||||
await using var scope = _provider.CreateAsyncScope();
|
||||
var exporter = scope.ServiceProvider.GetRequiredService<IBundleExporter>();
|
||||
var ctx = scope.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>();
|
||||
var listIds = await ctx.NotificationLists.Select(l => l.Id).ToListAsync();
|
||||
var selection = new ExportSelection(
|
||||
TemplateIds: Array.Empty<int>(),
|
||||
SharedScriptIds: Array.Empty<int>(),
|
||||
ExternalSystemIds: Array.Empty<int>(),
|
||||
DatabaseConnectionIds: Array.Empty<int>(),
|
||||
NotificationListIds: listIds,
|
||||
SmtpConfigurationIds: Array.Empty<int>(),
|
||||
ApiMethodIds: Array.Empty<int>(),
|
||||
IncludeDependencies: false);
|
||||
var stream = await exporter.ExportAsync(selection, user: "alice", sourceEnvironment: "dev",
|
||||
passphrase: null, cancellationToken: CancellationToken.None);
|
||||
using var ms = new MemoryStream();
|
||||
await stream.CopyToAsync(ms);
|
||||
return ms.ToArray();
|
||||
}
|
||||
|
||||
private async Task ImportOverwriteAsync(byte[] bundle)
|
||||
{
|
||||
Guid sessionId;
|
||||
await using (var scope = _provider.CreateAsyncScope())
|
||||
{
|
||||
var importer = scope.ServiceProvider.GetRequiredService<IBundleImporter>();
|
||||
using var input = new MemoryStream(bundle, writable: false);
|
||||
sessionId = (await importer.LoadAsync(input, passphrase: null)).SessionId;
|
||||
}
|
||||
|
||||
await using (var scope = _provider.CreateAsyncScope())
|
||||
{
|
||||
var importer = scope.ServiceProvider.GetRequiredService<IBundleImporter>();
|
||||
var result = await importer.ApplyAsync(sessionId,
|
||||
new List<ImportResolution> { new("NotificationList", "Ops", ResolutionAction.Overwrite, null) },
|
||||
user: "bob");
|
||||
Assert.Equal(1, result.Overwritten);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<string[]> RecipientNamesAsync()
|
||||
{
|
||||
await using var scope = _provider.CreateAsyncScope();
|
||||
var ctx = scope.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>();
|
||||
return await ctx.NotificationRecipients
|
||||
.Where(r => r.NotificationListId == ctx.NotificationLists.Single(l => l.Name == "Ops").Id)
|
||||
.OrderBy(r => r.Name)
|
||||
.Select(r => r.Name)
|
||||
.ToArrayAsync();
|
||||
}
|
||||
}
|
||||
@@ -118,3 +118,45 @@ public sealed class BundleSecretEncryptorTests
|
||||
Assert.Equal(plaintext, recovered);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// TRN-10 (WP2 task 2.7): the PBKDF2 iteration count read from an uploaded manifest
|
||||
/// must be range-checked before the key is derived, so a hostile bundle cannot pin a
|
||||
/// thread (and the single-flight transport gate) with an absurd count.
|
||||
/// </summary>
|
||||
public sealed class BundleSecretEncryptorIterationBoundTests
|
||||
{
|
||||
private static EncryptionMetadata ValidMetadata() =>
|
||||
new("AES-256-GCM", "PBKDF2-SHA256", EncryptionMetadata.MinPbkdf2Iterations,
|
||||
Convert.ToBase64String(new byte[16]), Convert.ToBase64String(new byte[12]));
|
||||
|
||||
/// <summary>A metadata record whose iteration count was set past the ceiling is refused before PBKDF2 runs.</summary>
|
||||
[Theory]
|
||||
[InlineData(int.MaxValue)]
|
||||
[InlineData(EncryptionMetadata.MaxPbkdf2Iterations + 1)]
|
||||
[InlineData(EncryptionMetadata.MinPbkdf2Iterations - 1)]
|
||||
[InlineData(0)]
|
||||
[InlineData(-1)]
|
||||
public void Decrypt_rejects_out_of_range_iterations_without_deriving(int iterations)
|
||||
{
|
||||
// `with` bypasses the record constructor's range check — the encryptor must
|
||||
// not rely on it.
|
||||
var metadata = ValidMetadata() with { Iterations = iterations };
|
||||
var sw = System.Diagnostics.Stopwatch.StartNew();
|
||||
Assert.ThrowsAny<CryptographicException>(() =>
|
||||
new BundleSecretEncryptor().Decrypt(new byte[32], metadata, "pass"));
|
||||
Assert.True(sw.Elapsed < TimeSpan.FromSeconds(5), "the key must not be derived first");
|
||||
}
|
||||
|
||||
/// <summary>A manifest JSON carrying an absurd iteration count does not yield a usable metadata record.</summary>
|
||||
[Fact]
|
||||
public void Manifest_with_absurd_iterations_is_rejected_on_read()
|
||||
{
|
||||
var json = """
|
||||
{"algorithm":"AES-256-GCM","kdf":"PBKDF2-SHA256","iterations":2147483647,"saltB64":"","ivB64":""}
|
||||
""";
|
||||
Assert.ThrowsAny<Exception>(() =>
|
||||
System.Text.Json.JsonSerializer.Deserialize<EncryptionMetadata>(
|
||||
json, ZB.MOM.WW.ScadaBridge.Transport.Serialization.BundleJsonOptions.Default));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -534,12 +534,15 @@ public sealed class ArtifactDiffTests
|
||||
Assert.Equal("MxAccess", change.GetProperty("newValue").GetString());
|
||||
}
|
||||
|
||||
/// <summary>Verifies that a changed secret value with preserved presence is reported without echoing the secret.</summary>
|
||||
/// <summary>
|
||||
/// TRN-2: a changed secret value with preserved presence classifies Modified (it used to
|
||||
/// read Identical and be force-skipped) and is reported as a value-free marker.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void CompareDataConnection_SecretValueChangesButPresencePreserved_NoSecretEcho()
|
||||
public void CompareDataConnection_SecretValueChangesButPresencePreserved_ModifiedWithoutSecretEcho()
|
||||
{
|
||||
// Both sides HAVE a primary configuration secret; only the value differs.
|
||||
// Presence-only comparison => no Secrets.* change, and the value is never echoed.
|
||||
// Compared by hash => a value-free "<changed>" marker; the value is never echoed.
|
||||
var existing = new DataConnection("opc1", "OpcUa", siteId: 1)
|
||||
{
|
||||
FailoverRetryCount = 3,
|
||||
@@ -553,10 +556,79 @@ public sealed class ArtifactDiffTests
|
||||
|
||||
var item = _diff.CompareDataConnection(dto, existing);
|
||||
|
||||
Assert.Equal(ConflictKind.Identical, item.Kind);
|
||||
Assert.Null(item.FieldDiffJson);
|
||||
Assert.Equal(ConflictKind.Modified, item.Kind);
|
||||
var change = ChangeFor(item, "Secrets.PrimaryConfiguration");
|
||||
Assert.Equal("<present>", change.GetProperty("oldValue").GetString());
|
||||
Assert.Equal("<changed>", change.GetProperty("newValue").GetString());
|
||||
// The secret value must never appear anywhere in the diff output.
|
||||
Assert.DoesNotContain("4840", item.FieldDiffJson ?? string.Empty);
|
||||
Assert.DoesNotContain("4840", item.FieldDiffJson!);
|
||||
Assert.DoesNotContain("OLD", item.FieldDiffJson!);
|
||||
Assert.DoesNotContain("NEW", item.FieldDiffJson!);
|
||||
}
|
||||
|
||||
/// <summary>TRN-2: an unchanged secret value (same on both sides) stays Identical.</summary>
|
||||
[Fact]
|
||||
public void CompareDataConnection_SameSecretValue_Identical()
|
||||
{
|
||||
var existing = new DataConnection("opc1", "OpcUa", siteId: 1)
|
||||
{
|
||||
FailoverRetryCount = 3,
|
||||
PrimaryConfiguration = "{\"endpoint\":\"opc.tcp://h:4840\"}",
|
||||
};
|
||||
var dto = new DataConnectionDto("site-a", "opc1", "OpcUa", 3,
|
||||
new SecretsBlock(new Dictionary<string, string>
|
||||
{
|
||||
["PrimaryConfiguration"] = "{\"endpoint\":\"opc.tcp://h:4840\"}",
|
||||
}));
|
||||
|
||||
var item = _diff.CompareDataConnection(dto, existing);
|
||||
|
||||
Assert.Equal(ConflictKind.Identical, item.Kind);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// TRN-2 scenario B: when only FailoverRetryCount differs on the surface but the
|
||||
/// protocol configuration also changed, the diff shows the configuration change too,
|
||||
/// so an Overwrite no longer replaces it unseen.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void CompareDataConnection_RetryCountAndHiddenConfigChange_BothReported()
|
||||
{
|
||||
var existing = new DataConnection("opc1", "OpcUa", siteId: 1)
|
||||
{
|
||||
FailoverRetryCount = 3,
|
||||
PrimaryConfiguration = "{\"endpoint\":\"opc.tcp://target:4840\"}",
|
||||
};
|
||||
var dto = new DataConnectionDto("site-a", "opc1", "OpcUa", 5,
|
||||
new SecretsBlock(new Dictionary<string, string>
|
||||
{
|
||||
["PrimaryConfiguration"] = "{\"endpoint\":\"opc.tcp://source:4840\"}",
|
||||
}));
|
||||
|
||||
var item = _diff.CompareDataConnection(dto, existing);
|
||||
|
||||
Assert.Equal(ConflictKind.Modified, item.Kind);
|
||||
ChangeFor(item, "FailoverRetryCount");
|
||||
Assert.Equal("<changed>", ChangeFor(item, "Secrets.PrimaryConfiguration").GetProperty("newValue").GetString());
|
||||
Assert.DoesNotContain("source", item.FieldDiffJson!);
|
||||
}
|
||||
|
||||
/// <summary>TRN-2: external-system auth, DB connection string and SMTP credentials changes are Modified, value-free.</summary>
|
||||
[Fact]
|
||||
public void CompareOtherSecretBearingTypes_ChangedValue_ModifiedWithoutEcho()
|
||||
{
|
||||
var es = _diff.CompareExternalSystem(
|
||||
new ExternalSystemDto("Erp", "https://erp", "ApiKey",
|
||||
MaxRetries: 3, RetryDelay: TimeSpan.FromSeconds(5), Methods: [],
|
||||
Secrets: new SecretsBlock(new Dictionary<string, string> { ["AuthConfiguration"] = "key-NEW" })),
|
||||
new ExternalSystemDefinition("Erp", "https://erp", "ApiKey")
|
||||
{
|
||||
MaxRetries = 3, RetryDelay = TimeSpan.FromSeconds(5), AuthConfiguration = "key-OLD",
|
||||
},
|
||||
existingMethods: null);
|
||||
Assert.Equal(ConflictKind.Modified, es.Kind);
|
||||
Assert.Equal("<changed>", ChangeFor(es, "Secrets.AuthConfiguration").GetProperty("newValue").GetString());
|
||||
Assert.DoesNotContain("key-", es.FieldDiffJson!);
|
||||
}
|
||||
|
||||
/// <summary>Verifies that a flip in secret presence is shown only as a present marker, without the secret value.</summary>
|
||||
@@ -607,11 +679,14 @@ public sealed class ArtifactDiffTests
|
||||
Assert.Equal("AC1", item.Name);
|
||||
}
|
||||
|
||||
/// <summary>Verifies that an SMS configuration whose fields and secret presence all match compares as identical.</summary>
|
||||
/// <summary>Verifies that an SMS configuration whose fields and secret value all match compares as identical.</summary>
|
||||
[Fact]
|
||||
public void CompareSmsConfiguration_AllFieldsAndPresenceMatch_Identical()
|
||||
public void CompareSmsConfiguration_AllFieldsAndSecretMatch_Identical()
|
||||
{
|
||||
var item = _diff.CompareSmsConfiguration(SmsDto(), ExistingSms());
|
||||
// TRN-2: secrets are compared by value (hash), so the token must match too.
|
||||
var existing = ExistingSms();
|
||||
existing.AuthToken = "wire-token";
|
||||
var item = _diff.CompareSmsConfiguration(SmsDto(), existing);
|
||||
|
||||
Assert.Equal(ConflictKind.Identical, item.Kind);
|
||||
Assert.Null(item.FieldDiffJson);
|
||||
@@ -629,15 +704,16 @@ public sealed class ArtifactDiffTests
|
||||
Assert.Equal("+15559999999", change.GetProperty("newValue").GetString());
|
||||
}
|
||||
|
||||
/// <summary>Verifies that a changed auth token value with preserved presence is reported without echoing the secret.</summary>
|
||||
/// <summary>TRN-2: a changed auth token value with preserved presence is Modified, without echoing the secret.</summary>
|
||||
[Fact]
|
||||
public void CompareSmsConfiguration_AuthTokenValueChangesButPresencePreserved_NoSecretEcho()
|
||||
public void CompareSmsConfiguration_AuthTokenValueChangesButPresencePreserved_ModifiedWithoutSecretEcho()
|
||||
{
|
||||
// Both sides carry a token; only the value differs. Presence-only comparison =>
|
||||
// no Secrets.AuthToken change, and neither token value is ever echoed.
|
||||
// Both sides carry a token; only the value differs. Compared by hash =>
|
||||
// a value-free "<changed>" marker, and neither token value is ever echoed.
|
||||
var item = _diff.CompareSmsConfiguration(SmsDto(withSecret: true), ExistingSms());
|
||||
|
||||
Assert.Equal(ConflictKind.Identical, item.Kind);
|
||||
Assert.Equal(ConflictKind.Modified, item.Kind);
|
||||
Assert.Equal("<changed>", ChangeFor(item, "Secrets.AuthToken").GetProperty("newValue").GetString());
|
||||
var json = item.FieldDiffJson ?? string.Empty;
|
||||
Assert.DoesNotContain("stored-token", json);
|
||||
Assert.DoesNotContain("wire-token", json);
|
||||
@@ -672,19 +748,62 @@ public sealed class ArtifactDiffTests
|
||||
Assert.Equal("inst-1", item.Name);
|
||||
}
|
||||
|
||||
/// <summary>Verifies that an instance with a differing state compares as modified.</summary>
|
||||
/// <summary>
|
||||
/// TRN-6: State is not compared — the import never carries a live state, so a
|
||||
/// State-only difference must not read Modified (an Overwrite would then reset a live
|
||||
/// instance to NotDeployed for no configuration change).
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void CompareInstance_StateDiffers_Modified()
|
||||
public void CompareInstance_StateOnlyDiffers_Identical()
|
||||
{
|
||||
var existing = new Instance("inst-1") { State = InstanceState.Disabled };
|
||||
var dto = MakeInstanceDto("inst-1", state: InstanceState.Enabled);
|
||||
var existing = new Instance("inst-1") { State = InstanceState.Enabled };
|
||||
var dto = MakeInstanceDto("inst-1", state: InstanceState.Disabled);
|
||||
|
||||
var item = _diff.CompareInstance(dto, existing);
|
||||
|
||||
Assert.Equal(ConflictKind.Identical, item.Kind);
|
||||
}
|
||||
|
||||
/// <summary>TRN-6: a binding moved to another connection (same attribute + reference) is Modified.</summary>
|
||||
[Fact]
|
||||
public void CompareInstance_BindingRebindToOtherConnection_Modified()
|
||||
{
|
||||
var existing = new Instance("inst-1") { State = InstanceState.Enabled };
|
||||
existing.ConnectionBindings.Add(new InstanceConnectionBinding("Flow")
|
||||
{
|
||||
DataConnectionId = 10,
|
||||
DataSourceReferenceOverride = "ns=2;s=Flow",
|
||||
});
|
||||
var dto = MakeInstanceDto("inst-1") with
|
||||
{
|
||||
ConnectionBindings = [new InstanceConnectionBindingDto("Flow", "OPC2", "ns=2;s=Flow")],
|
||||
};
|
||||
var names = new Dictionary<int, string> { [10] = "OPC1", [11] = "OPC2" };
|
||||
|
||||
var item = _diff.CompareInstance(dto, existing, existingConnectionNameById: names);
|
||||
|
||||
Assert.Equal(ConflictKind.Modified, item.Kind);
|
||||
var change = ChangeFor(item, "State");
|
||||
Assert.Equal("Disabled", change.GetProperty("oldValue").GetString());
|
||||
Assert.Equal("Enabled", change.GetProperty("newValue").GetString());
|
||||
|
||||
// Same connection (case-insensitively) => Identical.
|
||||
var same = _diff.CompareInstance(
|
||||
dto with { ConnectionBindings = [new InstanceConnectionBindingDto("Flow", "opc1", "ns=2;s=Flow")] },
|
||||
existing, existingConnectionNameById: names);
|
||||
Assert.Equal(ConflictKind.Identical, same.Kind);
|
||||
}
|
||||
|
||||
/// <summary>TRN-8: with an incoming area path the full path is compared, not the leaf name.</summary>
|
||||
[Fact]
|
||||
public void CompareInstance_SameLeafDifferentAreaPath_Modified()
|
||||
{
|
||||
var existing = new Instance("inst-1") { State = InstanceState.Enabled, AreaId = 5 };
|
||||
var dto = MakeInstanceDto("inst-1") with { AreaName = "Cell", AreaPath = ["Line2", "Cell"] };
|
||||
|
||||
var item = _diff.CompareInstance(dto, existing, existingAreaName: "Cell", existingAreaPath: ["Line1", "Cell"]);
|
||||
|
||||
Assert.Equal(ConflictKind.Modified, item.Kind);
|
||||
var change = ChangeFor(item, "AreaPath");
|
||||
Assert.Equal("Line1/Cell", change.GetProperty("oldValue").GetString());
|
||||
Assert.Equal("Line2/Cell", change.GetProperty("newValue").GetString());
|
||||
}
|
||||
|
||||
/// <summary>Verifies that an instance with no changes compares as identical.</summary>
|
||||
|
||||
Reference in New Issue
Block a user