Files
ScadaBridge/tests/ZB.MOM.WW.ScadaBridge.Transport.IntegrationTests/Import/NotificationListOverwriteTests.cs
T
Joseph Doherty f42c17d2ce fix(transport): notification-list Overwrite replaces recipients instead of appending (TRN-1, WP2 task 2.1)
GetListByNameAsync now eager-loads Recipients, so the importer's Overwrite
Clear() removes the target's rows before the bundle's are re-added. Fixed in
the repository method (decision 2.1) so every caller gets the recipients.
Regression: target {A,B} + bundle {A,C} -> {A,C}, stable on re-import.
2026-12-03 09:38:41 -05:00

174 lines
8.0 KiB
C#

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();
}
}