using System.Reflection; using System.Runtime.ExceptionServices; using System.Security.Claims; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.Authorization; using Microsoft.AspNetCore.Components.RenderTree; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging.Abstractions; using Shouldly; using Xunit; using ZB.MOM.WW.OtOpcUa.AdminUI.Browsing; using ZB.MOM.WW.OtOpcUa.AdminUI.Clients; using ZB.MOM.WW.OtOpcUa.AdminUI.Components.Shared.Drivers; using ZB.MOM.WW.OtOpcUa.AdminUI.Components.Shared.Drivers.Pickers; using ZB.MOM.WW.OtOpcUa.Commons.Browsing; using ZB.MOM.WW.OtOpcUa.Commons.Interfaces; using ZB.MOM.WW.OtOpcUa.Commons.Messages.Admin; namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests; // Actual attached component instances exercise private event/lifecycle entry points, // following BrowseOpenGuardTests' framework-renderer pattern. #pragma warning disable BL0006 [Trait("Category", "Unit")] public sealed class SharedProbeLifecycleTests : IDisposable { private readonly List _renderers = []; public void Dispose() { foreach (var renderer in _renderers) renderer.Dispose(); } public static TheoryData Pickers => new() { typeof(AbCipAddressPickerBody), typeof(TwinCATAddressPickerBody), typeof(FOCASAddressPickerBody), typeof(GalaxyAddressPickerBody), typeof(OpcUaClientAddressPickerBody), typeof(SqlAddressPickerBody) }; [Theory, MemberData(nameof(Pickers))] public async Task Open_repeated_while_pending_dispatches_once_and_disposed_entry_does_not_read_config(Type type) { var browser = new RecordingBrowser(); var reads = 0; var picker = Attach(type); Set(picker, "BrowserService", browser); Set(picker, "GetConfigJson", (Func)(() => { reads++; return "{}"; })); var first = Call(picker, "OpenBrowseAsync"); var repeated = Call(picker, "OpenBrowseAsync"); browser.Opens.ShouldBe(1); reads.ShouldBe(1); browser.Pending.SetResult(new BrowseOpenResult(false, "synthetic refusal", Guid.Empty)); await Task.WhenAll(first, repeated); await ((IAsyncDisposable)picker).DisposeAsync(); await Call(picker, "OpenBrowseAsync"); browser.Opens.ShouldBe(1); reads.ShouldBe(1); } [Theory, MemberData(nameof(Pickers))] public async Task Already_dispatched_open_still_closes_its_orphan_after_disposal(Type type) { var browser = new RecordingBrowser(); var picker = Attach(type); Set(picker, "BrowserService", browser); var first = Call(picker, "OpenBrowseAsync"); await ((IAsyncDisposable)picker).DisposeAsync(); var token = Guid.NewGuid(); browser.Pending.SetResult(new BrowseOpenResult(true, null, token)); await first; browser.Closed.ShouldBe([token]); Field(picker, "_token").ShouldBe(Guid.Empty); } [Theory, MemberData(nameof(Pickers))] public async Task Delayed_authentication_after_disposal_does_not_authorize_construct_driver_or_emit_value(Type type) { var auth = new DeferredAuth(); var authorization = new RecordingAuthorization(); var browser = new RecordingBrowser(); var emitted = 0; var reads = 0; var picker = Attach(type); Set(picker, "AuthState", auth); Set(picker, "AuthorizationService", authorization); Set(picker, "BrowserService", browser); Set(picker, "GetConfigJson", (Func)(() => { reads++; return "{}"; })); Set(picker, "CurrentAddressChanged", EventCallback.Factory.Create(this, _ => emitted++)); var initialization = Call(picker, "OnInitializedAsync"); await ((IAsyncDisposable)picker).DisposeAsync(); auth.Pending.SetResult(new AuthenticationState(new ClaimsPrincipal())); await initialization; authorization.Calls.ShouldBe(0); browser.CanBrowseCalls.ShouldBe(0); emitted.ShouldBe(0); reads.ShouldBe(0); } [Theory, MemberData(nameof(Pickers))] public async Task Delayed_authorization_after_disposal_does_not_construct_driver_or_emit_value(Type type) { var auth = new DeferredAuth(); auth.Pending.SetResult(new AuthenticationState(new ClaimsPrincipal())); var authorization = new RecordingAuthorization { Deferred = true }; var browser = new RecordingBrowser(); var emitted = 0; var picker = Attach(type); Set(picker, "AuthState", auth); Set(picker, "AuthorizationService", authorization); Set(picker, "BrowserService", browser); Set(picker, "CurrentAddressChanged", EventCallback.Factory.Create(this, _ => emitted++)); var initialization = Call(picker, "OnInitializedAsync"); authorization.Calls.ShouldBe(1); await ((IAsyncDisposable)picker).DisposeAsync(); authorization.Pending.SetResult(AuthorizationResult.Success()); await initialization; browser.CanBrowseCalls.ShouldBe(0); emitted.ShouldBe(0); } [Theory, MemberData(nameof(Pickers))] public async Task Disposal_from_config_accessor_prevents_browse_dispatch(Type type) { var browser = new RecordingBrowser(); var picker = Attach(type); Set(picker, "BrowserService", browser); Set(picker, "GetConfigJson", (Func)(() => { ((IAsyncDisposable)picker).DisposeAsync().GetAwaiter().GetResult(); return "{}"; })); browser.Pending.SetResult(new BrowseOpenResult(false, "synthetic", Guid.Empty)); await Call(picker, "OpenBrowseAsync"); browser.Opens.ShouldBe(0); } [Fact] public async Task Disposal_from_config_accessor_prevents_test_connect_dispatch() { var client = DispatchProxy.Create(); var recorder = (RecordingOperations)(object)client; recorder.Pending.SetResult(new TestDriverConnectResult(false, "synthetic", null, Guid.NewGuid())); var button = Attach(typeof(DriverTestConnectButton)); Set(button, "Probe", new AdminProbeService(client)); Set(button, "GetConfigJson", (Func)(() => { ((IAsyncDisposable)button).DisposeAsync().GetAwaiter().GetResult(); return "{}"; })); await Call(button, "OnClickAsync"); recorder.Calls.ShouldBe(0); } [Fact] public async Task Test_connect_repeated_pending_and_disposed_clicks_do_not_replay_or_publish_late_result() { var client = DispatchProxy.Create(); var recorder = (RecordingOperations)(object)client; var button = Attach(typeof(DriverTestConnectButton)); var reads = 0; Set(button, "Probe", new AdminProbeService(client)); Set(button, "DriverType", "Synthetic"); Set(button, "GetConfigJson", (Func)(() => { reads++; return "{}"; })); var first = Call(button, "OnClickAsync"); var repeated = Call(button, "OnClickAsync"); recorder.Calls.ShouldBe(1); reads.ShouldBe(1); await ((IAsyncDisposable)button).DisposeAsync(); await Call(button, "OnClickAsync"); recorder.Calls.ShouldBe(1); reads.ShouldBe(1); recorder.Pending.SetResult(new TestDriverConnectResult(true, "synthetic", 1, Guid.NewGuid())); await Task.WhenAll(first, repeated); Field(button, "_result").ShouldBeNull(); } private object Attach(Type type) { var component = (IComponent)Activator.CreateInstance(type)!; var renderer = new InertRenderer(); _renderers.Add(renderer); renderer.Attach(component); return component; } private static void Set(object target, string name, object value) => target.GetType().GetProperty(name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)!.SetValue(target, value); private static T Field(object target, string name) => (T)target.GetType().GetField(name, BindingFlags.NonPublic | BindingFlags.Instance)!.GetValue(target)!; private static Task Call(object target, string name) => (Task)target.GetType().GetMethod(name, BindingFlags.NonPublic | BindingFlags.Instance)!.Invoke(target, null)!; private sealed class DeferredAuth : AuthenticationStateProvider { public TaskCompletionSource Pending { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); public override Task GetAuthenticationStateAsync() => Pending.Task; } private sealed class RecordingAuthorization : IAuthorizationService { public int Calls { get; private set; } public bool Deferred { get; init; } public TaskCompletionSource Pending { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); public Task AuthorizeAsync(ClaimsPrincipal user, object? resource, string policyName) { Calls++; return Deferred ? Pending.Task : Task.FromResult(AuthorizationResult.Success()); } public Task AuthorizeAsync(ClaimsPrincipal user, object? resource, IEnumerable requirements) => AuthorizeAsync(user, resource, ""); } private sealed class RecordingBrowser : IBrowserSessionService { public int Opens { get; private set; } public int CanBrowseCalls { get; private set; } public List Closed { get; } = []; public TaskCompletionSource Pending { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); public bool CanBrowse(string driverType, string configJson) { CanBrowseCalls++; return true; } public Task OpenAsync(string driverType, string configJson, CancellationToken ct) { Opens++; return Pending.Task; } public Task CloseAsync(Guid token) { Closed.Add(token); return Task.CompletedTask; } public Task> RootAsync(Guid token, CancellationToken ct) => throw new NotSupportedException(); public Task> ExpandAsync(Guid token, string nodeId, CancellationToken ct) => throw new NotSupportedException(); public Task> AttributesAsync(Guid token, string nodeId, CancellationToken ct) => throw new NotSupportedException(); public Task RequestRebirthAsync(Guid token, string scope, CancellationToken ct) => throw new NotSupportedException(); public bool CanRequestRebirth(Guid token) => false; } public class RecordingOperations : DispatchProxy { public int Calls { get; private set; } public TaskCompletionSource Pending { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); protected override object? Invoke(MethodInfo? method, object?[]? args) { Calls++; return Pending.Task; } } private sealed class InertRenderer() : Renderer(new ServiceCollection().BuildServiceProvider(), NullLoggerFactory.Instance) { public override Dispatcher Dispatcher { get; } = new InlineDispatcher(); public void Attach(IComponent component) => AssignRootComponentId(component); protected override void HandleException(Exception exception) => ExceptionDispatchInfo.Capture(exception).Throw(); protected override Task UpdateDisplayAsync(in RenderBatch renderBatch) => Task.CompletedTask; } private sealed class InlineDispatcher : Dispatcher { public override bool CheckAccess() => true; public override Task InvokeAsync(Action workItem) { workItem(); return Task.CompletedTask; } public override Task InvokeAsync(Func workItem) => workItem(); public override Task InvokeAsync(Func workItem) => Task.FromResult(workItem()); public override Task InvokeAsync(Func> workItem) => workItem(); } }