test: validate grpc data connections with local docker and opcua cli

This commit is contained in:
Joseph Doherty
2026-11-17 22:01:26 -05:00
parent 1df29a3124
commit 29fec57fac
194 changed files with 23327 additions and 740 deletions
@@ -182,6 +182,14 @@ public sealed class FakeOpcUaClientService : IOpcUaClientService
return Task.FromResult(ReadValueResult);
}
public TimeSpan? LastMaximumAge { get; private set; }
public Task<DataValue> ReadValueAsync(NodeId nodeId, TimeSpan maximumAge, CancellationToken ct = default)
{
LastMaximumAge = maximumAge;
return ReadValueAsync(nodeId, ct);
}
/// <inheritdoc />
public Task<StatusCode> WriteValueAsync(NodeId nodeId, object value, CancellationToken ct = default)
{
@@ -8,11 +8,45 @@ namespace ZB.MOM.WW.OtOpcUa.Client.CLI.Tests;
public class ReadCommandTests
{
[Theory]
[InlineData(0)]
[InlineData(5000)]
[InlineData(2147483647)]
public async Task Execute_ForwardsMaximumAge(double milliseconds)
{
var service = new FakeOpcUaClientService();
var command = new ReadCommand(new FakeOpcUaClientServiceFactory(service))
{
Url = "opc.tcp://localhost:4840", NodeId = "ns=2;s=Test", MaxAgeMilliseconds = milliseconds
};
using var console = TestConsoleHelper.CreateConsole();
await command.ExecuteAsync(console);
if (milliseconds == 0) service.LastMaximumAge.ShouldBeNull();
else service.LastMaximumAge.ShouldBe(TimeSpan.FromMilliseconds(milliseconds));
}
[Theory]
[InlineData(-1)]
[InlineData(2147483648d)]
[InlineData(double.NaN)]
[InlineData(double.PositiveInfinity)]
public async Task Execute_RejectsInvalidMaximumAge(double milliseconds)
{
var service = new FakeOpcUaClientService();
var command = new ReadCommand(new FakeOpcUaClientServiceFactory(service))
{
Url = "opc.tcp://localhost:4840", NodeId = "ns=2;s=Test", MaxAgeMilliseconds = milliseconds
};
using var console = TestConsoleHelper.CreateConsole();
await Should.ThrowAsync<CliFx.Exceptions.CommandException>(async () => await command.ExecuteAsync(console));
service.ReadNodeIds.ShouldBeEmpty();
}
/// <summary>Verifies that execute prints the read value.</summary>
[Fact]
public async Task Execute_PrintsReadValue()
{
var sourceTime = new DateTime(2025, 6, 15, 10, 30, 0, DateTimeKind.Utc);
var sourceTime = new DateTime(2025, 6, 15, 10, 30, 0, DateTimeKind.Utc).AddTicks(1234567);
var serverTime = new DateTime(2025, 6, 15, 10, 30, 1, DateTimeKind.Utc);
var fakeService = new FakeOpcUaClientService
{
@@ -38,6 +72,8 @@ public class ReadCommandTests
output.ShouldContain("Status:");
output.ShouldContain("Source Time:");
output.ShouldContain("Server Time:");
output.ShouldContain("Source Time: " + sourceTime.ToString("O", System.Globalization.CultureInfo.InvariantCulture));
output.ShouldContain("Server Time: " + serverTime.ToString("O", System.Globalization.CultureInfo.InvariantCulture));
}
/// <summary>Verifies that execute calls read value with correct node ID.</summary>
@@ -60,9 +60,10 @@ public class SubscribeCommandSummaryTests
// Wait until the subscription is registered by the fake.
await WaitForAsync(() => fakeService.SubscribeCalls.Count == 1);
var acquisitionTime = new DateTime(2026, 11, 17, 3, 0, 0, DateTimeKind.Utc).AddTicks(7654321);
fakeService.RaiseDataChanged(
"ns=2;s=GoodNode",
new DataValue(new Variant(42), StatusCodes.Good, DateTime.UtcNow, DateTime.UtcNow));
new DataValue(new Variant(42), StatusCodes.Good, acquisitionTime, DateTime.UtcNow));
await runTask;
@@ -70,6 +71,7 @@ public class SubscribeCommandSummaryTests
output.ShouldContain("NEVER went bad (suspect): 1");
output.ShouldContain("Last status GOOD: 1");
output.ShouldContain("No update received at all: 0");
output.ShouldContain("[" + acquisitionTime.ToString("O") + "]");
}
/// <summary>Verifies that nodes with bad values are counted as ever went bad.</summary>
@@ -1,3 +1,5 @@
using System.Globalization;
using CliFx.Exceptions;
using Opc.Ua;
using Shouldly;
using Xunit;
@@ -8,6 +10,131 @@ namespace ZB.MOM.WW.OtOpcUa.Client.CLI.Tests;
public class WriteCommandTests
{
/// <summary>Verifies that an explicit UInt16 write does not require read access.</summary>
[Fact]
public async Task Execute_ExplicitUInt16BypassesReadAndWritesUShort()
{
var fakeService = new FakeOpcUaClientService
{
ReadException = new InvalidOperationException("Value read is not authorized.")
};
var command = new WriteCommand(new FakeOpcUaClientServiceFactory(fakeService))
{
Url = "opc.tcp://localhost:4840",
NodeId = "ns=2;s=WriteOnly",
Value = "65535",
Type = "UInt16"
};
using var console = TestConsoleHelper.CreateConsole();
await command.ExecuteAsync(console);
fakeService.ReadNodeIds.ShouldBeEmpty();
fakeService.WriteValues.Count.ShouldBe(1);
fakeService.WriteValues[0].Value.ShouldBeOfType<ushort>().ShouldBe(ushort.MaxValue);
fakeService.DisconnectCalled.ShouldBeTrue();
fakeService.DisposeCalled.ShouldBeTrue();
}
/// <summary>Verifies the explicit scalar set and invariant numeric conversion.</summary>
[Theory]
[InlineData("Boolean", "yes", typeof(bool))]
[InlineData("Byte", "255", typeof(byte))]
[InlineData("SByte", "-128", typeof(sbyte))]
[InlineData("Int16", "-32768", typeof(short))]
[InlineData("UInt16", "65535", typeof(ushort))]
[InlineData("Int32", "-2147483648", typeof(int))]
[InlineData("UInt32", "4294967295", typeof(uint))]
[InlineData("Int64", "-9223372036854775808", typeof(long))]
[InlineData("UInt64", "18446744073709551615", typeof(ulong))]
[InlineData("Float", "1.25", typeof(float))]
[InlineData("Double", "1.25", typeof(double))]
[InlineData("String", "operator text", typeof(string))]
[InlineData("uint16", "123", typeof(ushort))]
public async Task Execute_ExplicitScalarUsesRequestedClrType(string type, string value, Type expectedType)
{
var fakeService = new FakeOpcUaClientService
{
ReadException = new InvalidOperationException("Explicit types must not read.")
};
var command = new WriteCommand(new FakeOpcUaClientServiceFactory(fakeService))
{
Url = "opc.tcp://localhost:4840", NodeId = "ns=2;s=Scalar", Value = value, Type = type
};
var originalCulture = CultureInfo.CurrentCulture;
try
{
CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("fr-FR");
using var console = TestConsoleHelper.CreateConsole();
await command.ExecuteAsync(console);
}
finally
{
CultureInfo.CurrentCulture = originalCulture;
}
fakeService.ReadNodeIds.ShouldBeEmpty();
fakeService.WriteValues.Count.ShouldBe(1);
var writtenValue = fakeService.WriteValues[0].Value;
writtenValue.GetType().ShouldBe(expectedType);
if (expectedType == typeof(bool))
writtenValue.ShouldBe(true);
else
Convert.ToString(writtenValue, CultureInfo.InvariantCulture).ShouldBe(value);
}
/// <summary>Verifies unsupported type names fail locally before connecting or writing.</summary>
[Theory]
[InlineData("")]
[InlineData(" ")]
[InlineData("DateTime")]
[InlineData("ByteString")]
[InlineData("UInt16[]")]
[InlineData("System.UInt16")]
[InlineData("Unknown")]
public async Task Execute_UnsupportedExplicitTypeRejectsBeforeConnect(string type)
{
var fakeService = new FakeOpcUaClientService();
var command = new WriteCommand(new FakeOpcUaClientServiceFactory(fakeService))
{
Url = "opc.tcp://localhost:4840", NodeId = "ns=2;s=Scalar", Value = "1", Type = type
};
using var console = TestConsoleHelper.CreateConsole();
var error = await Should.ThrowAsync<CommandException>(async () => await command.ExecuteAsync(console));
error.Message.ShouldContain("--type");
fakeService.ConnectCalled.ShouldBeFalse();
fakeService.ReadNodeIds.ShouldBeEmpty();
fakeService.WriteValues.ShouldBeEmpty();
}
/// <summary>Verifies invalid explicit values fail locally before connecting or writing.</summary>
[Theory]
[InlineData("UInt16", "65536")]
[InlineData("UInt16", "-1")]
[InlineData("UInt16", "not-a-number")]
[InlineData("UInt16", "1.5")]
[InlineData("SByte", "128")]
[InlineData("Boolean", "maybe")]
[InlineData("Double", "1,25")]
public async Task Execute_InvalidExplicitValueRejectsBeforeConnect(string type, string value)
{
var fakeService = new FakeOpcUaClientService();
var command = new WriteCommand(new FakeOpcUaClientServiceFactory(fakeService))
{
Url = "opc.tcp://localhost:4840", NodeId = "ns=2;s=Scalar", Value = value, Type = type
};
using var console = TestConsoleHelper.CreateConsole();
var error = await Should.ThrowAsync<CommandException>(async () => await command.ExecuteAsync(console));
error.Message.ShouldContain("--value");
fakeService.ConnectCalled.ShouldBeFalse();
fakeService.ReadNodeIds.ShouldBeEmpty();
fakeService.WriteValues.ShouldBeEmpty();
}
/// <summary>Verifies that write command executes successfully.</summary>
[Fact]
public async Task Execute_WritesSuccessfully()
@@ -104,4 +231,4 @@ public class WriteCommandTests
fakeService.DisconnectCalled.ShouldBeTrue();
fakeService.DisposeCalled.ShouldBeTrue();
}
}
}
@@ -11,6 +11,8 @@ internal sealed class FakeEndpointDiscovery : IEndpointDiscovery
public int SelectCallCount { get; private set; }
/// <summary>Gets the last endpoint URL passed to SelectEndpoint.</summary>
public string? LastEndpointUrl { get; private set; }
/// <summary>Gets or sets the discovered endpoint URL when it differs from the input URL.</summary>
public string? SelectedEndpointUrl { get; set; }
/// <summary>Selects an endpoint for the given configuration and URL, optionally throwing an exception.</summary>
/// <param name="config">The application configuration.</param>
@@ -28,7 +30,7 @@ internal sealed class FakeEndpointDiscovery : IEndpointDiscovery
return Task.FromResult(new EndpointDescription
{
EndpointUrl = endpointUrl,
EndpointUrl = SelectedEndpointUrl ?? endpointUrl,
SecurityMode = requestedMode,
SecurityPolicyUri = requestedMode == MessageSecurityMode.None
? SecurityPolicies.None
@@ -89,8 +89,17 @@ internal sealed class FakeSessionAdapter : ISessionAdapter
/// <inheritdoc />
public string SessionName { get; set; } = "FakeSession";
private string _endpointUrl = "opc.tcp://localhost:4840";
/// <summary>Simulates SDK endpoint metadata becoming unavailable after a transport failure.</summary>
public bool ThrowOnEndpointUrlRead { get; set; }
/// <inheritdoc />
public string EndpointUrl { get; set; } = "opc.tcp://localhost:4840";
public string EndpointUrl
{
get => ThrowOnEndpointUrlRead ? throw new NullReferenceException("The SDK transport is gone.") : _endpointUrl;
set => _endpointUrl = value;
}
/// <inheritdoc />
public string ServerName { get; set; } = "FakeServer";
@@ -123,6 +132,17 @@ internal sealed class FakeSessionAdapter : ISessionAdapter
return Task.FromResult(ReadResponse ?? new DataValue(new Variant(0), StatusCodes.Good));
}
public TimeSpan? LastMaximumAge { get; private set; }
public CancellationToken LastReadCancellationToken { get; private set; }
public Task<DataValue> ReadValueAsync(NodeId nodeId, TimeSpan maximumAge, CancellationToken ct)
{
LastMaximumAge = maximumAge;
LastReadCancellationToken = ct;
ct.ThrowIfCancellationRequested();
return ReadValueAsync(nodeId, ct);
}
/// <inheritdoc />
public Task<StatusCode> WriteValueAsync(NodeId nodeId, DataValue value, CancellationToken ct)
{
@@ -37,6 +37,12 @@ internal sealed class FakeSubscriptionAdapter : ISubscriptionAdapter
/// <summary>Gets the number of times AddEventMonitoredItemAsync was called.</summary>
public int AddEventCount { get; private set; }
/// <summary>Optional per-item rejection for an event add.</summary>
public Exception? EventAddException { get; set; }
/// <summary>Whether this instance was disposed.</summary>
public bool Disposed { get; private set; }
/// <summary>Gets or sets a value indicating whether RemoveMonitoredItemAsync throws (a session that died).</summary>
public bool ThrowOnRemove { get; set; }
@@ -91,6 +97,7 @@ internal sealed class FakeSubscriptionAdapter : ISubscriptionAdapter
lock (_itemsLock)
{
AddEventCount++;
if (EventAddException is { } error) throw error;
var handle = _nextHandle++;
_items[handle] = (nodeId, null, onEvent);
return Task.FromResult(handle);
@@ -126,6 +133,7 @@ internal sealed class FakeSubscriptionAdapter : ISubscriptionAdapter
/// </summary>
public void Dispose()
{
Disposed = true;
lock (_itemsLock) _items.Clear();
}
@@ -216,6 +216,30 @@ public class OpcUaClientServiceTests : IDisposable
_service.CurrentConnectionInfo.ShouldBeNull();
}
[Fact]
public async Task DisconnectAsync_AfterTransportLoss_UsesPublishedEndpointAndClosesSession()
{
var ct = TestContext.Current.CancellationToken;
const string endpoint = "opc.tcp://negotiated:4840";
_endpointDiscovery.SelectedEndpointUrl = endpoint;
var session = new FakeSessionAdapter();
_sessionFactory.EnqueueSession(session);
await _service.ConnectAsync(ValidSettings(), ct);
_service.CurrentConnectionInfo!.EndpointUrl.ShouldBe(endpoint);
session.ThrowOnEndpointUrlRead = true;
var events = new List<ConnectionStateChangedEventArgs>();
_service.ConnectionStateChanged += (_, state) => events.Add(state);
await _service.DisconnectAsync(ct);
session.Closed.ShouldBeTrue();
session.Disposed.ShouldBeTrue();
_service.CurrentConnectionInfo.ShouldBeNull();
var disconnected = events.ShouldHaveSingleItem();
disconnected.NewState.ShouldBe(ConnectionState.Disconnected);
disconnected.EndpointUrl.ShouldBe(endpoint);
}
/// <summary>
/// Verifies that disconnect is safe to call when no server session is active.
/// </summary>
@@ -239,6 +263,36 @@ public class OpcUaClientServiceTests : IDisposable
// --- Read tests ---
[Fact]
public async Task ReadValueAsync_MaximumAge_ForwardsAgeAndCancellation()
{
var session = new FakeSessionAdapter();
_sessionFactory.EnqueueSession(session);
await _service.ConnectAsync(ValidSettings(), TestContext.Current.CancellationToken);
using var source = new CancellationTokenSource();
await _service.ReadValueAsync(new NodeId("tag", 2), TimeSpan.FromSeconds(5), source.Token);
session.LastMaximumAge.ShouldBe(TimeSpan.FromSeconds(5));
session.LastReadCancellationToken.ShouldBe(source.Token);
source.Cancel();
await Should.ThrowAsync<OperationCanceledException>(() =>
_service.ReadValueAsync(new NodeId("tag", 2), TimeSpan.FromSeconds(5), source.Token));
}
[Fact]
public async Task ReadValueAsync_MaximumAge_ZeroPreservesOriginalPathAndInvalidAgesFail()
{
var session = new FakeSessionAdapter();
_sessionFactory.EnqueueSession(session);
await _service.ConnectAsync(ValidSettings(), TestContext.Current.CancellationToken);
await _service.ReadValueAsync(new NodeId("tag", 2), TimeSpan.Zero, TestContext.Current.CancellationToken);
session.LastMaximumAge.ShouldBeNull();
session.ReadCount.ShouldBe(1);
await Should.ThrowAsync<ArgumentOutOfRangeException>(() => _service.ReadValueAsync(new NodeId("tag", 2), TimeSpan.FromMilliseconds(-1), TestContext.Current.CancellationToken));
await Should.ThrowAsync<ArgumentOutOfRangeException>(() => _service.ReadValueAsync(new NodeId("tag", 2), TimeSpan.FromMilliseconds((double)int.MaxValue + 1), TestContext.Current.CancellationToken));
}
/// <summary>
/// Verifies that a connected client can read the current value of a node through the session adapter.
/// </summary>
@@ -718,6 +772,50 @@ public class OpcUaClientServiceTests : IDisposable
session.CreatedSubscriptions[0].AddEventCount.ShouldBe(1);
}
[Fact]
public async Task Rejected_alarm_item_cleans_up_and_a_later_subscribe_succeeds()
{
var rejected = new ServiceResultException(StatusCodes.BadUserAccessDenied);
var failed = new FakeSubscriptionAdapter { EventAddException = rejected };
var session = new FakeSessionAdapter { NextSubscription = failed };
_sessionFactory.EnqueueSession(session);
await _service.ConnectAsync(ValidSettings(), TestContext.Current.CancellationToken);
var error = await Should.ThrowAsync<ServiceResultException>(() =>
_service.SubscribeAlarmsAsync(ct: TestContext.Current.CancellationToken));
error.ShouldBeSameAs(rejected);
failed.Deleted.ShouldBeTrue();
failed.Disposed.ShouldBeTrue();
await _service.SubscribeAlarmsAsync(ct: TestContext.Current.CancellationToken);
session.CreatedSubscriptions.Count.ShouldBe(2);
session.CreatedSubscriptions[1].AddEventCount.ShouldBe(1);
session.CreatedSubscriptions[1].ActiveHandles.Count.ShouldBe(1);
}
[Fact]
public async Task Rejected_alarm_replay_cleans_up_and_a_later_subscribe_succeeds()
{
var failed = new FakeSubscriptionAdapter { EventAddException = new ServiceResultException(StatusCodes.BadUserAccessDenied) };
var original = new FakeSessionAdapter { EndpointUrl = "opc.tcp://primary:4840" };
var replacement = new FakeSessionAdapter { EndpointUrl = "opc.tcp://backup:4840", NextSubscription = failed };
_sessionFactory.EnqueueSession(original);
_sessionFactory.EnqueueSession(replacement);
var settings = ValidSettings("opc.tcp://primary:4840");
settings.FailoverUrls = ["opc.tcp://backup:4840"];
await _service.ConnectAsync(settings, TestContext.Current.CancellationToken);
await _service.SubscribeAlarmsAsync(ct: TestContext.Current.CancellationToken);
original.SimulateKeepAlive(false);
await _service.LastFailover.ShouldNotBeNull().WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken);
failed.Deleted.ShouldBeTrue();
failed.Disposed.ShouldBeTrue();
await _service.SubscribeAlarmsAsync(ct: TestContext.Current.CancellationToken);
replacement.CreatedSubscriptions.Count.ShouldBe(2);
replacement.CreatedSubscriptions[1].AddEventCount.ShouldBe(1);
replacement.CreatedSubscriptions[1].ActiveHandles.Count.ShouldBe(1);
}
/// <summary>
/// Verifies that duplicate alarm-subscription requests do not create duplicate event subscriptions.
/// </summary>
@@ -1486,6 +1584,31 @@ public class OpcUaClientServiceTests : IDisposable
e.EndpointUrl == "opc.tcp://backup:4840");
}
[Fact]
public async Task KeepAliveFailure_AfterTransportLoss_UsesPublishedEndpointAndReconnects()
{
var ct = TestContext.Current.CancellationToken;
const string primary = "opc.tcp://primary:4840";
const string backup = "opc.tcp://backup:4840";
var original = new FakeSessionAdapter { EndpointUrl = primary };
_sessionFactory.EnqueueSession(original);
_sessionFactory.EnqueueSession(new FakeSessionAdapter { EndpointUrl = backup });
var settings = ValidSettings(primary);
settings.FailoverUrls = [backup];
await _service.ConnectAsync(settings, ct);
original.ThrowOnEndpointUrlRead = true;
var events = new List<ConnectionStateChangedEventArgs>();
_service.ConnectionStateChanged += (_, state) => events.Add(state);
original.SimulateKeepAlive(false);
await _service.LastFailover!.WaitAsync(TimeSpan.FromSeconds(5), ct);
original.Disposed.ShouldBeTrue();
events.Select(state => (state.NewState, state.EndpointUrl)).ShouldBe([
(ConnectionState.Reconnecting, primary), (ConnectionState.Connected, backup)]);
_service.CurrentConnectionInfo!.EndpointUrl.ShouldBe(backup);
}
/// <summary>
/// Verifies that connection metadata is refreshed to reflect the newly active failover endpoint.
/// </summary>
@@ -0,0 +1,25 @@
using Opc.Ua;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Client.Shared.Adapters;
namespace ZB.MOM.WW.OtOpcUa.Client.Shared.Tests;
[Trait("Feature", "GrpcData"), Trait("Phase", "P10")]
public class ReadResultValidationTests
{
[Fact]
public void ValidateReadResult_RejectsMissingOrExtraResultsAndBadStatus()
{
var header = new ResponseHeader { ServiceResult = StatusCodes.Good };
var node = new NodeId("tag", 2);
Should.Throw<ServiceResultException>(() => DefaultSessionAdapter.ValidateReadResult(header, [], node));
Should.Throw<ServiceResultException>(() => DefaultSessionAdapter.ValidateReadResult(header,
[new DataValue(), new DataValue()], node));
var error = Should.Throw<ServiceResultException>(() => DefaultSessionAdapter.ValidateReadResult(header,
[new DataValue(new Variant(0), StatusCodes.BadNodeIdUnknown)], node));
error.StatusCode.ShouldBe(StatusCodes.BadNodeIdUnknown);
Should.Throw<ServiceResultException>(() => DefaultSessionAdapter.ValidateReadResult(
new ResponseHeader { ServiceResult = StatusCodes.BadUnexpectedError }, [new DataValue()], node));
}
}