using System.Reflection;
using AngleSharp.Dom;
using Bunit;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.Extensions.DependencyInjection;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.AdminUI.Components.Shared.Drivers;
using ZB.MOM.WW.OtOpcUa.AdminUI.Components.Shared.Drivers.Forms;
using ZB.MOM.WW.OtOpcUa.AdminUI.Components.Shared.Drivers.DeviceForms;
using ZB.MOM.WW.OtOpcUa.AdminUI.Components.Shared.Uns.TagEditors;
using ZB.MOM.WW.OtOpcUa.AdminUI.Uns;
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.Pages;
/// Rendered field contracts across real protocol forms, including two simultaneous instances.
public class ProtocolFormAccessibilityTests : BunitContext
{
/// Common resilience controls have a separate owner and contract suite.
public ProtocolFormAccessibilityTests()
{
ComponentFactories.AddStub();
Services.AddSingleton(DispatchProxy.Create());
}
/// The verified12 driver,10 device and13 tag-editor surfaces.
public static IEnumerable Forms()
{
yield return [typeof(AbCipDeviceForm)];
yield return [typeof(AbLegacyDeviceForm)];
yield return [typeof(FocasDeviceForm)];
yield return [typeof(GalaxyDeviceForm)];
yield return [typeof(HeidenhainDeviceForm)];
yield return [typeof(ModbusDeviceForm)];
yield return [typeof(MqttDeviceForm)];
yield return [typeof(OpcUaClientDeviceForm)];
yield return [typeof(S7DeviceForm)];
yield return [typeof(TwinCATDeviceForm)];
yield return [typeof(AbCipDriverForm)];
yield return [typeof(AbLegacyDriverForm)];
yield return [typeof(FocasDriverForm)];
yield return [typeof(GalaxyDriverForm)];
yield return [typeof(HeidenhainDriverForm)];
yield return [typeof(MTConnectDriverForm)];
yield return [typeof(ModbusDriverForm)];
yield return [typeof(MqttDriverForm)];
yield return [typeof(OpcUaClientDriverForm)];
yield return [typeof(S7DriverForm)];
yield return [typeof(SqlDriverForm)];
yield return [typeof(TwinCATDriverForm)];
yield return [typeof(AbCipTagConfigEditor)];
yield return [typeof(AbLegacyTagConfigEditor)];
yield return [typeof(CalculationTagConfigEditor)];
yield return [typeof(FocasTagConfigEditor)];
yield return [typeof(HeidenhainTagConfigEditor)];
yield return [typeof(MTConnectTagConfigEditor)];
yield return [typeof(ModbusTagConfigEditor)];
yield return [typeof(MqttTagConfigEditor)];
yield return [typeof(NativeAlarmEditor)];
yield return [typeof(OpcUaClientTagConfigEditor)];
yield return [typeof(S7TagConfigEditor)];
yield return [typeof(SqlTagConfigEditor)];
yield return [typeof(TwinCATTagConfigEditor)];
}
/// Every native field has a visible label/name and every referenced ID is unique and present.
[Theory]
[MemberData(nameof(Forms))]
[Trait("Category", "Unit")]
public void ProtocolFields_TwoInstancesHaveUniqueNamesAndResolvedDescriptions(Type type)
{
var cut = Render>(p => p.Add(x => x.Value, new EditContext(new object()))
.Add(x => x.ChildContent, (RenderFragment)(builder =>
{
for (int i = 0; i < 2; i++)
{
builder.OpenComponent(0, type); builder.SetKey(i);
if (type == typeof(NativeAlarmEditor))
{
builder.AddAttribute(1, "DriverType", "AbCip");
builder.AddAttribute(2, "ConfigJson", "{\"alarm\":{\"alarmType\":\"AlarmCondition\",\"severity\":500}}");
}
builder.CloseComponent();
}
})));
var controls = cut.FindAll("input:not([type=hidden]),select,textarea");
if (type == typeof(GalaxyDeviceForm) || type == typeof(MqttDeviceForm)) controls.ShouldBeEmpty("Galaxy/MQTT devices intentionally have no per-device endpoint");
else controls.ShouldNotBeEmpty(type.Name);
AssertRelationships(cut, type);
}
/// Embedded driver/device/tag bodies remain usable without an external EditForm.
[Theory]
[MemberData(nameof(Forms))]
[Trait("Category", "Unit")]
public void ProtocolFields_StandaloneDoesNotRequireEditContext(Type type)
{
Dictionary values = type == typeof(NativeAlarmEditor)
? new() { ["DriverType"] = "AbCip", ["ConfigJson"] = "{\"alarm\":{\"severity\":500}}" } : new();
var cut = Render(p => p.Add(x => x.Type, type).Add(x => x.Parameters, values));
if (type == typeof(GalaxyDeviceForm) || type == typeof(MqttDeviceForm)) cut.FindAll("input,select,textarea").ShouldBeEmpty();
else cut.FindAll("input,select,textarea").ShouldNotBeEmpty(type.Name);
}
/// Existing number parsing stays in Blazor and cannot silently alter emitted protocol JSON.
[Theory]
[InlineData(typeof(AbCipDriverForm))]
[InlineData(typeof(AbLegacyDriverForm))]
[InlineData(typeof(FocasDriverForm))]
[InlineData(typeof(GalaxyDriverForm))]
[InlineData(typeof(HeidenhainDriverForm))]
[InlineData(typeof(ModbusDriverForm))]
[InlineData(typeof(MqttDriverForm))]
[InlineData(typeof(MTConnectDriverForm))]
[InlineData(typeof(OpcUaClientDriverForm))]
[InlineData(typeof(S7DriverForm))]
[InlineData(typeof(SqlDriverForm))]
[InlineData(typeof(TwinCATDriverForm))]
[Trait("Category", "Unit")]
public void ProtocolFields_InvalidNumberHasLinkedFeedbackAndPreservesConfig(Type type)
{
var cut = Render>(p => p.Add(x => x.Value, new EditContext(new object()))
.Add(x => x.ChildContent, (RenderFragment)(builder =>
{
builder.OpenComponent(0); builder.AddAttribute(1, "Type", type); builder.CloseComponent();
})));
object instance = cut.FindComponent().Instance.Instance!;
MethodInfo getConfig = type.GetMethod("GetConfigJson")!;
string before = (string)getConfig.Invoke(instance, null)!;
var input = cut.Find("input[type=number]");
input.Change("not-a-number");
input = cut.Find("input[type=number]");
input.GetAttribute("aria-invalid").ShouldBe("true");
string description = string.Join(" ", (input.GetAttribute("aria-describedby") ?? string.Empty)
.Split(' ', StringSplitOptions.RemoveEmptyEntries).Select(id => FindById(cut, id).TextContent));
description.ShouldContain("number");
getConfig.Invoke(instance, null).ShouldBe(before);
}
/// Conditional protocol branches retain labels and descriptions in simultaneous instances.
[Theory]
[InlineData(typeof(MqttTagConfigEditor), "{\"groupId\":\"Plant1\",\"edgeNodeId\":\"E1\",\"deviceId\":\"D1\",\"metricName\":\"Temp\"}")]
[InlineData(typeof(SqlTagConfigEditor), "{\"model\":\"Query\",\"queryName\":\"fixture\"}")]
[InlineData(typeof(SqlTagConfigEditor), "{\"model\":\"WideRow\",\"rowSelector\":{\"whereColumn\":\"station\",\"whereValue\":\"1\"}}")]
[InlineData(typeof(SqlTagConfigEditor), "{\"model\":\"WideRow\",\"rowSelector\":{\"topByTimestamp\":\"sample_ts\"}}")]
[InlineData(typeof(HeidenhainTagConfigEditor), "{\"address\":\"Status/ExecutionState\"}")]
[InlineData(typeof(HeidenhainTagConfigEditor), "{\"address\":\"ALARM:*\"}")]
[InlineData(typeof(FocasTagConfigEditor), "{\"address\":\"R100\",\"dataType\":\"String\"}")]
[Trait("Category", "Unit")]
public void ProtocolFields_ConditionalBranchesResolveRelationships(Type type, string config)
{
var cut = Render>(p => p.Add(x => x.Value, new EditContext(new object()))
.Add(x => x.ChildContent, (RenderFragment)(builder =>
{
for (int i = 0; i < 2; i++)
{
builder.OpenComponent(0, type); builder.SetKey(i);
builder.AddAttribute(1, "ConfigJson", config); builder.CloseComponent();
}
})));
AssertRelationships(cut, type);
if (type == typeof(FocasTagConfigEditor))
{
cut.FindAll("[aria-invalid=true]").Count.ShouldBe(4);
foreach (var input in cut.FindAll("[aria-invalid=true]"))
FindById(cut, input.GetAttribute("aria-describedby")!).TextContent.ShouldNotBeNullOrWhiteSpace();
}
}
private static void AssertRelationships(IRenderedComponent> cut, Type type)
{
var controls = cut.FindAll("input:not([type=hidden]),select,textarea");
var ids = cut.FindAll("[id]").Select(e => e.Id).ToArray();
ids.Distinct(StringComparer.Ordinal).Count().ShouldBe(ids.Length, type.Name + " repeated IDs");
foreach (IElement input in controls)
{
string label = input.GetAttribute("aria-label") ?? string.Empty;
if (string.IsNullOrWhiteSpace(label) && input.GetAttribute("aria-labelledby") is { } namedBy)
label = string.Join(" ", namedBy.Split(' ', StringSplitOptions.RemoveEmptyEntries).Select(id => FindById(cut, id).TextContent));
if (string.IsNullOrWhiteSpace(label) && !string.IsNullOrEmpty(input.Id))
label = string.Join(" ", cut.FindAll("label").Where(e => e.GetAttribute("for") == input.Id).Select(e => e.TextContent));
if (string.IsNullOrWhiteSpace(label)) label = input.Closest("label")?.TextContent ?? string.Empty;
label.ShouldNotBeNullOrWhiteSpace(type.Name + ": " + input.OuterHtml);
foreach (string id in (input.GetAttribute("aria-describedby") ?? string.Empty).Split(' ', StringSplitOptions.RemoveEmptyEntries))
FindById(cut, id).ShouldNotBeNull();
}
foreach (var label in cut.FindAll("label[for]"))
FindById(cut, label.GetAttribute("for")!).ShouldNotBeNull();
}
private static IElement FindById(IRenderedComponent> cut, string id) => cut.FindAll("[id]").Single(e => e.Id == id);
/// The only render-time dependency returns an empty synthetic script list; mutations fail closed.
public class ScriptListOnlyProxy : DispatchProxy
{
protected override object? Invoke(MethodInfo? method, object?[]? args) => method?.Name == nameof(IUnsTreeService.LoadScriptsAsync)
? Task.FromResult>([])
: throw new NotSupportedException("Protocol field fixture does not execute operations: " + method?.Name);
}
}