using System.Collections.Concurrent; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using ZB.MOM.WW.ScadaBridge.Commons.Entities.ExternalSystems; using ZB.MOM.WW.ScadaBridge.Commons.Entities.InboundApi; using ZB.MOM.WW.ScadaBridge.Commons.Entities.Notifications; 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; using ZB.MOM.WW.ScadaBridge.Transport.Import; namespace ZB.MOM.WW.ScadaBridge.Transport.IntegrationTests.Import; /// /// ScadaBridge#93: preview looked database connections, notification lists and API /// methods up one name at a time, and re-keyed template by-name results with an /// ordinal comparer although SQL Server matches names case-insensitively. /// public sealed class ImportNameLookupTests : IDisposable { private readonly ServiceProvider _provider; private readonly ConcurrentDictionary _calls = new(StringComparer.Ordinal); /// Initializes the test class with counting repositories over an in-memory database. public ImportNameLookupTests() { var services = new ServiceCollection(); services.AddSingleton( new Microsoft.AspNetCore.DataProtection.EphemeralDataProtectionProvider()); services.AddSingleton(new ConfigurationBuilder().AddInMemoryCollection().Build()); var dbName = $"ImportNameLookupTests_{Guid.NewGuid()}"; services.AddDbContext(opts => opts .UseInMemoryDatabase(dbName) .ConfigureWarnings(w => w.Ignore(InMemoryEventId.TransactionIgnoredWarning))); services.AddSingleton(); services.AddScoped(); services.AddScoped(sp => ImportRoundTripBudgetTests.CountingProxy.Wrap( new ExternalSystemRepository(sp.GetRequiredService()), _calls)); services.AddScoped(sp => ImportRoundTripBudgetTests.CountingProxy.Wrap( new NotificationRepository(sp.GetRequiredService()), _calls)); services.AddScoped(sp => ImportRoundTripBudgetTests.CountingProxy.Wrap( new InboundApiRepository(sp.GetRequiredService()), _calls)); services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddTransport(); _provider = services.BuildServiceProvider(); } /// Releases the resources used by this instance. public void Dispose() => _provider.Dispose(); private int Calls(string method) => _calls.TryGetValue(method, out var n) ? n : 0; /// /// Preview of a bundle with several database connections, notification lists and /// API methods must read each library once (no per-name query) and must match the /// target's rows case-insensitively, as SQL Server's collation does. /// /// A task that represents the asynchronous operation. [Fact] public async Task Preview_batches_name_lookups_and_matches_case_insensitively() { await using (var scope = _provider.CreateAsyncScope()) { var ctx = scope.ServiceProvider.GetRequiredService(); for (var i = 0; i < 4; i++) { ctx.DatabaseConnectionDefinitions.Add(new DatabaseConnectionDefinition($"db-{i}", "Server=s;Database=d;")); ctx.NotificationLists.Add(new NotificationList($"list-{i}")); ctx.ApiMethods.Add(new ApiMethod($"Method{i}", "return 1;")); } await ctx.SaveChangesAsync(); } Stream bundle; await using (var scope = _provider.CreateAsyncScope()) { var ctx = scope.ServiceProvider.GetRequiredService(); bundle = await scope.ServiceProvider.GetRequiredService().ExportAsync( new ExportSelection( TemplateIds: Array.Empty(), SharedScriptIds: Array.Empty(), ExternalSystemIds: Array.Empty(), DatabaseConnectionIds: await ctx.DatabaseConnectionDefinitions.Select(x => x.Id).ToListAsync(), NotificationListIds: await ctx.NotificationLists.Select(x => x.Id).ToListAsync(), SmtpConfigurationIds: Array.Empty(), ApiMethodIds: await ctx.ApiMethods.Select(x => x.Id).ToListAsync(), IncludeDependencies: false), user: "alice", sourceEnvironment: "dev", passphrase: null, cancellationToken: CancellationToken.None); } Guid sessionId; await using (var scope = _provider.CreateAsyncScope()) { sessionId = (await scope.ServiceProvider.GetRequiredService() .LoadAsync(bundle, passphrase: null)).SessionId; } // The target environment spells two of the names with different casing; the // production collation treats them as the SAME row. await using (var scope = _provider.CreateAsyncScope()) { var ctx = scope.ServiceProvider.GetRequiredService(); (await ctx.DatabaseConnectionDefinitions.SingleAsync(x => x.Name == "db-1")).Name = "DB-1"; (await ctx.NotificationLists.SingleAsync(x => x.Name == "list-2")).Name = "LIST-2"; (await ctx.ApiMethods.SingleAsync(x => x.Name == "Method3")).Name = "METHOD3"; await ctx.SaveChangesAsync(); } _calls.Clear(); ImportPreview preview; await using (var scope = _provider.CreateAsyncScope()) { preview = await scope.ServiceProvider.GetRequiredService().PreviewAsync(sessionId); } Assert.Equal(0, Calls(nameof(IExternalSystemRepository.GetDatabaseConnectionByNameAsync))); Assert.Equal(0, Calls(nameof(INotificationRepository.GetListByNameAsync))); Assert.Equal(0, Calls(nameof(IInboundApiRepository.GetMethodByNameAsync))); Assert.Equal(1, Calls(nameof(IExternalSystemRepository.GetAllDatabaseConnectionsAsync))); Assert.Equal(1, Calls(nameof(INotificationRepository.GetAllNotificationListsAsync))); Assert.Equal(1, Calls(nameof(IInboundApiRepository.GetAllApiMethodsAsync))); foreach (var item in preview.Items.Where(i => i.EntityType is "DatabaseConnection" or "NotificationList" or "ApiMethod")) { Assert.NotEqual(ConflictKind.New, item.Kind); } Assert.Equal(12, preview.Items.Count(i => i.EntityType is "DatabaseConnection" or "NotificationList" or "ApiMethod")); } /// /// Two rows whose names differ only in case (possible for derived templates, which /// the filtered unique index on Name does not cover) must not throw, and a base /// template wins over a derived one. /// [Fact] public void Template_lookup_tolerates_names_differing_only_in_case() { var derived = new Template("Pump") { Id = 1, IsDerived = true }; var other = new Template("pump") { Id = 2, IsDerived = true }; var baseT = new Template("PUMP") { Id = 3, IsDerived = false }; var lookup = BundleImporter.ToTemplateLookup(new[] { derived, other, baseT }); Assert.Single(lookup); Assert.Same(baseT, lookup["pump"]); var onlyDerived = BundleImporter.ToTemplateLookup(new[] { derived, other }); Assert.Same(derived, onlyDerived["PUMP"]); } /// A lookup built from by-name rows never throws on duplicate case variants. [Fact] public void Name_lookup_is_case_insensitive_and_first_wins() { var a = new NotificationList("List"); var b = new NotificationList("LIST"); var lookup = BundleImporter.ToNameLookup(new[] { a, b }, x => x.Name); Assert.Same(a, lookup["list"]); } }