using System.Data.Common;
using System.Reflection;
using Bunit;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.Extensions.DependencyInjection;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.AdminUI.Deployments;
using ZB.MOM.WW.OtOpcUa.Commons.Interfaces;
using ZB.MOM.WW.OtOpcUa.Configuration;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
using DeploymentPage = ZB.MOM.WW.OtOpcUa.AdminUI.Components.Pages.Deployments;
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.Pages;
/// Real-provider page reads stay bounded and exclude whole-fleet artifact payloads.
[Collection(nameof(AdminUiSqlServerCollection))]
public sealed class DeploymentPageSqlServerTests(AdminUiSqlServerFixture sql) : BunitContext
{
[SqlServerFact]
public async Task HistoryRead_IsTranslatedBoundedAndDoesNotSelectArtifactBlobs()
{
var ids=Enumerable.Range(0,60).Select(_=>Guid.NewGuid()).ToArray();
try
{
await using(var db=await sql.Factory.CreateDbContextAsync(Xunit.TestContext.Current.CancellationToken))
{
db.Deployments.AddRange(ids.Select((id,i)=>new Deployment {
DeploymentId=id,RevisionHash=new string('a',64),CreatedBy="isolated-ui-fixture",
Status=DeploymentStatus.Dispatching,CreatedAtUtc=new DateTime(4000,1,1,0,0,0,DateTimeKind.Utc).AddSeconds(i),
ArtifactBlob=new byte[64*1024] }));
await db.SaveChangesAsync(Xunit.TestContext.Current.CancellationToken);
}
var commands=new ReadCommands();
var options=new DbContextOptionsBuilder().UseSqlServer(sql.ConnectionString).AddInterceptors(commands).Options;
var factory=new SqlFactory(options);
AddAuthorization().SetAuthorized("isolated-fixture");
Services.AddSingleton>(factory);
Services.AddSingleton(new DeploymentDriftProbe(factory,_=>Task.FromResult(new string('a',64))));
Services.AddSingleton(DispatchProxy.Create());
var cut=Render();
cut.WaitForAssertion(()=>cut.FindAll("tbody tr").Count.ShouldBe(50),TimeSpan.FromSeconds(10));
commands.Text.ShouldNotBeEmpty();
string.Join("\n",commands.Text).ShouldNotContain("ArtifactBlob");
}
finally
{
await using var cleanup=await sql.Factory.CreateDbContextAsync(Xunit.TestContext.Current.CancellationToken);
await cleanup.Deployments.Where(d=>ids.Contains(d.DeploymentId)).ExecuteDeleteAsync(Xunit.TestContext.Current.CancellationToken);
}
}
private sealed class SqlFactory(DbContextOptions options) : IDbContextFactory
{
public OtOpcUaConfigDbContext CreateDbContext()=>new(options);
public Task CreateDbContextAsync(CancellationToken ct=default)=>Task.FromResult(CreateDbContext());
}
private sealed class ReadCommands : DbCommandInterceptor
{
public List Text {get;}=[];
public override ValueTask> ReaderExecutingAsync(DbCommand command,CommandEventData eventData,InterceptionResult result,CancellationToken cancellationToken=default)
{Text.Add(command.CommandText);return ValueTask.FromResult(result);}
}
}