Files
ScadaBridge/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/DataConnectionFormTests.cs
T
Joseph Doherty 712c5117ee feat(dcl): ServiceLevel-aware OPC UA failover for primary/backup pairs (#138)
Prerequisite for OtOpcUa Warm redundancy (lmxopcua#717): a Warm standby keeps a
healthy session but serves BadOutOfService at a standby ServiceLevel (90/50, boot 1),
so a connection that lands there sat on Bad quality forever.

- OPC UA connections with a backup poll Server_ServiceLevel (i=2267) on the connected
  endpoint (IServiceLevelReadable, implemented by OpcUaDataConnection; never raises
  Disconnected). A level < 200 sustained for the degraded window (default 10 s), or
  the first sample after any (re)connect, triggers a probe of the other endpoint
  (short-lived session: connect, read, dispose). Switch only when it reports a
  Healthy (>= 200) higher level, and not within the minimum dwell (default 60 s) of
  the previous ServiceLevel switch. Both degraded, other unreachable or level
  unknown: stay put. 250/240 (today's OtOpcUa) never starts a streak.
- The switch reuses the failover path: SwitchToOtherEndpoint() now shared by all
  three triggers, then BecomeReconnecting(ReconnectCause.ServiceLevelFailover) -
  zero delay, no unstable accounting, ReSubscribeAll on the new endpoint.
- Config: OpcUaEndpointConfig.ServiceLevelFailover {enabled, degradedWindowSeconds,
  minDwellSeconds}, read from the PRIMARY endpoint's JSON only; null = defaults
  (enabled, 10, 60). Inside the encrypted protocol JSON, so no schema change or
  migration. Central UI: fields in the Backup card next to Failover Retry Count.
  Global: ScadaBridge:DataConnection:ServiceLevelPollInterval (2 s) and
  ServiceLevelProbeTimeout (15 s).
- Tests: actor tests per trigger/non-trigger with positive controls, an unsolicited
  promotion RefreshStart/RefreshEnd test at client and actor level, adapter tests,
  and a real in-process OPC UA server pair end to end. All 15 mutants killed.
- Docs: Component-DataConnectionLayer, components/DataConnectionLayer, Component-CLI.

Claude-Session: https://claude.ai/code/session_01GT67ACmpMR7b9LGRPLijMi
2026-11-13 03:06:54 -05:00

241 lines
11 KiB
C#

using System.Security.Claims;
using ZB.MOM.WW.ScadaBridge.Security;
using System.Text.Json;
using Bunit;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.Extensions.DependencyInjection;
using NSubstitute;
using ZB.MOM.WW.ScadaBridge.CentralUI.Services;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;
using DataConnectionForm = ZB.MOM.WW.ScadaBridge.CentralUI.Components.Pages.Design.DataConnectionForm;
namespace ZB.MOM.WW.ScadaBridge.CentralUI.Tests;
public class DataConnectionFormTests : BunitContext
{
private readonly ISiteRepository _siteRepo = Substitute.For<ISiteRepository>();
/// <summary>Initializes the test context and registers the substitute services the form requires.</summary>
public DataConnectionFormTests()
{
Services.AddSingleton(_siteRepo);
// The OPC UA editor rendered inside the form injects IEndpointVerificationService
// (B8 / T17 Verify-endpoint button) and ICertManagementService (B10 / T17
// Trust-certificate button); no-op substitutes satisfy the injections.
Services.AddSingleton<IEndpointVerificationService>(Substitute.For<IEndpointVerificationService>());
Services.AddSingleton<ICertManagementService>(Substitute.For<ICertManagementService>());
AddTestAuth();
var sites = new List<Site> { new("Plant-A", "plant-a") { Id = 1 } };
_siteRepo.GetAllSitesAsync(Arg.Any<CancellationToken>())
.Returns(Task.FromResult<IReadOnlyList<Site>>(sites));
}
private void AddTestAuth()
{
var claims = new[]
{
new Claim(JwtTokenService.UsernameClaimType, "tester"),
new Claim(JwtTokenService.RoleClaimType, "Designer")
};
var user = new ClaimsPrincipal(new ClaimsIdentity(claims, "TestAuth"));
Services.AddSingleton<AuthenticationStateProvider>(new TestAuthStateProvider(user));
Services.AddAuthorizationCore();
Services.AddTestConfigurationMutations();
}
private IRenderedComponent<DataConnectionForm> RenderForCreateSite(int siteId)
{
Services.GetRequiredService<NavigationManager>()
.NavigateTo($"/admin/connections/create?siteId={siteId}");
return Render<DataConnectionForm>();
}
/// <summary>Verifies that the protocol dropdown is rendered on create and offers both protocols.</summary>
[Fact]
public void ProtocolDropdown_IsRendered_OnCreate_WithBothProtocols()
{
var cut = RenderForCreateSite(1);
var labels = cut.FindAll("label").Select(l => l.TextContent.Trim()).ToList();
Assert.Contains(labels, l => l == "Protocol");
// The protocol select offers OPC UA and MxGateway.
var optionTexts = cut.FindAll("option").Select(o => o.TextContent.Trim()).ToList();
Assert.Contains("OPC UA", optionTexts);
Assert.Contains("MxGateway", optionTexts);
}
/// <summary>Verifies that saving an MxGateway connection persists typed JSON with the MxGateway protocol.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task Save_MxGateway_PersistsTypedJsonAndProtocolMxGateway()
{
DataConnection? captured = null;
await _siteRepo.AddDataConnectionAsync(
Arg.Do<DataConnection>(d => captured = d));
var cut = RenderForCreateSite(1);
// Switch protocol to MxGateway — re-renders with the MxGateway editor.
cut.FindAll("select")
.First(s => s.QuerySelectorAll("option").Any(o => o.TextContent.Trim() == "MxGateway"))
.Change("MxGateway");
// Name (skip readonly Site plaintext input; MxGateway editor inputs carry placeholders).
cut.FindAll("input[type='text']")
.First(i => !i.HasAttribute("readonly") && i.GetAttribute("placeholder") is null)
.Change("MX-1");
// Gateway endpoint
cut.FindAll("input[type='text']")
.First(i => i.GetAttribute("placeholder")?.StartsWith("http://") == true)
.Change("http://gw:5000");
// API key (password input)
cut.FindAll("input[type='password']")
.First(i => i.GetAttribute("placeholder")?.Contains("API key") == true)
.Change("secret");
await cut.FindAll("button")
.First(b => b.TextContent.Trim() == "Save").ClickAsync(new());
Assert.NotNull(captured);
Assert.Equal("MxGateway", captured!.Protocol);
Assert.NotNull(captured.PrimaryConfiguration);
using var doc = JsonDocument.Parse(captured.PrimaryConfiguration!);
Assert.Equal("http://gw:5000",
doc.RootElement.GetProperty("endpoint").GetString());
}
/// <summary>Verifies that saving an invalid primary URL does not call the repository.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task Save_InvalidPrimaryUrl_DoesNotCallRepo()
{
var cut = RenderForCreateSite(1);
cut.FindAll("input[type='text']")
.First(i => i.GetAttribute("placeholder")?.StartsWith("opc.tcp") == true)
.Change("not-a-url");
// Name field (the first editable text input that is NOT the OPC URL).
// Site renders as a readonly plaintext input when locked — skip it.
cut.FindAll("input[type='text']")
.First(i => !i.HasAttribute("readonly")
&& (i.GetAttribute("placeholder") is null
|| !i.GetAttribute("placeholder")!.StartsWith("opc.tcp")))
.Change("My Connection");
await cut.FindAll("button")
.First(b => b.TextContent.Trim() == "Save").ClickAsync(new());
await _siteRepo.DidNotReceive().AddDataConnectionAsync(Arg.Any<DataConnection>());
Assert.Contains("Endpoint URL must be a valid", cut.Markup);
}
/// <summary>Verifies that saving a valid configuration persists typed JSON with the OPC UA protocol.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task Save_ValidConfig_PersistsTypedJsonAndProtocolOpcUa()
{
DataConnection? captured = null;
await _siteRepo.AddDataConnectionAsync(
Arg.Do<DataConnection>(d => captured = d));
var cut = RenderForCreateSite(1);
// Name (skip readonly Site plaintext input)
cut.FindAll("input[type='text']")
.First(i => !i.HasAttribute("readonly")
&& (i.GetAttribute("placeholder") is null
|| !i.GetAttribute("placeholder")!.StartsWith("opc.tcp")))
.Change("PLC-1");
// Endpoint URL
cut.FindAll("input[type='text']")
.First(i => i.GetAttribute("placeholder")?.StartsWith("opc.tcp") == true)
.Change("opc.tcp://plant-a:4840");
await cut.FindAll("button")
.First(b => b.TextContent.Trim() == "Save").ClickAsync(new());
Assert.NotNull(captured);
Assert.Equal("OpcUa", captured!.Protocol);
Assert.NotNull(captured.PrimaryConfiguration);
using var doc = JsonDocument.Parse(captured.PrimaryConfiguration!);
Assert.Equal("opc.tcp://plant-a:4840",
doc.RootElement.GetProperty("endpointUrl").GetString());
Assert.Equal(60000,
doc.RootElement.GetProperty("sessionTimeoutMs").GetInt32());
}
/// <summary>
/// ScadaBridge#138: with a backup, the ServiceLevel failover fields shown next to Failover
/// Retry Count are stored on the PRIMARY endpoint's JSON; the backup's copy stays null.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task Save_WithBackup_StoresServiceLevelFailoverOnThePrimary()
{
DataConnection? captured = null;
await _siteRepo.AddDataConnectionAsync(Arg.Do<DataConnection>(d => captured = d));
var cut = RenderForCreateSite(1);
cut.FindAll("input[type='text']")
.First(i => !i.HasAttribute("readonly")
&& (i.GetAttribute("placeholder") is null
|| !i.GetAttribute("placeholder")!.StartsWith("opc.tcp")))
.Change("OtOpcUa-Pair");
cut.FindAll("input[type='text']")
.First(i => i.GetAttribute("placeholder")?.StartsWith("opc.tcp") == true)
.Change("opc.tcp://otopcua-a:4840");
await cut.FindAll("button").First(b => b.TextContent.Trim() == "Add Backup Endpoint").ClickAsync(new());
cut.FindAll("input[type='text']")
.Where(i => i.GetAttribute("placeholder")?.StartsWith("opc.tcp") == true)
.ElementAt(1)
.Change("opc.tcp://otopcua-b:4840");
// Defaults are on screen, then edited.
Assert.Equal("10", cut.Find("#sl-failover-window").GetAttribute("value"));
Assert.Equal("60", cut.Find("#sl-failover-dwell").GetAttribute("value"));
cut.Find("#sl-failover-window").Change("15");
cut.Find("#sl-failover-dwell").Change("90");
await cut.FindAll("button").First(b => b.TextContent.Trim() == "Save").ClickAsync(new());
Assert.NotNull(captured);
using var primary = JsonDocument.Parse(captured!.PrimaryConfiguration!);
var sl = primary.RootElement.GetProperty("serviceLevelFailover");
Assert.True(sl.GetProperty("enabled").GetBoolean());
Assert.Equal(15, sl.GetProperty("degradedWindowSeconds").GetInt32());
Assert.Equal(90, sl.GetProperty("minDwellSeconds").GetInt32());
using var backup = JsonDocument.Parse(captured.BackupConfiguration!);
Assert.Equal(JsonValueKind.Null, backup.RootElement.GetProperty("serviceLevelFailover").ValueKind);
}
/// <summary>ScadaBridge#138: without a backup the setting is neither shown nor stored.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task Save_WithoutBackup_StoresNoServiceLevelFailover()
{
DataConnection? captured = null;
await _siteRepo.AddDataConnectionAsync(Arg.Do<DataConnection>(d => captured = d));
var cut = RenderForCreateSite(1);
Assert.Empty(cut.FindAll("#sl-failover-enabled"));
cut.FindAll("input[type='text']")
.First(i => !i.HasAttribute("readonly")
&& (i.GetAttribute("placeholder") is null
|| !i.GetAttribute("placeholder")!.StartsWith("opc.tcp")))
.Change("PLC-1");
cut.FindAll("input[type='text']")
.First(i => i.GetAttribute("placeholder")?.StartsWith("opc.tcp") == true)
.Change("opc.tcp://plant-a:4840");
await cut.FindAll("button").First(b => b.TextContent.Trim() == "Save").ClickAsync(new());
Assert.NotNull(captured);
using var primary = JsonDocument.Parse(captured!.PrimaryConfiguration!);
Assert.Equal(JsonValueKind.Null, primary.RootElement.GetProperty("serviceLevelFailover").ValueKind);
}
}