320 lines
20 KiB
C#
320 lines
20 KiB
C#
using System.Reflection;
|
|
using System.Security.Claims;
|
|
using Bunit;
|
|
using Microsoft.AspNetCore.Authorization;
|
|
using Microsoft.AspNetCore.Components;
|
|
using Microsoft.AspNetCore.Components.Authorization;
|
|
using Microsoft.AspNetCore.Components.Web;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Shouldly;
|
|
using Xunit;
|
|
using ZB.MOM.WW.OtOpcUa.AdminUI.Components.Shared.Drivers;
|
|
using ZB.MOM.WW.OtOpcUa.AdminUI.Hubs;
|
|
using ZB.MOM.WW.OtOpcUa.Commons.Interfaces;
|
|
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Admin;
|
|
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Drivers;
|
|
|
|
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.Pages;
|
|
|
|
/// <summary>Driver operations and inline confirmation retain authorization and presentation identity.</summary>
|
|
[Trait("Category", "Unit")]
|
|
public sealed class DriverOperationConfirmationTests : BunitContext
|
|
{
|
|
private readonly ControlledAuth _auth = new();
|
|
private readonly ControlledAuthorization _authorization = new();
|
|
private readonly RecordingStatus _status = new();
|
|
private readonly RecordingResilience _resilience = new();
|
|
private readonly Operations _operations;
|
|
public DriverOperationConfirmationTests()
|
|
{
|
|
Services.AddSingleton<AuthenticationStateProvider>(_auth);
|
|
Services.AddSingleton<IAuthorizationService>(_authorization);
|
|
Services.AddSingleton<IDriverStatusSnapshotStore>(_status);
|
|
Services.AddSingleton<IDriverResilienceStatusStore>(_resilience);
|
|
var ops = DispatchProxy.Create<IAdminOperationsClient, Operations>();_operations = (Operations)(object)ops;Services.AddSingleton(ops);
|
|
JSInterop.SetupVoid("Blazor._internal.domWrapper.focus", _ => true).SetVoidResult();
|
|
}
|
|
private IRenderedComponent<DriverStatusPanel> Open() => Render<DriverStatusPanel>(p => p.Add(x => x.DriverInstanceId, "A").Add(x => x.ClusterId, "cluster-A"));
|
|
private static AngleSharp.Dom.IElement Button(IRenderedComponent<DriverStatusPanel> cut, string name) => cut.FindAll("button").Single(b => b.TextContent.Trim() == name);
|
|
private static Task Click(AngleSharp.Dom.IElement button) => button.TriggerEventAsync("onclick", new MouseEventArgs());
|
|
private void Busy(IRenderedComponent<DriverStatusPanel> cut, List<bool> received)
|
|
{
|
|
var property = typeof(DriverStatusPanel).GetProperty("BusyChanged");property.ShouldNotBeNull();
|
|
property.SetValue(cut.Instance, EventCallback.Factory.Create<bool>(this, value => received.Add(value)));
|
|
cut.Render();
|
|
}
|
|
private static AuthenticationState User(string name = "current-operator", bool allowed = true) => new(new ClaimsPrincipal(new ClaimsIdentity(
|
|
new[] { new Claim(ClaimTypes.Name, name) }.Concat(allowed ? [new Claim(ClaimTypes.Role,"operator")] : Array.Empty<Claim>()), "synthetic")));
|
|
|
|
[Theory]
|
|
[InlineData(false)]
|
|
[InlineData(true)]
|
|
public async Task DisposalDuringInitialAuthorizationDoesNotSubscribeOrInstallTimers(bool awaitPolicy)
|
|
{
|
|
var auth = new TaskCompletionSource<AuthenticationState>(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
var policy = new TaskCompletionSource<AuthorizationResult>(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
if (awaitPolicy) _authorization.Pending.Enqueue(policy.Task);else _auth.Pending.Enqueue(auth.Task);
|
|
var cut = Render<ObservedPanel>(p => p.Add(x => x.DriverInstanceId,"A"));
|
|
var instance = cut.Instance;
|
|
await DisposeComponentsAsync();
|
|
if (awaitPolicy) policy.SetResult(AuthorizationResult.Success());else auth.SetResult(User());
|
|
await instance.FirstLifecycleFinished.Task.WaitAsync(TimeSpan.FromSeconds(10), Xunit.TestContext.Current.CancellationToken);
|
|
_status.Subscribers.ShouldBe(0);_resilience.Subscribers.ShouldBe(0);_status.Reads.ShouldBe(0);
|
|
typeof(DriverStatusPanel).GetField("_timer",BindingFlags.Instance|BindingFlags.NonPublic)!.GetValue(instance).ShouldBeNull();
|
|
}
|
|
|
|
[Fact]
|
|
public async Task QueuedReconnectAndRestartShareOneGuardBeforeAuthorizationCompletes()
|
|
{
|
|
var cut = Open();
|
|
var auth = new TaskCompletionSource<AuthenticationState>(TaskCreationOptions.RunContinuationsAsynchronously);_auth.Pending.Enqueue(auth.Task);
|
|
var first = Click(Button(cut,"Reconnect"));
|
|
var repeated = Click(Button(cut,"Reconnecting…"));
|
|
try
|
|
{
|
|
_auth.Calls.ShouldBe(2); // initialization plus exactly one operation
|
|
await Click(Button(cut,"Restart"));
|
|
cut.FindAll("button").Any(b => b.TextContent.Trim()=="Confirm restart").ShouldBeFalse();
|
|
_operations.Messages.ShouldBeEmpty();
|
|
}
|
|
finally { auth.TrySetResult(User());await Task.WhenAll(first,repeated); }
|
|
_operations.Messages.Count.ShouldBe(1);
|
|
}
|
|
|
|
[Theory]
|
|
[InlineData("retarget")]
|
|
[InlineData("disabled")]
|
|
[InlineData("disposed")]
|
|
[InlineData("revoked")]
|
|
public async Task DeferredOperationAuthCannotDispatchAfterItsTargetOrAuthorityRetires(string retirement)
|
|
{
|
|
var cut = Open();
|
|
var auth = new TaskCompletionSource<AuthenticationState>(TaskCreationOptions.RunContinuationsAsynchronously);_auth.Pending.Enqueue(auth.Task);
|
|
var first = Click(Button(cut,"Reconnect"));
|
|
if (retirement=="retarget") cut.Render(p => p.Add(x=>x.DriverInstanceId,"B").Add(x=>x.ClusterId,"cluster-B"));
|
|
else if (retirement=="disabled") cut.Render(p=>p.Add(x=>x.Enabled,false));
|
|
else if (retirement=="disposed") await DisposeComponentsAsync();
|
|
auth.SetResult(User(allowed:retirement!="revoked"));await first;
|
|
_operations.Messages.ShouldBeEmpty();
|
|
}
|
|
|
|
[Fact]
|
|
public async Task BusyNotificationAndActorArgumentsUseTheCurrentUserAndClearOnlyTheirOwnOperation()
|
|
{
|
|
var cut=Open();var notifications=new List<bool>();Busy(cut,notifications);_operations.Defer=true;
|
|
_auth.Current=User("refreshed-user");
|
|
var first=Click(Button(cut,"Reconnect"));
|
|
cut.WaitForAssertion(()=>_operations.Messages.Count.ShouldBe(1));
|
|
notifications.ShouldBe([true]);
|
|
var message=Assert.IsType<ReconnectDriver>(_operations.Messages.Single());
|
|
message.DriverInstanceId.ShouldBe("A");message.ClusterId.ShouldBe("cluster-A");message.ActorByUserName.ShouldBe("refreshed-user");message.CorrelationId.ShouldNotBe(Guid.Empty);
|
|
_operations.Tokens.Single().CanBeCanceled.ShouldBeTrue();
|
|
_operations.ReconnectReplies.Single().SetResult(new(true,null,message.CorrelationId));await first;
|
|
notifications.ShouldBe([true,false]);cut.Markup.ShouldContain("Reconnect dispatched");
|
|
}
|
|
|
|
[Theory]
|
|
[InlineData(false)]
|
|
[InlineData(true)]
|
|
public async Task RetiredOperationCompletionCannotClearNewTargetBusyCallbackOrResult(bool exception)
|
|
{
|
|
var cut=Open();var a=new List<bool>();var b=new List<bool>();Busy(cut,a);_operations.Defer=true;
|
|
var first=Click(Button(cut,"Reconnect"));cut.WaitForAssertion(()=>_operations.Messages.Count.ShouldBe(1));
|
|
cut.Render(p=>p.Add(x=>x.DriverInstanceId,"B").Add(x=>x.ClusterId,"cluster-B"));Busy(cut,b);
|
|
var second=Click(Button(cut,"Reconnect"));cut.WaitForAssertion(()=>_operations.Messages.Count.ShouldBe(2));
|
|
if(exception)_operations.ReconnectReplies[0].SetException(new IOException("retired A result"));else _operations.ReconnectReplies[0].SetResult(new(false,"retired A result",Guid.Empty));await first;
|
|
a.ShouldBe([true]);b.ShouldBe([true]);cut.Markup.ShouldNotContain("retired A result");
|
|
_operations.ReconnectReplies[1].SetResult(new(true,null,Guid.Empty));await second;b.ShouldBe([true,false]);
|
|
}
|
|
|
|
[Fact]
|
|
public void RestartConfirmationIsInlineNamedAndCancelIsTheSafeFocusTarget()
|
|
{
|
|
var cut=Open();Button(cut,"Restart").Click();
|
|
cut.FindAll("[role=dialog]").ShouldBeEmpty();
|
|
var region=cut.Find("[role=group][aria-labelledby]");var label=region.GetAttribute("aria-labelledby");cut.Find("#"+label).TextContent.ShouldContain("Restart driver A");
|
|
var cancel=region.QuerySelectorAll("button").Single(b=>b.TextContent.Trim()=="Cancel");cancel.GetAttribute("data-initial-focus").ShouldNotBeNull();
|
|
JSInterop.Invocations["Blazor._internal.domWrapper.focus"].Count.ShouldBe(1);
|
|
cancel.Click();_operations.Messages.ShouldBeEmpty();cut.FindAll("[role=group][aria-labelledby]").ShouldBeEmpty();
|
|
}
|
|
|
|
[Fact]
|
|
public async Task CanceledAndReopenedSameDriverRejectsItsActualOldConfirmDelegate()
|
|
{
|
|
var cut=Open();Button(cut,"Restart").Click();
|
|
var old=CaptureConfirm(cut);
|
|
Button(cut,"Cancel").Click();Button(cut,"Restart").Click();
|
|
await cut.InvokeAsync(old);
|
|
_operations.Messages.ShouldBeEmpty();
|
|
Button(cut,"Confirm restart").ShouldNotBeNull();
|
|
await Click(Button(cut,"Confirm restart"));
|
|
var command=Assert.IsType<RestartDriver>(Assert.Single(_operations.Messages));
|
|
command.DriverInstanceId.ShouldBe("A");command.ClusterId.ShouldBe("cluster-A");
|
|
}
|
|
|
|
private Func<Task> CaptureConfirm(IRenderedComponent<DriverStatusPanel> cut)
|
|
{
|
|
var method=Renderer.GetType().GetMethod("GetCurrentRenderTreeFrames",BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic)!;
|
|
var snapshot=method.Invoke(Renderer,[cut.ComponentId])!;
|
|
var frames=(Array)snapshot.GetType().GetField("Array")!.GetValue(snapshot)!;
|
|
var count=(int)snapshot.GetType().GetField("Count")!.GetValue(snapshot)!;
|
|
static object? Read(object frame,string property)=>frame.GetType().GetProperty(property)!.GetValue(frame);
|
|
for(var i=0;i<count;i++)
|
|
{
|
|
var frame=frames.GetValue(i)!;if(Read(frame,"FrameType")!.ToString()!="Element")continue;
|
|
var attributes=new Dictionary<string,object?>();
|
|
for(var next=i+1;next<count;next++)
|
|
{
|
|
var attribute=frames.GetValue(next)!;if(Read(attribute,"FrameType")!.ToString()!="Attribute")break;
|
|
attributes[(string)Read(attribute,"AttributeName")!]=Read(attribute,"AttributeValue");
|
|
}
|
|
if(!attributes.TryGetValue("class",out var css)||css?.ToString()!="btn btn-danger")continue;
|
|
return attributes["onclick"] switch
|
|
{
|
|
Func<Task> handler=>()=>EventCallback.Factory.Create<MouseEventArgs>(cut.Instance,handler).InvokeAsync(new()),
|
|
Func<MouseEventArgs,Task> handler=>()=>EventCallback.Factory.Create<MouseEventArgs>(cut.Instance,handler).InvokeAsync(new()),
|
|
EventCallback<MouseEventArgs> handler=>()=>handler.InvokeAsync(new()),
|
|
EventCallback handler=>()=>handler.InvokeAsync(new MouseEventArgs()),
|
|
_=>throw new InvalidOperationException("Unexpected actual confirm handler")
|
|
};
|
|
}
|
|
throw new InvalidOperationException("Actual rendered confirm handler not found");
|
|
}
|
|
|
|
[Theory]
|
|
[InlineData("retarget")]
|
|
[InlineData("disabled")]
|
|
[InlineData("disposed")]
|
|
[InlineData("revoked")]
|
|
public async Task PendingPolicyDecisionCannotDispatchAfterCurrentContextOrRoleRetires(string retirement)
|
|
{
|
|
var cut=Open();var notifications=new List<bool>();Busy(cut,notifications);
|
|
var policy=new TaskCompletionSource<AuthorizationResult>(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
_authorization.Pending.Enqueue(policy.Task);
|
|
var pending=Click(Button(cut,"Reconnect"));
|
|
if(retirement=="retarget")cut.Render(p=>p.Add(x=>x.DriverInstanceId,"B"));
|
|
else if(retirement=="disabled")cut.Render(p=>p.Add(x=>x.Enabled,false));
|
|
else if(retirement=="disposed")await DisposeComponentsAsync();
|
|
policy.SetResult(retirement=="revoked"?AuthorizationResult.Failed():AuthorizationResult.Success());await pending;
|
|
_operations.Messages.ShouldBeEmpty();
|
|
notifications.ShouldBe(retirement=="revoked"?[true,false]:[true]);
|
|
}
|
|
|
|
[Theory]
|
|
[InlineData(false)]
|
|
[InlineData(true)]
|
|
public async Task DisposingDispatchedActorWorkDoesNotCancelItsExistingBudgetOrEmitBusyFalse(bool exception)
|
|
{
|
|
var cut=Open();var notifications=new List<bool>();Busy(cut,notifications);_operations.Defer=true;
|
|
var pending=Click(Button(cut,"Reconnect"));cut.WaitForAssertion(()=>_operations.Messages.Count.ShouldBe(1));
|
|
var token=_operations.Tokens.Single();
|
|
await DisposeComponentsAsync();
|
|
token.IsCancellationRequested.ShouldBeFalse();notifications.ShouldBe([true]);
|
|
if(exception)_operations.ReconnectReplies.Single().SetException(new IOException("retired failure"));else _operations.ReconnectReplies.Single().SetResult(new(false,"retired failure",Guid.Empty));await pending;
|
|
notifications.ShouldBe([true]);_status.Subscribers.ShouldBe(0);_resilience.Subscribers.ShouldBe(0);
|
|
Renderer.UnhandledException.IsCompletedSuccessfully.ShouldBeFalse();
|
|
}
|
|
|
|
[Fact]
|
|
public async Task RetargetDuringCapturedBusyCallbackDoesNotEvenBeginOperationAuth()
|
|
{
|
|
var cut=Open();var notifications=new List<bool>();
|
|
var release=new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
typeof(DriverStatusPanel).GetProperty("BusyChanged")!.SetValue(cut.Instance,EventCallback.Factory.Create<bool>(this,async value=>{notifications.Add(value);if(value)await release.Task;}));
|
|
cut.Render();var pending=Click(Button(cut,"Reconnect"));notifications.ShouldBe([true]);
|
|
cut.Render(p=>p.Add(x=>x.DriverInstanceId,"B").Add(x=>x.ClusterId,"cluster-B"));
|
|
release.SetResult();await pending;
|
|
_operations.Messages.ShouldBeEmpty();notifications.ShouldBe([true]);_auth.Calls.ShouldBe(2);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task PendingRestartRejectsItsRetainedConfirmAndCompetingReconnect()
|
|
{
|
|
var cut=Open();Button(cut,"Restart").Click();var confirm=CaptureConfirm(cut);
|
|
var auth=new TaskCompletionSource<AuthenticationState>(TaskCreationOptions.RunContinuationsAsynchronously);_auth.Pending.Enqueue(auth.Task);
|
|
var pending=cut.InvokeAsync(confirm);
|
|
try
|
|
{
|
|
await cut.InvokeAsync(confirm);
|
|
await Click(Button(cut,"Reconnect"));
|
|
_auth.Calls.ShouldBe(2);_operations.Messages.ShouldBeEmpty();
|
|
}
|
|
finally{auth.TrySetResult(User());await pending;}
|
|
Assert.IsType<RestartDriver>(Assert.Single(_operations.Messages));
|
|
}
|
|
|
|
[Theory]
|
|
[InlineData(false,false)]
|
|
[InlineData(false,true)]
|
|
[InlineData(true,false)]
|
|
[InlineData(true,true)]
|
|
public async Task RetiredInitializationAuthFailureDoesNotEscapeIntoReplacement(bool policy,bool dispose)
|
|
{
|
|
var auth=new TaskCompletionSource<AuthenticationState>(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
var grant=new TaskCompletionSource<AuthorizationResult>(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
if(policy)_authorization.Pending.Enqueue(grant.Task);else _auth.Pending.Enqueue(auth.Task);
|
|
var cut=Render<ObservedPanel>(p=>p.Add(x=>x.DriverInstanceId,"A"));var instance=cut.Instance;
|
|
if(dispose)await DisposeComponentsAsync();else cut.Render(p=>p.Add(x=>x.DriverInstanceId,"B"));
|
|
if(policy)grant.SetException(new IOException("retired initial policy failure"));else auth.SetException(new IOException("retired initial auth failure"));
|
|
await instance.FirstLifecycleFinished.Task.WaitAsync(TimeSpan.FromSeconds(10),Xunit.TestContext.Current.CancellationToken);
|
|
instance.FirstLifecycleException.ShouldBeNull();
|
|
_operations.Messages.ShouldBeEmpty();
|
|
}
|
|
|
|
private sealed class ObservedPanel : DriverStatusPanel
|
|
{
|
|
private int _visits;
|
|
public TaskCompletionSource FirstLifecycleFinished {get;}=new(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
public Exception? FirstLifecycleException {get;private set;}
|
|
protected override async Task OnParametersSetAsync()
|
|
{
|
|
var first=_visits++==0;
|
|
try{await base.OnParametersSetAsync();}
|
|
catch(Exception ex)when(first){FirstLifecycleException=ex;}
|
|
finally{if(first)FirstLifecycleFinished.TrySetResult();}
|
|
}
|
|
}
|
|
private sealed class ControlledAuth : AuthenticationStateProvider
|
|
{
|
|
public int Calls;public AuthenticationState Current=User();public Queue<Task<AuthenticationState>> Pending{get;}=[];
|
|
public override Task<AuthenticationState> GetAuthenticationStateAsync(){Calls++;return Pending.TryDequeue(out var next)?next:Task.FromResult(Current);}
|
|
}
|
|
private sealed class ControlledAuthorization : IAuthorizationService
|
|
{
|
|
public Queue<Task<AuthorizationResult>> Pending{get;}=[];
|
|
public Task<AuthorizationResult> AuthorizeAsync(ClaimsPrincipal user,object? resource,string policyName)=>Pending.TryDequeue(out var next)?next:Task.FromResult(user.IsInRole("operator")?AuthorizationResult.Success():AuthorizationResult.Failed());
|
|
public Task<AuthorizationResult> AuthorizeAsync(ClaimsPrincipal user,object? resource,IEnumerable<IAuthorizationRequirement> requirements)=>AuthorizeAsync(user,resource,"");
|
|
}
|
|
public class Operations : DispatchProxy
|
|
{
|
|
public bool Defer;public List<object> Messages{get;}=[];public List<CancellationToken> Tokens{get;}=[];
|
|
public List<TaskCompletionSource<ReconnectDriverResult>> ReconnectReplies{get;}=[];public List<TaskCompletionSource<RestartDriverResult>> RestartReplies{get;}=[];
|
|
protected override object? Invoke(MethodInfo? method,object?[]? args)
|
|
{
|
|
if(method?.Name!=nameof(IAdminOperationsClient.AskAsync))throw new InvalidOperationException("Synthetic operation refused");
|
|
Messages.Add(args![0]!);Tokens.Add((CancellationToken)args[1]!);
|
|
if(args[0]is ReconnectDriver reconnect){var reply=new TaskCompletionSource<ReconnectDriverResult>(TaskCreationOptions.RunContinuationsAsynchronously);ReconnectReplies.Add(reply);if(!Defer)reply.SetResult(new(true,null,reconnect.CorrelationId));return reply.Task;}
|
|
if(args[0]is RestartDriver restart){var reply=new TaskCompletionSource<RestartDriverResult>(TaskCreationOptions.RunContinuationsAsynchronously);RestartReplies.Add(reply);if(!Defer)reply.SetResult(new(true,null,restart.CorrelationId));return reply.Task;}
|
|
throw new InvalidOperationException("Unexpected operation type");
|
|
}
|
|
}
|
|
private sealed class RecordingStatus : IDriverStatusSnapshotStore
|
|
{
|
|
private Action<DriverHealthChanged>? _handlers;public int Subscribers=>_handlers?.GetInvocationList().Length??0;public int Reads;
|
|
public event Action<DriverHealthChanged>? SnapshotChanged{add{_handlers+=value;}remove{_handlers-=value;}}
|
|
public IReadOnlyCollection<StoredDriverHealth> GetAllWithReceiveTime(){Reads++;return [];}
|
|
public IReadOnlyCollection<DriverHealthChanged> GetAll()=>[];
|
|
public bool TryGet(string id,out DriverHealthChanged snapshot){snapshot=null!;return false;}
|
|
public void Upsert(DriverHealthChanged snapshot)=>_handlers?.Invoke(snapshot);
|
|
public int EvictUnconfiguredStale(IReadOnlySet<string> ids,DateTime older)=>0;
|
|
}
|
|
private sealed class RecordingResilience : IDriverResilienceStatusStore
|
|
{
|
|
private Action<DriverResilienceStatusChanged>? _handlers;public int Subscribers=>_handlers?.GetInvocationList().Length??0;
|
|
public event Action<DriverResilienceStatusChanged>? SnapshotChanged{add{_handlers+=value;}remove{_handlers-=value;}}
|
|
public IReadOnlyList<DriverResilienceStatusChanged> GetForInstance(string id)=>[];public IReadOnlyCollection<DriverResilienceStatusChanged> GetAll()=>[];
|
|
public void Upsert(DriverResilienceStatusChanged snapshot)=>_handlers?.Invoke(snapshot);
|
|
public int EvictUnconfiguredStale(IReadOnlySet<string> ids,DateTime older)=>0;
|
|
}
|
|
}
|