fix(transport): import diff compares secrets and bindings; preview honours the name map; CI lookups; area paths; no Rename where unsupported (TRN-2, TRN-3, TRN-6, TRN-7, TRN-8, TRN-9, WP2 tasks 2.4+2.5)

2.4 — ArtifactDiff:
- TRN-2: secret-bearing values (data-connection primary/backup config, DB
  connection string, external-system auth, SMTP credentials, SMS token) are
  compared by SHA-256 and reported value-free as <present> -> <changed>, so a
  changed endpoint no longer reads Identical and is force-skipped.
- TRN-6: the instance diff resolves each existing binding's DataConnectionId to
  its name and compares it (a rebind OPC1 -> OPC2 is Modified); State is no
  longer compared (the import never carries a live state).

2.5 — BundleImporter / ManagementActor / Central UI:
- TRN-3: PreviewAsync takes an optional BundleNameMap (additive optional param);
  under a MapToExisting redirect the connection/instance diffs, connection
  auto-match and unresolved-connection blocker run against the mapped target.
  The CLI import path passes its explicit --map-site/--map-connection redirects
  to the preview before the blocker gate; the Central UI re-runs the preview
  under the Map-step choices at Confirm. Apply binds a CreateNew site/connection
  whose identifier/name already exists to that row instead of inserting a
  duplicate the unique index rejects.
- TRN-7: connection, instance, instance-template and composition/base-template
  lookups match exact spelling first, then case-insensitively.
- TRN-8: InstanceDto gains the additive AreaPath (root->leaf); the exporter
  fills it and the importer resolves/creates areas level by level under their
  real parent. A legacy leaf-only bundle with an ambiguous leaf resolves
  deterministically and adds an ImportResult warning.
- TRN-9: Rename is rejected by ApplyAsync for Site, DataConnection,
  SmtpConfiguration and SmsConfiguration (ImportRenameSupport); the UI does not
  offer it there and the CLI rename policy falls back to Skip with a warning.

Also moves a doc comment misplaced by the 2.6 commit. Reflection round-trip
guard (RoundTripEquivalenceTests) re-run: green.
This commit is contained in:
Joseph Doherty
2026-12-03 10:11:07 -05:00
parent cbdd9fc40b
commit baecf10fea
16 changed files with 1391 additions and 169 deletions
@@ -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;
}
@@ -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 />
@@ -4426,7 +4426,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>(),
@@ -4449,6 +4450,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,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);
}
}
@@ -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>