Phase 0 — mechanical rename ZB.MOM.WW.LmxOpcUa.* → ZB.MOM.WW.OtOpcUa.*

Renames all 11 projects (5 src + 6 tests), the .slnx solution file, all source-file namespaces, all axaml namespace references, and all v1 documentation references in CLAUDE.md and docs/*.md (excluding docs/v2/ which is already in OtOpcUa form). Also updates the TopShelf service registration name from "LmxOpcUa" to "OtOpcUa" per Phase 0 Task 0.6.

Preserves runtime identifiers per Phase 0 Out-of-Scope rules to avoid breaking v1/v2 client trust during coexistence: OPC UA `ApplicationUri` defaults (`urn:{GalaxyName}:LmxOpcUa`), server `EndpointPath` (`/LmxOpcUa`), `ServerName` default (feeds cert subject CN), `MxAccessConfiguration.ClientName` default (defensive — stays "LmxOpcUa" for MxAccess audit-trail consistency), client OPC UA identifiers (`ApplicationName = "LmxOpcUaClient"`, `ApplicationUri = "urn:localhost:LmxOpcUaClient"`, cert directory `%LocalAppData%\LmxOpcUaClient\pki\`), and the `LmxOpcUaServer` class name (class rename out of Phase 0 scope per Task 0.5 sed pattern; happens in Phase 1 alongside `LmxNodeManager → GenericDriverNodeManager` Core extraction). 23 LmxOpcUa references retained, all enumerated and justified in `docs/v2/implementation/exit-gate-phase-0.md`.

Build clean: 0 errors, 30 warnings (lower than baseline 167). Tests at strict improvement over baseline: 821 passing / 1 failing vs baseline 820 / 2 (one flaky pre-existing failure passed this run; the other still fails — both pre-existing and unrelated to the rename). `Client.UI.Tests`, `Historian.Aveva.Tests`, `Client.Shared.Tests`, `IntegrationTests` all match baseline exactly. Exit gate compliance results recorded in `docs/v2/implementation/exit-gate-phase-0.md` with all 7 checks PASS or DEFERRED-to-PR-review (#7 service install verification needs Windows service permissions on the reviewer's box).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Joseph Doherty
2026-04-17 13:57:47 -04:00
parent 5b8d708c58
commit 3b2defd94f
293 changed files with 841 additions and 722 deletions

View File

@@ -0,0 +1,38 @@
using Opc.Ua;
using ZB.MOM.WW.OtOpcUa.Client.Shared.Adapters;
using ZB.MOM.WW.OtOpcUa.Client.Shared.Models;
namespace ZB.MOM.WW.OtOpcUa.Client.Shared.Tests.Fakes;
internal sealed class FakeApplicationConfigurationFactory : IApplicationConfigurationFactory
{
public bool ThrowOnCreate { get; set; }
public int CreateCallCount { get; private set; }
public ConnectionSettings? LastSettings { get; private set; }
public Task<ApplicationConfiguration> CreateAsync(ConnectionSettings settings, CancellationToken ct)
{
CreateCallCount++;
LastSettings = settings;
if (ThrowOnCreate)
throw new InvalidOperationException("FakeApplicationConfigurationFactory configured to fail.");
var config = new ApplicationConfiguration
{
ApplicationName = "FakeClient",
ApplicationUri = "urn:localhost:FakeClient",
ApplicationType = ApplicationType.Client,
SecurityConfiguration = new SecurityConfiguration
{
AutoAcceptUntrustedCertificates = true
},
ClientConfiguration = new ClientConfiguration
{
DefaultSessionTimeout = settings.SessionTimeoutSeconds * 1000
}
};
return Task.FromResult(config);
}
}

View File

@@ -0,0 +1,35 @@
using Opc.Ua;
using ZB.MOM.WW.OtOpcUa.Client.Shared.Adapters;
namespace ZB.MOM.WW.OtOpcUa.Client.Shared.Tests.Fakes;
internal sealed class FakeEndpointDiscovery : IEndpointDiscovery
{
public bool ThrowOnSelect { get; set; }
public int SelectCallCount { get; private set; }
public string? LastEndpointUrl { get; private set; }
public EndpointDescription SelectEndpoint(ApplicationConfiguration config, string endpointUrl,
MessageSecurityMode requestedMode)
{
SelectCallCount++;
LastEndpointUrl = endpointUrl;
if (ThrowOnSelect)
throw new InvalidOperationException($"No endpoint found for {endpointUrl}");
return new EndpointDescription
{
EndpointUrl = endpointUrl,
SecurityMode = requestedMode,
SecurityPolicyUri = requestedMode == MessageSecurityMode.None
? SecurityPolicies.None
: SecurityPolicies.Basic256Sha256,
Server = new ApplicationDescription
{
ApplicationName = "FakeServer",
ApplicationUri = "urn:localhost:FakeServer"
}
};
}
}

View File

@@ -0,0 +1,199 @@
using Opc.Ua;
using ZB.MOM.WW.OtOpcUa.Client.Shared.Adapters;
namespace ZB.MOM.WW.OtOpcUa.Client.Shared.Tests.Fakes;
/// <summary>
/// Test double for <see cref="ISessionAdapter" /> used to simulate reads, writes, browsing, history, and failover callbacks.
/// </summary>
internal sealed class FakeSessionAdapter : ISessionAdapter
{
private readonly List<FakeSubscriptionAdapter> _createdSubscriptions = [];
private Action<bool>? _keepAliveCallback;
/// <summary>
/// Gets a value indicating whether the fake session has been closed through the client disconnect path.
/// </summary>
public bool Closed { get; private set; }
/// <summary>
/// Gets a value indicating whether the fake session has been disposed.
/// </summary>
public bool Disposed { get; private set; }
public int ReadCount { get; private set; }
public int WriteCount { get; private set; }
public int BrowseCount { get; private set; }
public int BrowseNextCount { get; private set; }
public int HasChildrenCount { get; private set; }
public int HistoryReadRawCount { get; private set; }
public int HistoryReadAggregateCount { get; private set; }
// Configurable responses
public DataValue? ReadResponse { get; set; }
public Func<NodeId, DataValue>? ReadResponseFunc { get; set; }
public StatusCode WriteResponse { get; set; } = StatusCodes.Good;
public bool ThrowOnRead { get; set; }
public bool ThrowOnWrite { get; set; }
public bool ThrowOnBrowse { get; set; }
public ReferenceDescriptionCollection BrowseResponse { get; set; } = [];
public byte[]? BrowseContinuationPoint { get; set; }
public ReferenceDescriptionCollection BrowseNextResponse { get; set; } = [];
public byte[]? BrowseNextContinuationPoint { get; set; }
public bool HasChildrenResponse { get; set; } = false;
public List<DataValue> HistoryReadRawResponse { get; set; } = [];
public List<DataValue> HistoryReadAggregateResponse { get; set; } = [];
public bool ThrowOnHistoryReadRaw { get; set; }
public bool ThrowOnHistoryReadAggregate { get; set; }
/// <summary>
/// Gets or sets the next fake subscription returned when the client creates a monitored-item subscription.
/// If unset, the fake builds a new subscription automatically.
/// </summary>
public FakeSubscriptionAdapter? NextSubscription { get; set; }
/// <summary>
/// Gets the fake subscriptions created by this session so tests can inspect replay and cleanup behavior.
/// </summary>
public IReadOnlyList<FakeSubscriptionAdapter> CreatedSubscriptions => _createdSubscriptions;
/// <inheritdoc />
public bool Connected { get; set; } = true;
/// <inheritdoc />
public string SessionId { get; set; } = "ns=0;i=12345";
/// <inheritdoc />
public string SessionName { get; set; } = "FakeSession";
/// <inheritdoc />
public string EndpointUrl { get; set; } = "opc.tcp://localhost:4840";
/// <inheritdoc />
public string ServerName { get; set; } = "FakeServer";
/// <inheritdoc />
public string SecurityMode { get; set; } = "None";
/// <inheritdoc />
public string SecurityPolicyUri { get; set; } = "http://opcfoundation.org/UA/SecurityPolicy#None";
/// <inheritdoc />
public NamespaceTable NamespaceUris { get; set; } = new();
/// <inheritdoc />
public void RegisterKeepAliveHandler(Action<bool> callback)
{
_keepAliveCallback = callback;
}
/// <inheritdoc />
public Task<DataValue> ReadValueAsync(NodeId nodeId, CancellationToken ct)
{
ReadCount++;
if (ThrowOnRead)
throw new ServiceResultException(StatusCodes.BadNodeIdUnknown, "Node not found");
if (ReadResponseFunc != null)
return Task.FromResult(ReadResponseFunc(nodeId));
return Task.FromResult(ReadResponse ?? new DataValue(new Variant(0), StatusCodes.Good));
}
/// <inheritdoc />
public Task<StatusCode> WriteValueAsync(NodeId nodeId, DataValue value, CancellationToken ct)
{
WriteCount++;
if (ThrowOnWrite)
throw new ServiceResultException(StatusCodes.BadNodeIdUnknown, "Node not found");
return Task.FromResult(WriteResponse);
}
/// <inheritdoc />
public Task<(byte[]? ContinuationPoint, ReferenceDescriptionCollection References)> BrowseAsync(
NodeId nodeId, uint nodeClassMask, CancellationToken ct)
{
BrowseCount++;
if (ThrowOnBrowse)
throw new ServiceResultException(StatusCodes.BadNodeIdUnknown, "Node not found");
return Task.FromResult((BrowseContinuationPoint, BrowseResponse));
}
/// <inheritdoc />
public Task<(byte[]? ContinuationPoint, ReferenceDescriptionCollection References)> BrowseNextAsync(
byte[] continuationPoint, CancellationToken ct)
{
BrowseNextCount++;
return Task.FromResult((BrowseNextContinuationPoint, BrowseNextResponse));
}
/// <inheritdoc />
public Task<bool> HasChildrenAsync(NodeId nodeId, CancellationToken ct)
{
HasChildrenCount++;
return Task.FromResult(HasChildrenResponse);
}
/// <inheritdoc />
public Task<IReadOnlyList<DataValue>> HistoryReadRawAsync(
NodeId nodeId, DateTime startTime, DateTime endTime, int maxValues, CancellationToken ct)
{
HistoryReadRawCount++;
if (ThrowOnHistoryReadRaw)
throw new ServiceResultException(StatusCodes.BadHistoryOperationUnsupported, "History not supported");
return Task.FromResult<IReadOnlyList<DataValue>>(HistoryReadRawResponse);
}
/// <inheritdoc />
public Task<IReadOnlyList<DataValue>> HistoryReadAggregateAsync(
NodeId nodeId, DateTime startTime, DateTime endTime, NodeId aggregateId, double intervalMs,
CancellationToken ct)
{
HistoryReadAggregateCount++;
if (ThrowOnHistoryReadAggregate)
throw new ServiceResultException(StatusCodes.BadHistoryOperationUnsupported, "History not supported");
return Task.FromResult<IReadOnlyList<DataValue>>(HistoryReadAggregateResponse);
}
/// <inheritdoc />
public Task<ISubscriptionAdapter> CreateSubscriptionAsync(int publishingIntervalMs, CancellationToken ct)
{
var sub = NextSubscription ?? new FakeSubscriptionAdapter();
NextSubscription = null;
_createdSubscriptions.Add(sub);
return Task.FromResult<ISubscriptionAdapter>(sub);
}
/// <inheritdoc />
public Task<IList<object>?> CallMethodAsync(NodeId objectId, NodeId methodId, object[] inputArguments,
CancellationToken ct = default)
{
return Task.FromResult<IList<object>?>(null);
}
/// <inheritdoc />
public Task CloseAsync(CancellationToken ct)
{
Closed = true;
Connected = false;
return Task.CompletedTask;
}
/// <summary>
/// Marks the fake session as disposed so tests can verify cleanup after disconnect or failover.
/// </summary>
public void Dispose()
{
Disposed = true;
Connected = false;
}
/// <summary>
/// Simulates a keep-alive event.
/// </summary>
public void SimulateKeepAlive(bool isGood)
{
_keepAliveCallback?.Invoke(isGood);
}
}

View File

@@ -0,0 +1,52 @@
using Opc.Ua;
using ZB.MOM.WW.OtOpcUa.Client.Shared.Adapters;
namespace ZB.MOM.WW.OtOpcUa.Client.Shared.Tests.Fakes;
internal sealed class FakeSessionFactory : ISessionFactory
{
private readonly List<FakeSessionAdapter> _createdSessions = [];
private readonly Queue<FakeSessionAdapter> _sessions = new();
public int CreateCallCount { get; private set; }
public bool ThrowOnCreate { get; set; }
public string? LastEndpointUrl { get; private set; }
public IReadOnlyList<FakeSessionAdapter> CreatedSessions => _createdSessions;
public Task<ISessionAdapter> CreateSessionAsync(
ApplicationConfiguration config, EndpointDescription endpoint, string sessionName,
uint sessionTimeoutMs, UserIdentity identity, CancellationToken ct)
{
CreateCallCount++;
LastEndpointUrl = endpoint.EndpointUrl;
if (ThrowOnCreate)
throw new InvalidOperationException("FakeSessionFactory configured to fail.");
FakeSessionAdapter session;
if (_sessions.Count > 0)
session = _sessions.Dequeue();
else
session = new FakeSessionAdapter
{
EndpointUrl = endpoint.EndpointUrl,
ServerName = endpoint.Server?.ApplicationName?.Text ?? "FakeServer",
SecurityMode = endpoint.SecurityMode.ToString(),
SecurityPolicyUri = endpoint.SecurityPolicyUri ?? string.Empty
};
// Ensure endpoint URL matches
session.EndpointUrl = endpoint.EndpointUrl;
_createdSessions.Add(session);
return Task.FromResult<ISessionAdapter>(session);
}
/// <summary>
/// Enqueues a session adapter to be returned on the next call to CreateSessionAsync.
/// </summary>
public void EnqueueSession(FakeSessionAdapter session)
{
_sessions.Enqueue(session);
}
}

View File

@@ -0,0 +1,111 @@
using Opc.Ua;
using ZB.MOM.WW.OtOpcUa.Client.Shared.Adapters;
namespace ZB.MOM.WW.OtOpcUa.Client.Shared.Tests.Fakes;
/// <summary>
/// Test double for <see cref="ISubscriptionAdapter" /> used to drive monitored-item behavior in shared-client tests.
/// </summary>
internal sealed class FakeSubscriptionAdapter : ISubscriptionAdapter
{
private readonly
Dictionary<uint, (NodeId NodeId, Action<string, DataValue>? DataCallback, Action<EventFieldList>? EventCallback
)> _items = new();
private uint _nextHandle = 100;
/// <summary>
/// Gets a value indicating whether the fake subscription has been deleted.
/// </summary>
public bool Deleted { get; private set; }
/// <summary>
/// Gets a value indicating whether a condition refresh was requested by the client under test.
/// </summary>
public bool ConditionRefreshCalled { get; private set; }
/// <summary>
/// Gets or sets a value indicating whether condition refresh should throw to simulate unsupported servers.
/// </summary>
public bool ThrowOnConditionRefresh { get; set; }
public int AddDataChangeCount { get; private set; }
public int AddEventCount { get; private set; }
public int RemoveCount { get; private set; }
/// <summary>
/// Gets the handles of all active items.
/// </summary>
public IReadOnlyCollection<uint> ActiveHandles => _items.Keys.ToList();
/// <inheritdoc />
public uint SubscriptionId { get; set; } = 42;
/// <inheritdoc />
public Task<uint> AddDataChangeMonitoredItemAsync(NodeId nodeId, int samplingIntervalMs,
Action<string, DataValue> onDataChange, CancellationToken ct)
{
AddDataChangeCount++;
var handle = _nextHandle++;
_items[handle] = (nodeId, onDataChange, null);
return Task.FromResult(handle);
}
/// <inheritdoc />
public Task RemoveMonitoredItemAsync(uint clientHandle, CancellationToken ct)
{
RemoveCount++;
_items.Remove(clientHandle);
return Task.CompletedTask;
}
/// <inheritdoc />
public Task<uint> AddEventMonitoredItemAsync(NodeId nodeId, int samplingIntervalMs, EventFilter filter,
Action<EventFieldList> onEvent, CancellationToken ct)
{
AddEventCount++;
var handle = _nextHandle++;
_items[handle] = (nodeId, null, onEvent);
return Task.FromResult(handle);
}
/// <inheritdoc />
public Task ConditionRefreshAsync(CancellationToken ct)
{
ConditionRefreshCalled = true;
if (ThrowOnConditionRefresh)
throw new InvalidOperationException("Condition refresh not supported");
return Task.CompletedTask;
}
/// <inheritdoc />
public Task DeleteAsync(CancellationToken ct)
{
Deleted = true;
_items.Clear();
return Task.CompletedTask;
}
/// <summary>
/// Clears tracked monitored items when the fake subscription is disposed by the client under test.
/// </summary>
public void Dispose()
{
_items.Clear();
}
/// <summary>
/// Simulates a data change notification for testing.
/// </summary>
public void SimulateDataChange(uint handle, DataValue value)
{
if (_items.TryGetValue(handle, out var item) && item.DataCallback != null)
item.DataCallback(item.NodeId.ToString(), value);
}
/// <summary>
/// Simulates an event notification for testing.
/// </summary>
public void SimulateEvent(uint handle, EventFieldList eventFields)
{
if (_items.TryGetValue(handle, out var item) && item.EventCallback != null) item.EventCallback(eventFields);
}
}

View File

@@ -0,0 +1,75 @@
using Opc.Ua;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Client.Shared.Helpers;
using ZB.MOM.WW.OtOpcUa.Client.Shared.Models;
namespace ZB.MOM.WW.OtOpcUa.Client.Shared.Tests.Helpers;
public class AggregateTypeMapperTests
{
[Theory]
[InlineData(AggregateType.Average)]
[InlineData(AggregateType.Minimum)]
[InlineData(AggregateType.Maximum)]
[InlineData(AggregateType.Count)]
[InlineData(AggregateType.Start)]
[InlineData(AggregateType.End)]
[InlineData(AggregateType.StandardDeviation)]
public void ToNodeId_ReturnsNonNullForAllValues(AggregateType aggregate)
{
var nodeId = AggregateTypeMapper.ToNodeId(aggregate);
nodeId.ShouldNotBeNull();
nodeId.IsNullNodeId.ShouldBeFalse();
}
[Fact]
public void ToNodeId_Average_MapsCorrectly()
{
AggregateTypeMapper.ToNodeId(AggregateType.Average).ShouldBe(ObjectIds.AggregateFunction_Average);
}
[Fact]
public void ToNodeId_Minimum_MapsCorrectly()
{
AggregateTypeMapper.ToNodeId(AggregateType.Minimum).ShouldBe(ObjectIds.AggregateFunction_Minimum);
}
[Fact]
public void ToNodeId_Maximum_MapsCorrectly()
{
AggregateTypeMapper.ToNodeId(AggregateType.Maximum).ShouldBe(ObjectIds.AggregateFunction_Maximum);
}
[Fact]
public void ToNodeId_Count_MapsCorrectly()
{
AggregateTypeMapper.ToNodeId(AggregateType.Count).ShouldBe(ObjectIds.AggregateFunction_Count);
}
[Fact]
public void ToNodeId_Start_MapsCorrectly()
{
AggregateTypeMapper.ToNodeId(AggregateType.Start).ShouldBe(ObjectIds.AggregateFunction_Start);
}
[Fact]
public void ToNodeId_End_MapsCorrectly()
{
AggregateTypeMapper.ToNodeId(AggregateType.End).ShouldBe(ObjectIds.AggregateFunction_End);
}
[Fact]
public void ToNodeId_StandardDeviation_MapsCorrectly()
{
AggregateTypeMapper.ToNodeId(AggregateType.StandardDeviation)
.ShouldBe(ObjectIds.AggregateFunction_StandardDeviationPopulation);
}
[Fact]
public void ToNodeId_InvalidValue_Throws()
{
Should.Throw<ArgumentOutOfRangeException>(() =>
AggregateTypeMapper.ToNodeId((AggregateType)99));
}
}

View File

@@ -0,0 +1,110 @@
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Client.Shared.Helpers;
namespace ZB.MOM.WW.OtOpcUa.Client.Shared.Tests.Helpers;
public class FailoverUrlParserTests
{
[Fact]
public void Parse_CsvNull_ReturnsPrimaryOnly()
{
var result = FailoverUrlParser.Parse("opc.tcp://primary:4840", (string?)null);
result.ShouldBe(["opc.tcp://primary:4840"]);
}
[Fact]
public void Parse_CsvEmpty_ReturnsPrimaryOnly()
{
var result = FailoverUrlParser.Parse("opc.tcp://primary:4840", "");
result.ShouldBe(["opc.tcp://primary:4840"]);
}
[Fact]
public void Parse_CsvWhitespace_ReturnsPrimaryOnly()
{
var result = FailoverUrlParser.Parse("opc.tcp://primary:4840", " ");
result.ShouldBe(["opc.tcp://primary:4840"]);
}
[Fact]
public void Parse_SingleFailover_ReturnsBoth()
{
var result = FailoverUrlParser.Parse("opc.tcp://primary:4840", "opc.tcp://backup:4840");
result.ShouldBe(["opc.tcp://primary:4840", "opc.tcp://backup:4840"]);
}
[Fact]
public void Parse_MultipleFailovers_ReturnsAll()
{
var result = FailoverUrlParser.Parse("opc.tcp://primary:4840", "opc.tcp://backup1:4840,opc.tcp://backup2:4840");
result.ShouldBe(["opc.tcp://primary:4840", "opc.tcp://backup1:4840", "opc.tcp://backup2:4840"]);
}
[Fact]
public void Parse_TrimsWhitespace()
{
var result = FailoverUrlParser.Parse("opc.tcp://primary:4840", " opc.tcp://backup:4840 ");
result.ShouldBe(["opc.tcp://primary:4840", "opc.tcp://backup:4840"]);
}
[Fact]
public void Parse_DeduplicatesPrimaryInFailoverList()
{
var result = FailoverUrlParser.Parse("opc.tcp://primary:4840", "opc.tcp://primary:4840,opc.tcp://backup:4840");
result.ShouldBe(["opc.tcp://primary:4840", "opc.tcp://backup:4840"]);
}
[Fact]
public void Parse_DeduplicatesCaseInsensitive()
{
var result = FailoverUrlParser.Parse("opc.tcp://Primary:4840", "opc.tcp://primary:4840");
result.ShouldBe(["opc.tcp://Primary:4840"]);
}
[Fact]
public void Parse_ArrayNull_ReturnsPrimaryOnly()
{
var result = FailoverUrlParser.Parse("opc.tcp://primary:4840", (string[]?)null);
result.ShouldBe(["opc.tcp://primary:4840"]);
}
[Fact]
public void Parse_ArrayEmpty_ReturnsPrimaryOnly()
{
var result = FailoverUrlParser.Parse("opc.tcp://primary:4840", []);
result.ShouldBe(["opc.tcp://primary:4840"]);
}
[Fact]
public void Parse_ArrayWithUrls_ReturnsAll()
{
var result = FailoverUrlParser.Parse("opc.tcp://primary:4840",
["opc.tcp://backup1:4840", "opc.tcp://backup2:4840"]);
result.ShouldBe(["opc.tcp://primary:4840", "opc.tcp://backup1:4840", "opc.tcp://backup2:4840"]);
}
[Fact]
public void Parse_ArrayDeduplicates()
{
var result = FailoverUrlParser.Parse("opc.tcp://primary:4840",
["opc.tcp://primary:4840", "opc.tcp://backup:4840"]);
result.ShouldBe(["opc.tcp://primary:4840", "opc.tcp://backup:4840"]);
}
[Fact]
public void Parse_ArrayTrimsWhitespace()
{
var result = FailoverUrlParser.Parse("opc.tcp://primary:4840",
[" opc.tcp://backup:4840 "]);
result.ShouldBe(["opc.tcp://primary:4840", "opc.tcp://backup:4840"]);
}
[Fact]
public void Parse_ArraySkipsNullAndEmpty()
{
var result = FailoverUrlParser.Parse("opc.tcp://primary:4840",
[null!, "", "opc.tcp://backup:4840"]);
result.ShouldBe(["opc.tcp://primary:4840", "opc.tcp://backup:4840"]);
}
}

View File

@@ -0,0 +1,58 @@
using Opc.Ua;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Client.Shared.Helpers;
using ZB.MOM.WW.OtOpcUa.Client.Shared.Models;
namespace ZB.MOM.WW.OtOpcUa.Client.Shared.Tests.Helpers;
public class SecurityModeMapperTests
{
[Theory]
[InlineData(SecurityMode.None, MessageSecurityMode.None)]
[InlineData(SecurityMode.Sign, MessageSecurityMode.Sign)]
[InlineData(SecurityMode.SignAndEncrypt, MessageSecurityMode.SignAndEncrypt)]
public void ToMessageSecurityMode_MapsCorrectly(SecurityMode input, MessageSecurityMode expected)
{
SecurityModeMapper.ToMessageSecurityMode(input).ShouldBe(expected);
}
[Fact]
public void ToMessageSecurityMode_InvalidValue_Throws()
{
Should.Throw<ArgumentOutOfRangeException>(() =>
SecurityModeMapper.ToMessageSecurityMode((SecurityMode)99));
}
[Theory]
[InlineData("none", SecurityMode.None)]
[InlineData("None", SecurityMode.None)]
[InlineData("NONE", SecurityMode.None)]
[InlineData("sign", SecurityMode.Sign)]
[InlineData("Sign", SecurityMode.Sign)]
[InlineData("encrypt", SecurityMode.SignAndEncrypt)]
[InlineData("signandencrypt", SecurityMode.SignAndEncrypt)]
[InlineData("SignAndEncrypt", SecurityMode.SignAndEncrypt)]
public void FromString_ParsesCorrectly(string input, SecurityMode expected)
{
SecurityModeMapper.FromString(input).ShouldBe(expected);
}
[Fact]
public void FromString_WithWhitespace_ParsesCorrectly()
{
SecurityModeMapper.FromString(" sign ").ShouldBe(SecurityMode.Sign);
}
[Fact]
public void FromString_UnknownValue_Throws()
{
Should.Throw<ArgumentException>(() => SecurityModeMapper.FromString("invalid"));
}
[Fact]
public void FromString_Null_DefaultsToNone()
{
SecurityModeMapper.FromString(null!).ShouldBe(SecurityMode.None);
}
}

View File

@@ -0,0 +1,110 @@
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Client.Shared.Helpers;
namespace ZB.MOM.WW.OtOpcUa.Client.Shared.Tests.Helpers;
public class ValueConverterTests
{
[Fact]
public void ConvertValue_Bool_True()
{
ValueConverter.ConvertValue("True", true).ShouldBe(true);
}
[Fact]
public void ConvertValue_Bool_False()
{
ValueConverter.ConvertValue("False", false).ShouldBe(false);
}
[Fact]
public void ConvertValue_Byte()
{
ValueConverter.ConvertValue("255", (byte)0).ShouldBe((byte)255);
}
[Fact]
public void ConvertValue_Short()
{
ValueConverter.ConvertValue("-100", (short)0).ShouldBe((short)-100);
}
[Fact]
public void ConvertValue_UShort()
{
ValueConverter.ConvertValue("65535", (ushort)0).ShouldBe((ushort)65535);
}
[Fact]
public void ConvertValue_Int()
{
ValueConverter.ConvertValue("42", 0).ShouldBe(42);
}
[Fact]
public void ConvertValue_UInt()
{
ValueConverter.ConvertValue("42", 0u).ShouldBe(42u);
}
[Fact]
public void ConvertValue_Long()
{
ValueConverter.ConvertValue("9999999999", 0L).ShouldBe(9999999999L);
}
[Fact]
public void ConvertValue_ULong()
{
ValueConverter.ConvertValue("18446744073709551615", 0UL).ShouldBe(ulong.MaxValue);
}
[Fact]
public void ConvertValue_Float()
{
ValueConverter.ConvertValue("3.14", 0f).ShouldBe(3.14f);
}
[Fact]
public void ConvertValue_Double()
{
ValueConverter.ConvertValue("3.14159", 0.0).ShouldBe(3.14159);
}
[Fact]
public void ConvertValue_String_WhenCurrentIsString()
{
ValueConverter.ConvertValue("hello", "").ShouldBe("hello");
}
[Fact]
public void ConvertValue_String_WhenCurrentIsNull()
{
ValueConverter.ConvertValue("hello", null).ShouldBe("hello");
}
[Fact]
public void ConvertValue_String_WhenCurrentIsUnknownType()
{
ValueConverter.ConvertValue("hello", new object()).ShouldBe("hello");
}
[Fact]
public void ConvertValue_InvalidBool_Throws()
{
Should.Throw<FormatException>(() => ValueConverter.ConvertValue("notabool", true));
}
[Fact]
public void ConvertValue_InvalidInt_Throws()
{
Should.Throw<FormatException>(() => ValueConverter.ConvertValue("notanint", 0));
}
[Fact]
public void ConvertValue_Overflow_Throws()
{
Should.Throw<OverflowException>(() => ValueConverter.ConvertValue("256", (byte)0));
}
}

View File

@@ -0,0 +1,95 @@
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Client.Shared.Models;
namespace ZB.MOM.WW.OtOpcUa.Client.Shared.Tests.Models;
public class ConnectionSettingsTests
{
[Fact]
public void Defaults_AreCorrect()
{
var settings = new ConnectionSettings();
settings.EndpointUrl.ShouldBe(string.Empty);
settings.FailoverUrls.ShouldBeNull();
settings.Username.ShouldBeNull();
settings.Password.ShouldBeNull();
settings.SecurityMode.ShouldBe(SecurityMode.None);
settings.SessionTimeoutSeconds.ShouldBe(60);
settings.AutoAcceptCertificates.ShouldBeTrue();
settings.CertificateStorePath.ShouldContain("LmxOpcUaClient");
settings.CertificateStorePath.ShouldContain("pki");
}
[Fact]
public void Validate_ThrowsOnNullEndpointUrl()
{
var settings = new ConnectionSettings { EndpointUrl = null! };
Should.Throw<ArgumentException>(() => settings.Validate())
.ParamName.ShouldBe("EndpointUrl");
}
[Fact]
public void Validate_ThrowsOnEmptyEndpointUrl()
{
var settings = new ConnectionSettings { EndpointUrl = "" };
Should.Throw<ArgumentException>(() => settings.Validate())
.ParamName.ShouldBe("EndpointUrl");
}
[Fact]
public void Validate_ThrowsOnWhitespaceEndpointUrl()
{
var settings = new ConnectionSettings { EndpointUrl = " " };
Should.Throw<ArgumentException>(() => settings.Validate())
.ParamName.ShouldBe("EndpointUrl");
}
[Fact]
public void Validate_ThrowsOnZeroTimeout()
{
var settings = new ConnectionSettings
{
EndpointUrl = "opc.tcp://localhost:4840",
SessionTimeoutSeconds = 0
};
Should.Throw<ArgumentException>(() => settings.Validate())
.ParamName.ShouldBe("SessionTimeoutSeconds");
}
[Fact]
public void Validate_ThrowsOnNegativeTimeout()
{
var settings = new ConnectionSettings
{
EndpointUrl = "opc.tcp://localhost:4840",
SessionTimeoutSeconds = -1
};
Should.Throw<ArgumentException>(() => settings.Validate())
.ParamName.ShouldBe("SessionTimeoutSeconds");
}
[Fact]
public void Validate_ThrowsOnTimeoutAbove3600()
{
var settings = new ConnectionSettings
{
EndpointUrl = "opc.tcp://localhost:4840",
SessionTimeoutSeconds = 3601
};
Should.Throw<ArgumentException>(() => settings.Validate())
.ParamName.ShouldBe("SessionTimeoutSeconds");
}
[Fact]
public void Validate_SucceedsWithValidSettings()
{
var settings = new ConnectionSettings
{
EndpointUrl = "opc.tcp://localhost:4840",
SessionTimeoutSeconds = 120
};
Should.NotThrow(() => settings.Validate());
}
}

View File

@@ -0,0 +1,130 @@
using Opc.Ua;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Client.Shared.Models;
using BrowseResult = ZB.MOM.WW.OtOpcUa.Client.Shared.Models.BrowseResult;
namespace ZB.MOM.WW.OtOpcUa.Client.Shared.Tests.Models;
public class ModelConstructionTests
{
[Fact]
public void BrowseResult_ConstructsCorrectly()
{
var result = new BrowseResult("ns=2;s=MyNode", "MyNode", "Variable", true);
result.NodeId.ShouldBe("ns=2;s=MyNode");
result.DisplayName.ShouldBe("MyNode");
result.NodeClass.ShouldBe("Variable");
result.HasChildren.ShouldBeTrue();
}
[Fact]
public void BrowseResult_WithoutChildren()
{
var result = new BrowseResult("ns=2;s=Leaf", "Leaf", "Variable", false);
result.HasChildren.ShouldBeFalse();
}
[Fact]
public void AlarmEventArgs_ConstructsCorrectly()
{
var time = new DateTime(2026, 1, 15, 10, 30, 0, DateTimeKind.Utc);
var args = new AlarmEventArgs("Source1", "HighTemp", 500, "Temperature high", true, true, false, time);
args.SourceName.ShouldBe("Source1");
args.ConditionName.ShouldBe("HighTemp");
args.Severity.ShouldBe((ushort)500);
args.Message.ShouldBe("Temperature high");
args.Retain.ShouldBeTrue();
args.ActiveState.ShouldBeTrue();
args.AckedState.ShouldBeFalse();
args.Time.ShouldBe(time);
}
[Fact]
public void RedundancyInfo_ConstructsCorrectly()
{
var uris = new[] { "urn:server1", "urn:server2" };
var info = new RedundancyInfo("Warm", 200, uris, "urn:server1");
info.Mode.ShouldBe("Warm");
info.ServiceLevel.ShouldBe((byte)200);
info.ServerUris.ShouldBe(uris);
info.ApplicationUri.ShouldBe("urn:server1");
}
[Fact]
public void RedundancyInfo_WithEmptyUris()
{
var info = new RedundancyInfo("None", 0, [], string.Empty);
info.ServerUris.ShouldBeEmpty();
info.ApplicationUri.ShouldBeEmpty();
}
[Fact]
public void DataChangedEventArgs_ConstructsCorrectly()
{
var value = new DataValue(new Variant(42), StatusCodes.Good);
var args = new DataChangedEventArgs("ns=2;s=Temp", value);
args.NodeId.ShouldBe("ns=2;s=Temp");
args.Value.ShouldBe(value);
args.Value.Value.ShouldBe(42);
}
[Fact]
public void ConnectionStateChangedEventArgs_ConstructsCorrectly()
{
var args = new ConnectionStateChangedEventArgs(
ConnectionState.Disconnected, ConnectionState.Connected, "opc.tcp://localhost:4840");
args.OldState.ShouldBe(ConnectionState.Disconnected);
args.NewState.ShouldBe(ConnectionState.Connected);
args.EndpointUrl.ShouldBe("opc.tcp://localhost:4840");
}
[Fact]
public void ConnectionInfo_ConstructsCorrectly()
{
var info = new ConnectionInfo(
"opc.tcp://localhost:4840",
"TestServer",
"None",
"http://opcfoundation.org/UA/SecurityPolicy#None",
"ns=0;i=12345",
"TestSession");
info.EndpointUrl.ShouldBe("opc.tcp://localhost:4840");
info.ServerName.ShouldBe("TestServer");
info.SecurityMode.ShouldBe("None");
info.SecurityPolicyUri.ShouldBe("http://opcfoundation.org/UA/SecurityPolicy#None");
info.SessionId.ShouldBe("ns=0;i=12345");
info.SessionName.ShouldBe("TestSession");
}
[Fact]
public void SecurityMode_Enum_HasExpectedValues()
{
Enum.GetValues<SecurityMode>().Length.ShouldBe(3);
((int)SecurityMode.None).ShouldBe(0);
((int)SecurityMode.Sign).ShouldBe(1);
((int)SecurityMode.SignAndEncrypt).ShouldBe(2);
}
[Fact]
public void ConnectionState_Enum_HasExpectedValues()
{
Enum.GetValues<ConnectionState>().Length.ShouldBe(4);
((int)ConnectionState.Disconnected).ShouldBe(0);
((int)ConnectionState.Connecting).ShouldBe(1);
((int)ConnectionState.Connected).ShouldBe(2);
((int)ConnectionState.Reconnecting).ShouldBe(3);
}
[Fact]
public void AggregateType_Enum_HasExpectedValues()
{
Enum.GetValues<AggregateType>().Length.ShouldBe(7);
}
}

View File

@@ -0,0 +1,978 @@
using Opc.Ua;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Client.Shared.Models;
using ZB.MOM.WW.OtOpcUa.Client.Shared.Tests.Fakes;
namespace ZB.MOM.WW.OtOpcUa.Client.Shared.Tests;
/// <summary>
/// Verifies the shared OPC UA client service behaviors for connection management, browsing, subscriptions, history, alarms, and redundancy.
/// </summary>
public class OpcUaClientServiceTests : IDisposable
{
private readonly FakeApplicationConfigurationFactory _configFactory = new();
private readonly FakeEndpointDiscovery _endpointDiscovery = new();
private readonly OpcUaClientService _service;
private readonly FakeSessionFactory _sessionFactory = new();
public OpcUaClientServiceTests()
{
_service = new OpcUaClientService(_configFactory, _endpointDiscovery, _sessionFactory);
}
/// <summary>
/// Releases the shared client service after each test so session and subscription state do not leak between scenarios.
/// </summary>
public void Dispose()
{
_service.Dispose();
}
private ConnectionSettings ValidSettings(string url = "opc.tcp://localhost:4840")
{
return new ConnectionSettings
{
EndpointUrl = url,
SessionTimeoutSeconds = 60
};
}
// --- Connection tests ---
/// <summary>
/// Verifies that a valid connection request returns populated connection metadata and marks the client as connected.
/// </summary>
[Fact]
public async Task ConnectAsync_ValidSettings_ReturnsConnectionInfo()
{
var info = await _service.ConnectAsync(ValidSettings());
info.ShouldNotBeNull();
info.EndpointUrl.ShouldBe("opc.tcp://localhost:4840");
_service.IsConnected.ShouldBeTrue();
_service.CurrentConnectionInfo.ShouldBe(info);
}
/// <summary>
/// Verifies that invalid connection settings fail validation before any OPC UA session is created.
/// </summary>
[Fact]
public async Task ConnectAsync_InvalidSettings_ThrowsBeforeCreatingSession()
{
var settings = new ConnectionSettings { EndpointUrl = "" };
await Should.ThrowAsync<ArgumentException>(() => _service.ConnectAsync(settings));
_sessionFactory.CreateCallCount.ShouldBe(0);
_service.IsConnected.ShouldBeFalse();
}
/// <summary>
/// Verifies that server and security details from the session are copied into the exposed connection info.
/// </summary>
[Fact]
public async Task ConnectAsync_PopulatesConnectionInfo()
{
var session = new FakeSessionAdapter
{
ServerName = "MyServer",
SecurityMode = "Sign",
SecurityPolicyUri = "http://opcfoundation.org/UA/SecurityPolicy#Basic256Sha256",
SessionId = "ns=0;i=999",
SessionName = "TestSession"
};
_sessionFactory.EnqueueSession(session);
var info = await _service.ConnectAsync(ValidSettings());
info.ServerName.ShouldBe("MyServer");
info.SecurityMode.ShouldBe("Sign");
info.SecurityPolicyUri.ShouldBe("http://opcfoundation.org/UA/SecurityPolicy#Basic256Sha256");
info.SessionId.ShouldBe("ns=0;i=999");
info.SessionName.ShouldBe("TestSession");
}
/// <summary>
/// Verifies that connection-state transitions are raised for the connecting and connected phases.
/// </summary>
[Fact]
public async Task ConnectAsync_RaisesConnectionStateChangedEvents()
{
var events = new List<ConnectionStateChangedEventArgs>();
_service.ConnectionStateChanged += (_, e) => events.Add(e);
await _service.ConnectAsync(ValidSettings());
events.Count.ShouldBe(2);
events[0].OldState.ShouldBe(ConnectionState.Disconnected);
events[0].NewState.ShouldBe(ConnectionState.Connecting);
events[1].OldState.ShouldBe(ConnectionState.Connecting);
events[1].NewState.ShouldBe(ConnectionState.Connected);
}
/// <summary>
/// Verifies that a failed session creation leaves the client in the disconnected state.
/// </summary>
[Fact]
public async Task ConnectAsync_SessionFactoryFails_TransitionsToDisconnected()
{
_sessionFactory.ThrowOnCreate = true;
var events = new List<ConnectionStateChangedEventArgs>();
_service.ConnectionStateChanged += (_, e) => events.Add(e);
await Should.ThrowAsync<InvalidOperationException>(() => _service.ConnectAsync(ValidSettings()));
_service.IsConnected.ShouldBeFalse();
events.Last().NewState.ShouldBe(ConnectionState.Disconnected);
}
/// <summary>
/// Verifies that username and password settings are passed through to the session-creation pipeline.
/// </summary>
[Fact]
public async Task ConnectAsync_WithUsername_PassesThroughToFactory()
{
var settings = ValidSettings();
settings.Username = "admin";
settings.Password = "secret";
await _service.ConnectAsync(settings);
_configFactory.LastSettings!.Username.ShouldBe("admin");
_configFactory.LastSettings!.Password.ShouldBe("secret");
}
// --- Disconnect tests ---
/// <summary>
/// Verifies that disconnect closes the active session and clears exposed connection state.
/// </summary>
[Fact]
public async Task DisconnectAsync_WhenConnected_ClosesSession()
{
await _service.ConnectAsync(ValidSettings());
var session = _sessionFactory.CreatedSessions[0];
await _service.DisconnectAsync();
session.Closed.ShouldBeTrue();
_service.IsConnected.ShouldBeFalse();
_service.CurrentConnectionInfo.ShouldBeNull();
}
/// <summary>
/// Verifies that disconnect is safe to call when no server session is active.
/// </summary>
[Fact]
public async Task DisconnectAsync_WhenNotConnected_IsIdempotent()
{
await _service.DisconnectAsync(); // Should not throw
_service.IsConnected.ShouldBeFalse();
}
/// <summary>
/// Verifies that repeated disconnect calls do not throw after cleanup has already run.
/// </summary>
[Fact]
public async Task DisconnectAsync_CalledTwice_IsIdempotent()
{
await _service.ConnectAsync(ValidSettings());
await _service.DisconnectAsync();
await _service.DisconnectAsync(); // Should not throw
}
// --- Read tests ---
/// <summary>
/// Verifies that a connected client can read the current value of a node through the session adapter.
/// </summary>
[Fact]
public async Task ReadValueAsync_WhenConnected_ReturnsValue()
{
var session = new FakeSessionAdapter
{
ReadResponse = new DataValue(new Variant(42), StatusCodes.Good)
};
_sessionFactory.EnqueueSession(session);
await _service.ConnectAsync(ValidSettings());
var result = await _service.ReadValueAsync(new NodeId("ns=2;s=MyNode"));
result.Value.ShouldBe(42);
session.ReadCount.ShouldBe(1);
}
/// <summary>
/// Verifies that reads are rejected when the client is not connected to a server.
/// </summary>
[Fact]
public async Task ReadValueAsync_WhenDisconnected_Throws()
{
await Should.ThrowAsync<InvalidOperationException>(() =>
_service.ReadValueAsync(new NodeId("ns=2;s=MyNode")));
}
/// <summary>
/// Verifies that session-level read failures are surfaced to callers instead of being swallowed.
/// </summary>
[Fact]
public async Task ReadValueAsync_SessionThrows_PropagatesException()
{
var session = new FakeSessionAdapter { ThrowOnRead = true };
_sessionFactory.EnqueueSession(session);
await _service.ConnectAsync(ValidSettings());
await Should.ThrowAsync<ServiceResultException>(() =>
_service.ReadValueAsync(new NodeId("ns=2;s=MyNode")));
}
// --- Write tests ---
/// <summary>
/// Verifies that writes succeed through the session adapter when the client is connected.
/// </summary>
[Fact]
public async Task WriteValueAsync_WhenConnected_WritesValue()
{
var session = new FakeSessionAdapter
{
ReadResponse = new DataValue(new Variant(0), StatusCodes.Good),
WriteResponse = StatusCodes.Good
};
_sessionFactory.EnqueueSession(session);
await _service.ConnectAsync(ValidSettings());
var result = await _service.WriteValueAsync(new NodeId("ns=2;s=MyNode"), 42);
result.ShouldBe(StatusCodes.Good);
session.WriteCount.ShouldBe(1);
}
/// <summary>
/// Verifies that string inputs are coerced to the node's current data type before writing.
/// </summary>
[Fact]
public async Task WriteValueAsync_StringValue_CoercesToTargetType()
{
var session = new FakeSessionAdapter
{
ReadResponse = new DataValue(new Variant(0), StatusCodes.Good) // int type
};
_sessionFactory.EnqueueSession(session);
await _service.ConnectAsync(ValidSettings());
await _service.WriteValueAsync(new NodeId("ns=2;s=MyNode"), "42");
session.WriteCount.ShouldBe(1);
session.ReadCount.ShouldBe(1); // Read for type inference
}
/// <summary>
/// Verifies that non-string values are written directly without an extra type-inference read.
/// </summary>
[Fact]
public async Task WriteValueAsync_NonStringValue_WritesDirectly()
{
var session = new FakeSessionAdapter();
_sessionFactory.EnqueueSession(session);
await _service.ConnectAsync(ValidSettings());
await _service.WriteValueAsync(new NodeId("ns=2;s=MyNode"), 42);
session.WriteCount.ShouldBe(1);
session.ReadCount.ShouldBe(0); // No read for non-string values
}
/// <summary>
/// Verifies that writes are rejected when the client is disconnected.
/// </summary>
[Fact]
public async Task WriteValueAsync_WhenDisconnected_Throws()
{
await Should.ThrowAsync<InvalidOperationException>(() =>
_service.WriteValueAsync(new NodeId("ns=2;s=MyNode"), 42));
}
// --- Browse tests ---
/// <summary>
/// Verifies that browse results are mapped into the client browse model used by CLI and UI consumers.
/// </summary>
[Fact]
public async Task BrowseAsync_WhenConnected_ReturnsMappedResults()
{
var session = new FakeSessionAdapter
{
BrowseResponse =
[
new ReferenceDescription
{
NodeId = new ExpandedNodeId("ns=2;s=Child1"),
DisplayName = new LocalizedText("Child1"),
NodeClass = NodeClass.Variable
}
]
};
_sessionFactory.EnqueueSession(session);
await _service.ConnectAsync(ValidSettings());
var results = await _service.BrowseAsync();
results.Count.ShouldBe(1);
results[0].DisplayName.ShouldBe("Child1");
results[0].NodeClass.ShouldBe("Variable");
results[0].HasChildren.ShouldBeFalse(); // Variable nodes don't check HasChildren
}
/// <summary>
/// Verifies that a null browse root defaults to the OPC UA Objects folder.
/// </summary>
[Fact]
public async Task BrowseAsync_NullParent_UsesObjectsFolder()
{
var session = new FakeSessionAdapter
{
BrowseResponse = []
};
_sessionFactory.EnqueueSession(session);
await _service.ConnectAsync(ValidSettings());
await _service.BrowseAsync();
session.BrowseCount.ShouldBe(1);
}
/// <summary>
/// Verifies that object nodes trigger child-detection checks so the client can mark expandable branches.
/// </summary>
[Fact]
public async Task BrowseAsync_ObjectNode_ChecksHasChildren()
{
var session = new FakeSessionAdapter
{
BrowseResponse =
[
new ReferenceDescription
{
NodeId = new ExpandedNodeId("ns=2;s=Folder1"),
DisplayName = new LocalizedText("Folder1"),
NodeClass = NodeClass.Object
}
],
HasChildrenResponse = true
};
_sessionFactory.EnqueueSession(session);
await _service.ConnectAsync(ValidSettings());
var results = await _service.BrowseAsync();
results[0].HasChildren.ShouldBeTrue();
session.HasChildrenCount.ShouldBe(1);
}
/// <summary>
/// Verifies that browse continuation points are followed so multi-page address-space branches are fully returned.
/// </summary>
[Fact]
public async Task BrowseAsync_WithContinuationPoint_FollowsIt()
{
var session = new FakeSessionAdapter
{
BrowseResponse =
[
new ReferenceDescription
{
NodeId = new ExpandedNodeId("ns=2;s=A"),
DisplayName = new LocalizedText("A"),
NodeClass = NodeClass.Variable
}
],
BrowseContinuationPoint = [1, 2, 3],
BrowseNextResponse =
[
new ReferenceDescription
{
NodeId = new ExpandedNodeId("ns=2;s=B"),
DisplayName = new LocalizedText("B"),
NodeClass = NodeClass.Variable
}
],
BrowseNextContinuationPoint = null
};
_sessionFactory.EnqueueSession(session);
await _service.ConnectAsync(ValidSettings());
var results = await _service.BrowseAsync();
results.Count.ShouldBe(2);
session.BrowseNextCount.ShouldBe(1);
}
/// <summary>
/// Verifies that browse requests are rejected when the client is disconnected.
/// </summary>
[Fact]
public async Task BrowseAsync_WhenDisconnected_Throws()
{
await Should.ThrowAsync<InvalidOperationException>(() => _service.BrowseAsync());
}
// --- Subscribe tests ---
/// <summary>
/// Verifies that subscribing to a node creates a monitored item on a data-change subscription.
/// </summary>
[Fact]
public async Task SubscribeAsync_CreatesSubscription()
{
var session = new FakeSessionAdapter();
_sessionFactory.EnqueueSession(session);
await _service.ConnectAsync(ValidSettings());
await _service.SubscribeAsync(new NodeId("ns=2;s=MyNode"), 500);
session.CreatedSubscriptions.Count.ShouldBe(1);
session.CreatedSubscriptions[0].AddDataChangeCount.ShouldBe(1);
}
/// <summary>
/// Verifies that duplicate subscribe requests for the same node do not create duplicate monitored items.
/// </summary>
[Fact]
public async Task SubscribeAsync_DuplicateNode_IsIdempotent()
{
var session = new FakeSessionAdapter();
_sessionFactory.EnqueueSession(session);
await _service.ConnectAsync(ValidSettings());
await _service.SubscribeAsync(new NodeId("ns=2;s=MyNode"));
await _service.SubscribeAsync(new NodeId("ns=2;s=MyNode")); // duplicate
session.CreatedSubscriptions[0].AddDataChangeCount.ShouldBe(1);
}
/// <summary>
/// Verifies that data-change notifications from the subscription are raised through the shared client event.
/// </summary>
[Fact]
public async Task SubscribeAsync_RaisesDataChangedEvent()
{
var fakeSub = new FakeSubscriptionAdapter();
var session = new FakeSessionAdapter { NextSubscription = fakeSub };
_sessionFactory.EnqueueSession(session);
await _service.ConnectAsync(ValidSettings());
DataChangedEventArgs? received = null;
_service.DataChanged += (_, e) => received = e;
await _service.SubscribeAsync(new NodeId("ns=2;s=MyNode"), 500);
// Simulate data change
var handle = fakeSub.ActiveHandles.First();
fakeSub.SimulateDataChange(handle, new DataValue(new Variant(99), StatusCodes.Good));
received.ShouldNotBeNull();
received!.NodeId.ShouldBe("ns=2;s=MyNode");
received.Value.Value.ShouldBe(99);
}
/// <summary>
/// Verifies that unsubscribing removes the corresponding monitored item from the active subscription.
/// </summary>
[Fact]
public async Task UnsubscribeAsync_RemovesMonitoredItem()
{
var fakeSub = new FakeSubscriptionAdapter();
var session = new FakeSessionAdapter { NextSubscription = fakeSub };
_sessionFactory.EnqueueSession(session);
await _service.ConnectAsync(ValidSettings());
await _service.SubscribeAsync(new NodeId("ns=2;s=MyNode"));
await _service.UnsubscribeAsync(new NodeId("ns=2;s=MyNode"));
fakeSub.RemoveCount.ShouldBe(1);
}
/// <summary>
/// Verifies that unsubscribing an unknown node is treated as a safe no-op.
/// </summary>
[Fact]
public async Task UnsubscribeAsync_WhenNotSubscribed_DoesNotThrow()
{
var session = new FakeSessionAdapter();
_sessionFactory.EnqueueSession(session);
await _service.ConnectAsync(ValidSettings());
await _service.UnsubscribeAsync(new NodeId("ns=2;s=NotSubscribed"));
// Should not throw
}
/// <summary>
/// Verifies that data subscriptions cannot be created while the client is disconnected.
/// </summary>
[Fact]
public async Task SubscribeAsync_WhenDisconnected_Throws()
{
await Should.ThrowAsync<InvalidOperationException>(() =>
_service.SubscribeAsync(new NodeId("ns=2;s=MyNode")));
}
// --- Alarm subscription tests ---
/// <summary>
/// Verifies that alarm subscription requests create an event monitored item on the session.
/// </summary>
[Fact]
public async Task SubscribeAlarmsAsync_CreatesEventSubscription()
{
var session = new FakeSessionAdapter();
_sessionFactory.EnqueueSession(session);
await _service.ConnectAsync(ValidSettings());
await _service.SubscribeAlarmsAsync();
session.CreatedSubscriptions.Count.ShouldBe(1);
session.CreatedSubscriptions[0].AddEventCount.ShouldBe(1);
}
/// <summary>
/// Verifies that duplicate alarm-subscription requests do not create duplicate event subscriptions.
/// </summary>
[Fact]
public async Task SubscribeAlarmsAsync_Duplicate_IsIdempotent()
{
var session = new FakeSessionAdapter();
_sessionFactory.EnqueueSession(session);
await _service.ConnectAsync(ValidSettings());
await _service.SubscribeAlarmsAsync();
await _service.SubscribeAlarmsAsync(); // duplicate
session.CreatedSubscriptions.Count.ShouldBe(1);
}
/// <summary>
/// Verifies that OPC UA event notifications are mapped into the shared client alarm event model.
/// </summary>
[Fact]
public async Task SubscribeAlarmsAsync_RaisesAlarmEvent()
{
var fakeSub = new FakeSubscriptionAdapter();
var session = new FakeSessionAdapter { NextSubscription = fakeSub };
_sessionFactory.EnqueueSession(session);
await _service.ConnectAsync(ValidSettings());
AlarmEventArgs? received = null;
_service.AlarmEvent += (_, e) => received = e;
await _service.SubscribeAlarmsAsync();
// Simulate alarm event with proper field count
var handle = fakeSub.ActiveHandles.First();
var fields = new EventFieldList
{
EventFields =
[
new Variant(new byte[] { 1, 2, 3 }), // 0: EventId
new Variant(ObjectTypeIds.AlarmConditionType), // 1: EventType
new Variant("Source1"), // 2: SourceName
new Variant(DateTime.UtcNow), // 3: Time
new Variant(new LocalizedText("High temp")), // 4: Message
new Variant((ushort)500), // 5: Severity
new Variant("HighTemp"), // 6: ConditionName
new Variant(true), // 7: Retain
new Variant(false), // 8: AckedState
new Variant(true), // 9: ActiveState
new Variant(true), // 10: EnabledState
new Variant(false)
]
};
fakeSub.SimulateEvent(handle, fields);
received.ShouldNotBeNull();
received!.SourceName.ShouldBe("Source1");
received.ConditionName.ShouldBe("HighTemp");
received.Severity.ShouldBe((ushort)500);
received.Message.ShouldBe("High temp");
received.Retain.ShouldBeTrue();
received.ActiveState.ShouldBeTrue();
received.AckedState.ShouldBeFalse();
}
/// <summary>
/// Verifies that removing alarm monitoring deletes the underlying event subscription.
/// </summary>
[Fact]
public async Task UnsubscribeAlarmsAsync_DeletesSubscription()
{
var fakeSub = new FakeSubscriptionAdapter();
var session = new FakeSessionAdapter { NextSubscription = fakeSub };
_sessionFactory.EnqueueSession(session);
await _service.ConnectAsync(ValidSettings());
await _service.SubscribeAlarmsAsync();
await _service.UnsubscribeAlarmsAsync();
fakeSub.Deleted.ShouldBeTrue();
}
/// <summary>
/// Verifies that removing alarms is safe even when no alarm subscription exists.
/// </summary>
[Fact]
public async Task UnsubscribeAlarmsAsync_WhenNoSubscription_DoesNotThrow()
{
var session = new FakeSessionAdapter();
_sessionFactory.EnqueueSession(session);
await _service.ConnectAsync(ValidSettings());
await _service.UnsubscribeAlarmsAsync(); // Should not throw
}
/// <summary>
/// Verifies that condition refresh requests are forwarded to the active alarm subscription.
/// </summary>
[Fact]
public async Task RequestConditionRefreshAsync_CallsAdapter()
{
var fakeSub = new FakeSubscriptionAdapter();
var session = new FakeSessionAdapter { NextSubscription = fakeSub };
_sessionFactory.EnqueueSession(session);
await _service.ConnectAsync(ValidSettings());
await _service.SubscribeAlarmsAsync();
await _service.RequestConditionRefreshAsync();
fakeSub.ConditionRefreshCalled.ShouldBeTrue();
}
/// <summary>
/// Verifies that condition refresh fails fast when no alarm subscription is active.
/// </summary>
[Fact]
public async Task RequestConditionRefreshAsync_NoAlarmSubscription_Throws()
{
var session = new FakeSessionAdapter();
_sessionFactory.EnqueueSession(session);
await _service.ConnectAsync(ValidSettings());
await Should.ThrowAsync<InvalidOperationException>(() =>
_service.RequestConditionRefreshAsync());
}
/// <summary>
/// Verifies that alarm subscriptions cannot be created while disconnected.
/// </summary>
[Fact]
public async Task SubscribeAlarmsAsync_WhenDisconnected_Throws()
{
await Should.ThrowAsync<InvalidOperationException>(() =>
_service.SubscribeAlarmsAsync());
}
// --- History read tests ---
/// <summary>
/// Verifies that raw history reads return the session-provided values.
/// </summary>
[Fact]
public async Task HistoryReadRawAsync_ReturnsValues()
{
var expectedValues = new List<DataValue>
{
new(new Variant(1.0), StatusCodes.Good),
new(new Variant(2.0), StatusCodes.Good)
};
var session = new FakeSessionAdapter { HistoryReadRawResponse = expectedValues };
_sessionFactory.EnqueueSession(session);
await _service.ConnectAsync(ValidSettings());
var results = await _service.HistoryReadRawAsync(
new NodeId("ns=2;s=Temp"), DateTime.UtcNow.AddHours(-1), DateTime.UtcNow);
results.Count.ShouldBe(2);
session.HistoryReadRawCount.ShouldBe(1);
}
/// <summary>
/// Verifies that raw history reads are rejected while disconnected.
/// </summary>
[Fact]
public async Task HistoryReadRawAsync_WhenDisconnected_Throws()
{
await Should.ThrowAsync<InvalidOperationException>(() =>
_service.HistoryReadRawAsync(new NodeId("ns=2;s=Temp"), DateTime.UtcNow.AddHours(-1), DateTime.UtcNow));
}
/// <summary>
/// Verifies that raw-history failures from the session are propagated to callers.
/// </summary>
[Fact]
public async Task HistoryReadRawAsync_SessionThrows_PropagatesException()
{
var session = new FakeSessionAdapter { ThrowOnHistoryReadRaw = true };
_sessionFactory.EnqueueSession(session);
await _service.ConnectAsync(ValidSettings());
await Should.ThrowAsync<ServiceResultException>(() =>
_service.HistoryReadRawAsync(new NodeId("ns=2;s=Temp"), DateTime.UtcNow.AddHours(-1), DateTime.UtcNow));
}
/// <summary>
/// Verifies that aggregate history reads return the processed values from the session adapter.
/// </summary>
[Fact]
public async Task HistoryReadAggregateAsync_ReturnsValues()
{
var expectedValues = new List<DataValue>
{
new(new Variant(1.5), StatusCodes.Good)
};
var session = new FakeSessionAdapter { HistoryReadAggregateResponse = expectedValues };
_sessionFactory.EnqueueSession(session);
await _service.ConnectAsync(ValidSettings());
var results = await _service.HistoryReadAggregateAsync(
new NodeId("ns=2;s=Temp"), DateTime.UtcNow.AddHours(-1), DateTime.UtcNow,
AggregateType.Average);
results.Count.ShouldBe(1);
session.HistoryReadAggregateCount.ShouldBe(1);
}
/// <summary>
/// Verifies that aggregate history reads are rejected while disconnected.
/// </summary>
[Fact]
public async Task HistoryReadAggregateAsync_WhenDisconnected_Throws()
{
await Should.ThrowAsync<InvalidOperationException>(() =>
_service.HistoryReadAggregateAsync(
new NodeId("ns=2;s=Temp"), DateTime.UtcNow.AddHours(-1), DateTime.UtcNow,
AggregateType.Average));
}
/// <summary>
/// Verifies that aggregate-history failures from the session are propagated to callers.
/// </summary>
[Fact]
public async Task HistoryReadAggregateAsync_SessionThrows_PropagatesException()
{
var session = new FakeSessionAdapter { ThrowOnHistoryReadAggregate = true };
_sessionFactory.EnqueueSession(session);
await _service.ConnectAsync(ValidSettings());
await Should.ThrowAsync<ServiceResultException>(() =>
_service.HistoryReadAggregateAsync(
new NodeId("ns=2;s=Temp"), DateTime.UtcNow.AddHours(-1), DateTime.UtcNow,
AggregateType.Average));
}
// --- Redundancy tests ---
/// <summary>
/// Verifies that redundancy mode, service level, and server URIs are read from the standard OPC UA redundancy nodes.
/// </summary>
[Fact]
public async Task GetRedundancyInfoAsync_ReturnsInfo()
{
var session = new FakeSessionAdapter
{
ReadResponseFunc = nodeId =>
{
if (nodeId == VariableIds.Server_ServerRedundancy_RedundancySupport)
return new DataValue(new Variant((int)RedundancySupport.Warm), StatusCodes.Good);
if (nodeId == VariableIds.Server_ServiceLevel)
return new DataValue(new Variant((byte)200), StatusCodes.Good);
if (nodeId == VariableIds.Server_ServerRedundancy_ServerUriArray)
return new DataValue(new Variant(["urn:server1", "urn:server2"]), StatusCodes.Good);
if (nodeId == VariableIds.Server_ServerArray)
return new DataValue(new Variant(["urn:server1"]), StatusCodes.Good);
return new DataValue(StatusCodes.BadNodeIdUnknown);
}
};
_sessionFactory.EnqueueSession(session);
await _service.ConnectAsync(ValidSettings());
var info = await _service.GetRedundancyInfoAsync();
info.Mode.ShouldBe("Warm");
info.ServiceLevel.ShouldBe((byte)200);
info.ServerUris.ShouldBe(["urn:server1", "urn:server2"]);
info.ApplicationUri.ShouldBe("urn:server1");
}
/// <summary>
/// Verifies that missing optional redundancy arrays do not prevent a redundancy snapshot from being returned.
/// </summary>
[Fact]
public async Task GetRedundancyInfoAsync_MissingOptionalArrays_ReturnsGracefully()
{
var readCallIndex = 0;
var session = new FakeSessionAdapter
{
ReadResponseFunc = nodeId =>
{
if (nodeId == VariableIds.Server_ServerRedundancy_RedundancySupport)
return new DataValue(new Variant((int)RedundancySupport.None), StatusCodes.Good);
if (nodeId == VariableIds.Server_ServiceLevel)
return new DataValue(new Variant((byte)100), StatusCodes.Good);
// Throw for optional reads
throw new ServiceResultException(StatusCodes.BadNodeIdUnknown);
}
};
_sessionFactory.EnqueueSession(session);
await _service.ConnectAsync(ValidSettings());
var info = await _service.GetRedundancyInfoAsync();
info.Mode.ShouldBe("None");
info.ServiceLevel.ShouldBe((byte)100);
info.ServerUris.ShouldBeEmpty();
info.ApplicationUri.ShouldBeEmpty();
}
/// <summary>
/// Verifies that redundancy inspection is rejected while disconnected.
/// </summary>
[Fact]
public async Task GetRedundancyInfoAsync_WhenDisconnected_Throws()
{
await Should.ThrowAsync<InvalidOperationException>(() =>
_service.GetRedundancyInfoAsync());
}
// --- Failover tests ---
/// <summary>
/// Verifies that a keep-alive failure moves the client to a configured failover endpoint.
/// </summary>
[Fact]
public async Task KeepAliveFailure_TriggersFailover()
{
var session1 = new FakeSessionAdapter { EndpointUrl = "opc.tcp://primary:4840" };
var session2 = new FakeSessionAdapter { EndpointUrl = "opc.tcp://backup:4840" };
_sessionFactory.EnqueueSession(session1);
_sessionFactory.EnqueueSession(session2);
var settings = ValidSettings("opc.tcp://primary:4840");
settings.FailoverUrls = ["opc.tcp://backup:4840"];
var stateChanges = new List<ConnectionStateChangedEventArgs>();
_service.ConnectionStateChanged += (_, e) => stateChanges.Add(e);
await _service.ConnectAsync(settings);
// Simulate keep-alive failure
session1.SimulateKeepAlive(false);
// Give async failover time to complete
await Task.Delay(200);
// Should have reconnected
stateChanges.ShouldContain(e => e.NewState == ConnectionState.Reconnecting);
stateChanges.ShouldContain(e => e.NewState == ConnectionState.Connected &&
e.EndpointUrl == "opc.tcp://backup:4840");
}
/// <summary>
/// Verifies that connection metadata is refreshed to reflect the newly active failover endpoint.
/// </summary>
[Fact]
public async Task KeepAliveFailure_UpdatesConnectionInfo()
{
var session1 = new FakeSessionAdapter { EndpointUrl = "opc.tcp://primary:4840" };
var session2 = new FakeSessionAdapter
{
EndpointUrl = "opc.tcp://backup:4840",
ServerName = "BackupServer"
};
_sessionFactory.EnqueueSession(session1);
_sessionFactory.EnqueueSession(session2);
var settings = ValidSettings("opc.tcp://primary:4840");
settings.FailoverUrls = ["opc.tcp://backup:4840"];
await _service.ConnectAsync(settings);
session1.SimulateKeepAlive(false);
await Task.Delay(200);
_service.CurrentConnectionInfo!.EndpointUrl.ShouldBe("opc.tcp://backup:4840");
_service.CurrentConnectionInfo.ServerName.ShouldBe("BackupServer");
}
/// <summary>
/// Verifies that the client falls back to disconnected when every failover endpoint is unreachable.
/// </summary>
[Fact]
public async Task KeepAliveFailure_AllEndpointsFail_TransitionsToDisconnected()
{
var session1 = new FakeSessionAdapter();
_sessionFactory.EnqueueSession(session1);
await _service.ConnectAsync(ValidSettings());
// After the first session, make factory fail
_sessionFactory.ThrowOnCreate = true;
session1.SimulateKeepAlive(false);
await Task.Delay(200);
_service.IsConnected.ShouldBeFalse();
}
// --- Dispose tests ---
/// <summary>
/// Verifies that dispose releases the underlying session and clears exposed connection state.
/// </summary>
[Fact]
public async Task Dispose_CleansUpResources()
{
var session = new FakeSessionAdapter();
_sessionFactory.EnqueueSession(session);
await _service.ConnectAsync(ValidSettings());
_service.Dispose();
session.Disposed.ShouldBeTrue();
_service.CurrentConnectionInfo.ShouldBeNull();
}
/// <summary>
/// Verifies that dispose is safe to call even when no connection was established.
/// </summary>
[Fact]
public void Dispose_WhenNotConnected_DoesNotThrow()
{
_service.Dispose(); // Should not throw
}
/// <summary>
/// Verifies that public operations reject use after the shared client has been disposed.
/// </summary>
[Fact]
public async Task OperationsAfterDispose_Throw()
{
_service.Dispose();
await Should.ThrowAsync<ObjectDisposedException>(() =>
_service.ConnectAsync(ValidSettings()));
await Should.ThrowAsync<ObjectDisposedException>(() =>
_service.ReadValueAsync(new NodeId("ns=2;s=X")));
}
// --- Factory tests ---
/// <summary>
/// Verifies that the factory creates a usable shared OPC UA client service instance.
/// </summary>
[Fact]
public void OpcUaClientServiceFactory_CreatesService()
{
var factory = new OpcUaClientServiceFactory();
var service = factory.Create();
service.ShouldNotBeNull();
service.ShouldBeAssignableTo<IOpcUaClientService>();
service.Dispose();
}
}

View File

@@ -0,0 +1,26 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
<RootNamespace>ZB.MOM.WW.OtOpcUa.Client.Shared.Tests</RootNamespace>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="xunit.v3" Version="1.1.0"/>
<PackageReference Include="Shouldly" Version="4.3.0"/>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.12.0"/>
<PackageReference Include="xunit.runner.visualstudio" Version="3.0.2">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\ZB.MOM.WW.OtOpcUa.Client.Shared\ZB.MOM.WW.OtOpcUa.Client.Shared.csproj"/>
</ItemGroup>
</Project>