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; /// /// 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). /// public sealed class ImportMappingAndIdentityTests : IDisposable { private readonly ServiceProvider _provider; /// Builds an in-memory configuration database plus the Transport services. public ImportMappingAndIdentityTests() { var services = new ServiceCollection(); services.AddSingleton( new Microsoft.AspNetCore.DataProtection.EphemeralDataProtectionProvider()); services.AddSingleton(new ConfigurationBuilder().AddInMemoryCollection().Build()); var dbName = $"ImportMappingAndIdentityTests_{Guid.NewGuid()}"; services.AddDbContext(opts => opts .UseInMemoryDatabase(dbName) .ConfigureWarnings(w => w.Ignore(InMemoryEventId.TransactionIgnoredWarning))); services.AddSingleton(); services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddTransport(); _provider = services.BuildServiceProvider(); } /// Releases the resources held by this instance. public void Dispose() => _provider.Dispose(); // ── TRN-2 / TRN-6 (task 2.4) ───────────────────────────────────────────── /// TRN-2: a target whose connection endpoint changed previews Modified, never echoing the config. /// A task that represents the asynchronous operation. [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("", change.GetProperty("newValue").GetString()); Assert.DoesNotContain("source-host", item.FieldDiffJson); Assert.DoesNotContain("target-host", item.FieldDiffJson); } /// TRN-6: rebinding an attribute to another connection previews Modified; a State-only change is Identical. /// A task that represents the asynchronous operation. [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) ───────────────────────────────────────────────────── /// /// 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. /// /// A task that represents the asynchronous operation. [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()); 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(); 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); } /// /// 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. /// /// A task that represents the asynchronous operation. [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 { ["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(); var conn = await ctx.DataConnections.SingleAsync(); Assert.Equal("{\"endpoint\":\"target\"}", conn.PrimaryConfiguration); } // ── TRN-7 (task 2.5) ───────────────────────────────────────────────────── /// /// 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.) /// /// A task that represents the asynchronous operation. [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 { ["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(); var conn = await ctx.DataConnections.SingleAsync(); var instance = await ctx.Instances.Include(i => i.ConnectionBindings).SingleAsync(); Assert.Equal(conn.Id, instance.ConnectionBindings.Single().DataConnectionId); } /// /// 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. /// /// A task that represents the asynchronous operation. [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(); 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) ───────────────────────────────────────────────────── /// TRN-8: an instance in Line2/Cell lands in Line2/Cell, not whichever 'Cell' comes back first. /// A task that represents the asynchronous operation. [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(); Assert.Equal(line2Cell, (await ctx.Instances.SingleAsync()).AreaId); Assert.Equal(4, await ctx.Areas.CountAsync()); // Line1, Line2 and both Cells — nothing created } /// TRN-8: a missing nested area is created under its real parent, not at the site root. /// A task that represents the asynchronous operation. [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(); 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); } /// TRN-8: a legacy (path-less) bundle with an ambiguous leaf name warns instead of guessing silently. /// A task that represents the asynchronous operation. [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) ───────────────────────────────────────────────────── /// TRN-9: Rename is rejected for sites, data connections, SMTP and SMS configurations. /// The resolution's entity type. /// A task that represents the asynchronous operation. [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(() => 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 mutate) { await using var scope = _provider.CreateAsyncScope(); var ctx = scope.ServiceProvider.GetRequiredService(); 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 AnyTemplateAsync() { await using var scope = _provider.CreateAsyncScope(); return await scope.ServiceProvider.GetRequiredService().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(); 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? bindings = null) => new(name, "Pump", site, AreaName: null, InstanceState.NotDeployed, Array.Empty(), Array.Empty(), Array.Empty(), bindings ?? Array.Empty()); private static BundleContentDto Content( IReadOnlyList? sites = null, IReadOnlyList? connections = null, IReadOnlyList? instances = null) => new( TemplateFolders: Array.Empty(), Templates: Array.Empty(), SharedScripts: Array.Empty(), ExternalSystems: Array.Empty(), DatabaseConnections: Array.Empty(), NotificationLists: Array.Empty(), SmtpConfigs: Array.Empty(), ApiMethods: Array.Empty()) { Sites = sites ?? Array.Empty(), DataConnections = connections ?? Array.Empty(), Instances = instances ?? Array.Empty(), }; private async Task PackAndLoadAsync(BundleContentDto content) { await using var scope = _provider.CreateAsyncScope(); var manifestBuilder = scope.ServiceProvider.GetRequiredService(); var serializer = scope.ServiceProvider.GetRequiredService(); var importer = scope.ServiceProvider.GetRequiredService(); 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(), 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 ExportSitesAndLoadAsync() { byte[] bytes; await using (var scope = _provider.CreateAsyncScope()) { var exporter = scope.ServiceProvider.GetRequiredService(); var ctx = scope.ServiceProvider.GetRequiredService(); var selection = new ExportSelection( TemplateIds: Array.Empty(), SharedScriptIds: Array.Empty(), ExternalSystemIds: Array.Empty(), DatabaseConnectionIds: Array.Empty(), NotificationListIds: Array.Empty(), SmtpConfigurationIds: Array.Empty(), ApiMethodIds: Array.Empty(), 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 ExportTemplatesAsync() { await using var scope = _provider.CreateAsyncScope(); var exporter = scope.ServiceProvider.GetRequiredService(); var ctx = scope.ServiceProvider.GetRequiredService(); var selection = new ExportSelection( TemplateIds: await ctx.Templates.Select(t => t.Id).ToListAsync(), SharedScriptIds: Array.Empty(), ExternalSystemIds: Array.Empty(), DatabaseConnectionIds: Array.Empty(), NotificationListIds: Array.Empty(), SmtpConfigurationIds: Array.Empty(), ApiMethodIds: Array.Empty(), 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 LoadAsync(byte[] bundle) { await using var scope = _provider.CreateAsyncScope(); using var ms = new MemoryStream(bundle, writable: false); return (await scope.ServiceProvider.GetRequiredService().LoadAsync(ms, passphrase: null)).SessionId; } private async Task PreviewAsync(Guid sessionId, BundleNameMap? map = null) { await using var scope = _provider.CreateAsyncScope(); return await scope.ServiceProvider.GetRequiredService().PreviewAsync(sessionId, CancellationToken.None, map); } private async Task ApplyAsync(Guid sessionId, IReadOnlyList resolutions, BundleNameMap map) { await using var scope = _provider.CreateAsyncScope(); return await scope.ServiceProvider.GetRequiredService() .ApplyAsync(sessionId, resolutions, user: "bob", ct: CancellationToken.None, nameMap: map); } }