using System.Reflection;
using Bunit;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Components.Authorization;
using System.Security.Claims;
using Microsoft.Extensions.DependencyInjection;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.AdminUI.Deployments;
using ZB.MOM.WW.OtOpcUa.AdminUI.Tests.Uns;
using ZB.MOM.WW.OtOpcUa.Commons.Interfaces;
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Admin;
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;
/// Manual deployment status reads and request replies retain their independent meanings.
[Trait("Category","Unit")]
public sealed class DeploymentRefreshTests : BunitContext
{
private readonly string _database = "deployment-ui-"+Guid.NewGuid().ToString("N");
private ControlledFactory Configure(bool seed=true)
{
AddAuthorization().SetAuthorized("fixture");
if (seed)
{
using var db=RawTreeTestDb.CreateNamed(_database);
db.Deployments.Add(new Deployment { DeploymentId=Guid.Parse("4ffec608-caa6-47f4-a9ca-71815c791648"), RevisionHash=new string('a',64), CreatedBy="fixture", Status=DeploymentStatus.AwaitingApplyAcks });
db.SaveChanges();
}
var factory=new ControlledFactory(_database);
Services.AddSingleton>(factory);
Services.AddSingleton(new DeploymentDriftProbe(factory,_=>Task.FromResult(new string('a',64))));
Services.AddSingleton(DispatchProxy.Create());
return factory;
}
private RequestProxy Request => (RequestProxy)Services.GetRequiredService();
[Fact]
public void ManualRefresh_ObservesLaterApplicationStatusWithoutReloadingPage()
{
Configure();var cut=Render();
using (var db=RawTreeTestDb.CreateNamed(_database)) { var row=db.Deployments.Single();row.Status=DeploymentStatus.Sealed;row.SealedAtUtc=DateTime.UtcNow;db.SaveChanges(); }
cut.Find("[data-testid=deployment-refresh]").Click();
cut.WaitForAssertion(()=>cut.Find("[role=status]").TextContent.ShouldContain("Sealed"));
cut.Find("[data-testid=deployment-last-fetched]").TextContent.ShouldContain("UTC");
}
[Fact]
public void FailedInitialHistoryRead_DoesNotBecomeEmptyOrKillThePage()
{
var factory=Configure(false);factory.Read=_=>Task.FromException(new IOException("Synthetic read failure"));
var cut=Render();
cut.WaitForAssertion(()=>cut.Find("[role=status]").TextContent.ShouldContain("history is unavailable"));
cut.Find("[role=status]").TextContent.ShouldNotContain("No deployment history");
factory.Read=null;cut.Find("[data-testid=deployment-refresh]").Click();
cut.WaitForAssertion(()=>cut.Find("[role=status]").TextContent.ShouldContain("No deployment history"));
}
[Fact]
public void AcceptedRequest_RemainsAcceptedWhenFollowingHistoryReadFails()
{
var factory=Configure();var cut=Render();
Request.Start=()=> { factory.Read=_=>Task.FromException(new IOException("Synthetic follow-up read failure"));return Task.FromResult(new StartDeploymentResult(StartDeploymentOutcome.Accepted,new(Guid.NewGuid()),new(new string('b',64)),null,new(Guid.NewGuid()))); };
cut.Find("[data-testid=deployment-request]").Click();
cut.WaitForAssertion(()=>cut.Find("[role=status]").TextContent.ShouldContain("Request accepted"));
cut.Find("[role=status]").TextContent.ShouldContain("not yet observed");
cut.Markup.ShouldNotContain("Deploy failed");cut.FindAll("tbody tr").Count.ShouldBe(1);cut.Markup.ShouldContain(new string('b',64));
}
[Fact]
public async Task PendingRefresh_BlocksQueuedRefreshAndRequestReentry()
{
var factory=Configure();var cut=Render();
var entered=new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var pending=new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
factory.Read=_=>{entered.TrySetResult();return pending.Task;};
var refreshing=cut.Find("[data-testid=deployment-refresh]").TriggerEventAsync("onclick",new Microsoft.AspNetCore.Components.Web.MouseEventArgs());
await entered.Task.WaitAsync(TimeSpan.FromSeconds(10),Xunit.TestContext.Current.CancellationToken);
try
{
await cut.Find("[data-testid=deployment-refresh]").TriggerEventAsync("onclick",new Microsoft.AspNetCore.Components.Web.MouseEventArgs());
await cut.Find("[data-testid=deployment-request]").TriggerEventAsync("onclick",new Microsoft.AspNetCore.Components.Web.MouseEventArgs());
factory.Attempts.ShouldBe(2);Request.Calls.ShouldBe(0);
}
finally {factory.Read=null;pending.TrySetResult(RawTreeTestDb.CreateNamed(_database));await refreshing;}
}
[Fact]
public async Task PendingRequest_BlocksQueuedRequestsAndStatusRefresh()
{
var factory=Configure();var cut=Render();
var entered=new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var pending=new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
Request.Start=()=>{entered.TrySetResult();return pending.Task;};
var submitting=cut.Find("[data-testid=deployment-request]").TriggerEventAsync("onclick",new Microsoft.AspNetCore.Components.Web.MouseEventArgs());
await entered.Task.WaitAsync(TimeSpan.FromSeconds(10),Xunit.TestContext.Current.CancellationToken);
try
{
await cut.Find("[data-testid=deployment-request]").TriggerEventAsync("onclick",new Microsoft.AspNetCore.Components.Web.MouseEventArgs());
await cut.Find("[data-testid=deployment-refresh]").TriggerEventAsync("onclick",new Microsoft.AspNetCore.Components.Web.MouseEventArgs());
Request.Calls.ShouldBe(1);factory.Attempts.ShouldBe(1);
}
finally { pending.TrySetResult(new StartDeploymentResult(StartDeploymentOutcome.NoChanges,null,null,null,new(Guid.NewGuid())));await submitting; }
cut.Find("[role=status]").TextContent.ShouldContain("No configuration changes");
}
[Fact]
public void MissingActorReply_IsUnconfirmedRatherThanRejected()
{
Configure();var cut=Render();Request.Start=()=>Task.FromException(new IOException("Synthetic unknown reply"));
cut.Find("[data-testid=deployment-request]").Click();
cut.WaitForAssertion(()=>cut.Find("[role=status]").TextContent.ShouldContain("could not be confirmed"));
cut.Find("[role=status]").TextContent.ShouldNotContain("Request rejected");
}
[Fact]
public async Task DelayedInitialHistory_ComposesDriftOnceAfterRowsBecomeAvailable()
{
var factory=Configure();
using (var db=RawTreeTestDb.CreateNamed(_database)) {db.Deployments.Single().Status=DeploymentStatus.Sealed;db.SaveChanges();}
var pending=new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
factory.Read=_=>pending.Task;
var compositions=0;
Services.AddSingleton(new DeploymentDriftProbe(factory,_=>{compositions++;return Task.FromResult(new string('a',64));}));
var cut=Render();
cut.Find("[role=status]").TextContent.ShouldContain("Loading deployment history");
compositions.ShouldBe(0);
factory.Read=null;pending.SetResult(RawTreeTestDb.CreateNamed(_database));
cut.WaitForAssertion(()=>cut.Find("[data-testid=drift-chip]").TextContent.ShouldBe("In sync"));
compositions.ShouldBe(1);
}
[Fact]
public void FailedRefresh_PreservesLastSuccessfulRowsAndFetchedTime()
{
var factory=Configure();var cut=Render();
var fetched=cut.Find("[data-testid=deployment-last-fetched]").GetAttribute("datetime");
factory.Read=_=>Task.FromException(new IOException("Synthetic stale read"));
cut.Find("[data-testid=deployment-refresh]").Click();
cut.WaitForAssertion(()=>cut.Find("[role=alert]").TextContent.ShouldContain("last successful reading"));
cut.Find("[data-testid=deployment-last-fetched]").GetAttribute("datetime").ShouldBe(fetched);
cut.FindAll("tbody tr").Count.ShouldBe(1);
cut.Find("[role=status]").TextContent.ShouldContain("Awaiting apply acknowledgements");
}
[Fact]
public async Task Disposal_CancelsOnlyTheViewOwnedHistoryRead()
{
var factory=Configure(false);
var canceled=new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var pending=new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
factory.Read=async ct=>
{
try {return await pending.Task.WaitAsync(ct);}
catch(OperationCanceledException) {canceled.TrySetResult();throw;}
};
var cut=Render();
cut.Find("[role=status]").TextContent.ShouldContain("Loading deployment history");
await DisposeComponentsAsync();
await canceled.Task.WaitAsync(TimeSpan.FromSeconds(10),Xunit.TestContext.Current.CancellationToken);
Renderer.UnhandledException.IsCompletedSuccessfully.ShouldBeFalse();
}
[Fact]
public async Task Disposal_DoesNotCancelOrReplayAnAlreadyDispatchedRequest()
{
var factory=Configure();var cut=Render();var client=Request;
var entered=new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var pending=new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var completed=false;
client.Start=async ()=>{entered.TrySetResult();var reply=await pending.Task;completed=true;return reply;};
var submitting=cut.Find("[data-testid=deployment-request]").TriggerEventAsync("onclick",new Microsoft.AspNetCore.Components.Web.MouseEventArgs());
await entered.Task.WaitAsync(TimeSpan.FromSeconds(10),Xunit.TestContext.Current.CancellationToken);
await DisposeComponentsAsync();
pending.SetResult(new StartDeploymentResult(StartDeploymentOutcome.Accepted,new(Guid.NewGuid()),new(new string('b',64)),null,new(Guid.NewGuid())));
await submitting;
completed.ShouldBeTrue();client.Calls.ShouldBe(1);client.LastToken.CanBeCanceled.ShouldBeFalse();factory.Attempts.ShouldBe(1);
}
[Fact]
public async Task DisposalDuringUsernameRead_DoesNotDispatchANewRequest()
{
Configure();
var state=new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
Services.AddSingleton(new DeferredState(state.Task));
var cut=Render();var client=Request;
var submitting=cut.Find("[data-testid=deployment-request]").TriggerEventAsync("onclick",new Microsoft.AspNetCore.Components.Web.MouseEventArgs());
await DisposeComponentsAsync();
state.SetResult(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.Name,"fixture")],"fixture"))));
await submitting;client.Calls.ShouldBe(0);
}
private sealed class DeferredState(Task state) : AuthenticationStateProvider
{public override Task GetAuthenticationStateAsync()=>state;}
public sealed class ControlledFactory(string name) : IDbContextFactory
{
public int Attempts {get;private set;}
public Func>? Read {get;set;}
public OtOpcUaConfigDbContext CreateDbContext()=>RawTreeTestDb.CreateNamed(name);
public Task CreateDbContextAsync(CancellationToken ct=default)
{Attempts++;return Read?.Invoke(ct)??Task.FromResult(CreateDbContext());}
}
public class RequestProxy : DispatchProxy
{
public int Calls {get;private set;}
public CancellationToken LastToken {get;private set;}
public Func> Start {get;set;}=()=>Task.FromException(new NotSupportedException("Synthetic operation not configured"));
protected override object? Invoke(MethodInfo? method,object?[]? args)
{
if(method?.Name!=nameof(IAdminOperationsClient.StartDeploymentAsync))throw new NotSupportedException("Synthetic fixture rejects other operations");
Calls++;LastToken=(CancellationToken)args![1]!;return Start();
}
}
}