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; /// /// TRN-1 (WP2 task 2.1): a notification-list Overwrite must REPLACE the target's /// recipients with the bundle's. GetListByNameAsync used to load the list /// without its recipients, so the apply's Recipients.Clear() 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. /// public sealed class NotificationListOverwriteTests : IDisposable { private readonly ServiceProvider _provider; /// Builds an in-memory configuration database plus the Transport services. public NotificationListOverwriteTests() { var services = new ServiceCollection(); services.AddSingleton(new ConfigurationBuilder().AddInMemoryCollection().Build()); var dbName = $"NotificationListOverwriteTests_{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(); /// /// 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}. /// /// A task that represents the asynchronous operation. [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(); 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(); 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()); } /// /// The repository method itself must return the list with its recipients — every /// caller (importer, delivery adapters) relies on the navigation being populated. /// /// A task that represents the asynchronous operation. [Fact] public async Task GetListByNameAsync_loads_recipients() { await using (var scope = _provider.CreateAsyncScope()) { var ctx = scope.ServiceProvider.GetRequiredService(); 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(); var loaded = await repo.GetListByNameAsync("Ops"); Assert.NotNull(loaded); Assert.Single(loaded!.Recipients); } } private async Task ExportAsync() { await using var scope = _provider.CreateAsyncScope(); var exporter = scope.ServiceProvider.GetRequiredService(); var ctx = scope.ServiceProvider.GetRequiredService(); var listIds = await ctx.NotificationLists.Select(l => l.Id).ToListAsync(); var selection = new ExportSelection( TemplateIds: Array.Empty(), SharedScriptIds: Array.Empty(), ExternalSystemIds: Array.Empty(), DatabaseConnectionIds: Array.Empty(), NotificationListIds: listIds, 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 ImportOverwriteAsync(byte[] bundle) { Guid sessionId; await using (var scope = _provider.CreateAsyncScope()) { var importer = scope.ServiceProvider.GetRequiredService(); 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(); var result = await importer.ApplyAsync(sessionId, new List { new("NotificationList", "Ops", ResolutionAction.Overwrite, null) }, user: "bob"); Assert.Equal(1, result.Overwritten); } } private async Task RecipientNamesAsync() { await using var scope = _provider.CreateAsyncScope(); var ctx = scope.ServiceProvider.GetRequiredService(); 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(); } }