using System.Security.Claims;
using Bunit;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.JSInterop;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.AdminUI.Components.Pages.Clusters;
using ZB.MOM.WW.OtOpcUa.AdminUI.Components.Shared.Raw;
using ZB.MOM.WW.OtOpcUa.AdminUI.DataConnections;
using ZB.MOM.WW.OtOpcUa.AdminUI.Tests.Uns;
using ZB.MOM.WW.OtOpcUa.AdminUI.Uns;
using ZB.MOM.WW.OtOpcUa.Commons.Interfaces;
using ZB.MOM.WW.OtOpcUa.Commons.Types;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
using ZB.MOM.WW.OtOpcUa.Configuration.Validation;
using ZB.MOM.WW.OtOpcUa.Security.Auth;
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.Pages;
/// #1077: the export-root / remote-root fields are cluster-scoped tree pickers.
[Trait("Category", "Unit")]
public sealed class DataConnectionRootPickerTests : BunitContext
{
private const string Cluster = RawTreeTestDb.ClusterId;
private sealed class NoDiagnostics : IFleetDiagnosticsClient
{
public Task GetDiagnosticsAsync(NodeId nodeId, CancellationToken ct) => throw new NotSupportedException();
}
private sealed class PrincipalState : AuthenticationStateProvider
{
public override Task GetAuthenticationStateAsync() => Task.FromResult(
new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity([new(ClaimTypes.Name, "fixture"), new(ClaimTypes.Role, "Administrator")], "fixture"))));
}
public DataConnectionRootPickerTests()
{
// Node-pick mode never mutates or lazy-loads, so RawTree's mutation dialogs are stubbed and its service refuses any call.
var names = new HashSet { "DriverConfigModal", "DeviceModal", "RawTagModal", "RawManualTagEntryModal", "RawCsvImportModal", "RawCsvExportModal", "RawBrowseModal", "RawNameDialog", "RawConfirmDialog", "RawDriverTypeDialog", "RawStubModal" };
ComponentFactories.AddStub(type => names.Contains(type.Name));
Services.AddSingleton(System.Reflection.DispatchProxy.Create());
JSInterop.Mode = JSRuntimeMode.Loose;
JSInterop.Setup("otDialog.activate", _ => true).SetResult(true); // ModalFrame closes itself when activation is refused.
}
public class RefusingRawService : System.Reflection.DispatchProxy
{
protected override object? Invoke(System.Reflection.MethodInfo? method, object?[]? args) => throw new NotSupportedException("Node-pick mode must not call " + method?.Name);
}
private string? _dbName;
private IRenderedComponent>> RenderPage()
{
Services.RemoveAll();
Services.RemoveAll();
Services.AddAuthorizationCore(o => o.AddPolicy(AdminUiPolicies.ConfigEditor, p => p.RequireRole("Administrator", "Designer")));
Services.AddCascadingAuthenticationState();
Services.AddSingleton(new PrincipalState());
Services.AddSingleton(new NoDiagnostics());
var name = _dbName = RawTreeTestDb.SeedFresh();
using (var db = RawTreeTestDb.CreateNamed(name))
{
db.UnsAreas.Add(new UnsArea { UnsAreaId = "AREA-1", ClusterId = Cluster, Name = "Packaging" });
db.UnsLines.Add(new UnsLine { UnsLineId = "LINE-1", UnsAreaId = "AREA-1", Name = "Line one" });
// Another cluster's entities must be unreachable from this cluster's pickers.
db.ServerClusters.Add(new ServerCluster { ClusterId = "OTHER", Name = "Other", Enterprise = "zb", Site = "x", RedundancyMode = RedundancyMode.None, CreatedBy = "test" });
db.UnsAreas.Add(new UnsArea { UnsAreaId = "AREA-OTHER", ClusterId = "OTHER", Name = "Foreign area" });
db.DataConnections.Add(new DataConnection { DataConnectionId = "CONN-1", ClusterId = Cluster, ExpectedClusterId = "OTHER" });
db.SaveChanges();
}
Services.AddSingleton(RawTreeTestDb.Factory(name));
Services.AddSingleton();
var state = new PrincipalState().GetAuthenticationStateAsync();
return Render>>(p => p.Add(x => x.Value, state)
.AddChildContent(c => c.Add(x => x.ClusterId, Cluster)));
}
[Fact]
public void ExportRoot_RawTreePicker_PicksADeviceAndFillsTheField()
{
var cut = RenderPage();
cut.WaitForAssertion(() => cut.Find("button.btn-primary:contains('New export')"));
cut.Find("button:contains('New export')").Click();
cut.WaitForAssertion(() => cut.Find("#export-root"));
cut.Find("#export-root").GetAttribute("value").ShouldBe("No root chosen");
cut.Find("#export-root-browse").Click();
// A dialog opened by a click renders on a later pass.
cut.WaitForAssertion(() => cut.Find("[role=dialog]"));
cut.WaitForAssertion(() => cut.FindAll("input[type=radio]").Count.ShouldBeGreaterThan(0));
cut.Find("#root-picker-confirm").HasAttribute("disabled").ShouldBeTrue();
// Expand down to the device: cluster root is open; folder -> driver -> device.
cut.Find("button[aria-label='Expand PLCs']").Click();
cut.WaitForElement("button[aria-label='Expand modbus-1']").Click();
cut.WaitForElement("input[title='Device dev:" + RawTreeTestDb.FolderedDeviceId + "']").Change(true);
cut.WaitForAssertion(() => cut.Find("#root-picker-selected").TextContent.ShouldBe("RawDevice " + RawTreeTestDb.FolderedDeviceId));
cut.Find("#root-picker-confirm").Click();
cut.WaitForAssertion(() => cut.Find("#export-root").GetAttribute("value").ShouldBe("RawDevice " + RawTreeTestDb.FolderedDeviceId));
cut.FindAll("[role=dialog]").Count.ShouldBe(0);
}
[Fact]
public void ExportRoot_UnsTreePicker_IsClusterScopedAndPicksAnArea()
{
var cut = RenderPage();
cut.WaitForElement("button:contains('New export')").Click();
cut.WaitForElement("#export-realm").Change("Uns");
cut.Find("#export-root-browse").Click();
cut.WaitForAssertion(() => cut.Find("[role=dialog]"));
cut.WaitForAssertion(() => cut.FindAll(".uns-root-picker input[type=radio]").Count.ShouldBeGreaterThan(0));
cut.Markup.ShouldContain("Packaging");
cut.Find("[role=dialog]").InnerHtml.ShouldNotContain("Foreign area");
cut.Find("input[title='UnsArea AREA-1']").Change(true);
cut.Find("#root-picker-confirm").Click();
cut.WaitForAssertion(() => cut.Find("#export-root").GetAttribute("value").ShouldBe("UnsArea AREA-1"));
}
[Fact]
public void RemoteRoot_PickerBrowsesTheTargetClusterOnly_AndFillsTheRootId()
{
var cut = RenderPage();
cut.WaitForElement("button:contains('New mapping')").Click();
cut.WaitForElement("#remote-root-browse").HasAttribute("disabled").ShouldBeTrue(); // no connection chosen yet
cut.Find("#mapping-connection").Change("CONN-1");
cut.Find("#mapping-realm").Change("Uns");
cut.Find("#remote-root-browse").HasAttribute("disabled").ShouldBeFalse();
cut.Find("#remote-root-browse").Click();
cut.WaitForElement("[role=dialog]");
cut.WaitForAssertion(() => cut.FindAll(".uns-root-picker input[type=radio]").Count.ShouldBeGreaterThan(0));
cut.Find("[role=dialog]").InnerHtml.ShouldContain("Foreign area");
cut.Find("[role=dialog]").InnerHtml.ShouldNotContain("Packaging");
cut.Find("input[title='UnsArea AREA-OTHER']").Change(true);
cut.Find("#root-picker-confirm").Click();
cut.WaitForAssertion(() => cut.Find("#remote-root").GetAttribute("value").ShouldBe("AREA-OTHER"));
}
/// #1084: the export editor's secured-write opt-in is offered only with the Write grant and is saved to the row.
[Fact]
public void Export_SecuredWritesCheckbox_RequiresWrite_AndIsSaved()
{
var cut = RenderPage();
cut.WaitForElement("button:contains('New export')").Click();
cut.WaitForElement("#export-secured-writes").HasAttribute("disabled").ShouldBeTrue("a new export has no Write grant");
cut.Find("#export-id").Change("EXP-SW");
cut.Find("#principal").Change("peer-principal");
cut.Find("#export-root-id").Change("RawDevice|" + RawTreeTestDb.FolderedDeviceId);
cut.FindAll("fieldset label").Single(l => l.TextContent.Trim() == "Write").QuerySelector("input")!.Change(true);
cut.WaitForAssertion(() => cut.Find("#export-secured-writes").HasAttribute("disabled").ShouldBeFalse());
cut.Find("#export-secured-writes").Change(true);
cut.Find("button:contains('Save draft')").Click();
cut.WaitForAssertion(() => cut.Markup.ShouldContain("Draft saved"));
using var db = RawTreeTestDb.CreateNamed(_dbName!);
var saved = db.DataExports.Single(x => x.DataExportId == "EXP-SW");
saved.AllowSecuredWrites.ShouldBeTrue();
saved.AllowedOperations.HasFlag(ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataOperations.Write).ShouldBeTrue();
}
[Fact]
public void LocalParent_UnsTreePicker_IsLocalClusterScoped_AndStoresKindAndId()
{
var cut = RenderPage();
cut.WaitForElement("button:contains('New mapping')").Click();
cut.WaitForElement("#mapping-parent").GetAttribute("value").ShouldBe("No parent chosen");
cut.Find("#mapping-realm").Change("Uns");
cut.Find("#mapping-parent-browse").Click();
cut.WaitForAssertion(() => cut.Find("[role=dialog]"));
cut.WaitForAssertion(() => cut.FindAll(".uns-root-picker input[type=radio]").Count.ShouldBeGreaterThan(0));
// The parent is a LOCAL node: this page's cluster, never the connection's target cluster.
cut.Find("[role=dialog]").InnerHtml.ShouldContain("Packaging");
cut.Find("[role=dialog]").InnerHtml.ShouldNotContain("Foreign area");
cut.Find("input[title='UnsArea AREA-1']").Change(true);
cut.Find("#root-picker-confirm").Click();
cut.WaitForAssertion(() => cut.Find("#mapping-parent").GetAttribute("value").ShouldBe("UnsArea AREA-1"));
cut.FindAll("[role=dialog]").Count.ShouldBe(0);
}
[Fact]
public void LocalParent_RawTreePicker_PicksAContainer()
{
var cut = RenderPage();
cut.WaitForElement("button:contains('New mapping')").Click();
cut.WaitForElement("#mapping-parent-browse").Click();
cut.WaitForAssertion(() => cut.FindAll("[role=dialog] input[type=radio]").Count.ShouldBeGreaterThan(0));
cut.Find("button[aria-label='Expand PLCs']").Click();
cut.WaitForElement("button[aria-label='Expand modbus-1']").Click();
cut.WaitForElement("input[title='Device dev:" + RawTreeTestDb.FolderedDeviceId + "']").Change(true);
cut.Find("#root-picker-confirm").Click();
cut.WaitForAssertion(() => cut.Find("#mapping-parent").GetAttribute("value").ShouldBe("RawDevice " + RawTreeTestDb.FolderedDeviceId));
}
[Fact]
public void ChangingTheExportRealm_ClearsTheStaleRoot()
{
var cut = RenderPage();
cut.WaitForElement("button:contains('New export')").Click();
cut.WaitForElement("#export-root-id").Change("RawTag|tag-1");
cut.Find("#export-root").GetAttribute("value").ShouldBe("RawTag tag-1");
cut.Find("#export-realm").Change("Uns");
cut.WaitForAssertion(() => cut.Find("#export-root").GetAttribute("value").ShouldBe("No root chosen"));
}
[Fact]
public void ChangingTheMappingRealm_ClearsTheParentAndRemoteRoot()
{
var cut = RenderPage();
cut.WaitForElement("button:contains('New mapping')").Click();
cut.WaitForElement("#mapping-realm").Change("Uns");
cut.Find("#mapping-parent-browse").Click();
cut.WaitForAssertion(() => cut.FindAll(".uns-root-picker input[type=radio]").Count.ShouldBeGreaterThan(0));
cut.Find("input[title='UnsArea AREA-1']").Change(true);
cut.Find("#root-picker-confirm").Click();
cut.WaitForAssertion(() => cut.Find("#mapping-parent").GetAttribute("value").ShouldBe("UnsArea AREA-1"));
cut.Find("#remote-root-id").Change("AREA-OTHER");
cut.Find("#remote-root").GetAttribute("value").ShouldBe("AREA-OTHER");
cut.Find("#mapping-realm").Change("Raw");
cut.WaitForAssertion(() => cut.Find("#mapping-parent").GetAttribute("value").ShouldBe("No parent chosen"));
cut.Find("#remote-root").GetAttribute("value").ShouldBe("No root chosen");
}
[Fact]
public void Cancel_LeavesTheFieldUnchanged()
{
var cut = RenderPage();
cut.WaitForElement("button:contains('New export')").Click();
cut.WaitForElement("#export-root-browse").Click();
cut.WaitForAssertion(() => cut.Find("[role=dialog]"));
cut.Find("[role=dialog] .modal-footer button:contains('Cancel')").Click();
cut.WaitForAssertion(() => cut.FindAll("[role=dialog]").Count.ShouldBe(0));
cut.Find("#export-root").GetAttribute("value").ShouldBe("No root chosen");
}
[Fact]
public void RawTree_NodePickMode_OffersARadioOnEveryEntityKind_AndLeavesTagPickerModeAlone()
{
var tag = new RawNode { Kind = RawNodeKind.Tag, Key = "tag:t", EntityId = "t", DisplayName = "T" };
var device = new RawNode { Kind = RawNodeKind.Device, Key = "dev:d", EntityId = "d", DisplayName = "D", Expanded = true };
device.Children.Add(tag);
RawNode? picked = null;
var cut = Render(p => p.Add(x => x.Roots, new[] { device }).Add(x => x.NodePickMode, true)
.Add(x => x.OnNodePicked, n => picked = n));
cut.FindAll("input[type=radio]").Count.ShouldBe(2);
cut.Find("input[title='Device dev:d']").Change(true);
picked.ShouldBeSameAs(device);
// The tag picker mode is unchanged: a checkbox on tags only, no radios.
var multi = Render(p => p.Add(x => x.Roots, new[] { device }).Add(x => x.PickerMode, true).Add(x => x.SelectedTagIds, new HashSet()));
multi.FindAll("input[type=radio]").Count.ShouldBe(0);
multi.FindAll("input[type=checkbox]").Count.ShouldBe(1);
}
[Fact]
public async Task Trees_AreClusterScoped_AndNestFoldersGroupsAndTags()
{
var name = RawTreeTestDb.SeedFresh();
using var db = RawTreeTestDb.CreateNamed(name);
var snapshot = await DraftSnapshotFactory.FromConfigDbAsync(db, CancellationToken.None);
var raw = DataRootTrees.BuildRaw(snapshot, Cluster);
raw.Children.Select(c => c.EntityId).ShouldContain(RawTreeTestDb.RootFolderId);
var group = raw.Children.Single(c => c.EntityId == RawTreeTestDb.RootFolderId).Children.Single().Children.Single().Children.Single();
group.Kind.ShouldBe(RawNodeKind.TagGroup);
group.Children.Select(c => c.EntityId).ShouldBe([RawTreeTestDb.HistorizedTagId, RawTreeTestDb.PlainTagId], ignoreOrder: true);
DataRootTrees.BuildRaw(snapshot, "NOPE").Children.ShouldBeEmpty();
DataRootTrees.BuildRaw(snapshot, Cluster, includeTags: false).Children.SelectMany(Flatten).ShouldNotContain(n => n.Kind == RawNodeKind.Tag);
}
private static IEnumerable Flatten(RawNode n) => new[] { n }.Concat(n.Children.SelectMany(Flatten));
}