Files
lmxopcua/tests/Client/ZB.MOM.WW.OtOpcUa.Client.CLI.Tests/SubscribeCommandTests.cs
T
Joseph Doherty 9496db9357 fix(client): #1048 Client.UI recursive subscribe + restore batch through SubscribeManyAsync; CLI subscribe/alarms exit 3 when a failover never recovers
- SubscriptionsViewModel collects the subtree's variables first (deduped, already-subscribed
  skipped) and creates them in one SubscribeManyAsync; per-node failures are named in
  StatusMessage, a whole-batch failure adds nothing. RestoreSubscriptionsAsync batches too.
- CLI: ConnectionLossWatch ends subscribe/alarms when the service lands Disconnected on its
  own, or stays out of Connected past --reconnect-timeout (default 300 s, 0 = no limit):
  WARNING line, summary (subscribe adds 'Connection: LOST'), exit code 3. A recovery inside
  the window re-arms the watch.
2026-12-03 15:07:30 -05:00

238 lines
11 KiB
C#

using CliFx.Exceptions;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Client.CLI.Commands;
using ZB.MOM.WW.OtOpcUa.Client.CLI.Tests.Fakes;
namespace ZB.MOM.WW.OtOpcUa.Client.CLI.Tests;
public class SubscribeCommandTests
{
/// <summary>Verifies that ExecuteAsync subscribes with the correct parameters.</summary>
[Fact]
public async Task Execute_SubscribesWithCorrectParameters()
{
var fakeService = new FakeOpcUaClientService();
var factory = new FakeOpcUaClientServiceFactory(fakeService);
var command = new SubscribeCommand(factory)
{
Url = "opc.tcp://localhost:4840",
NodeId = "ns=2;s=TestVar",
Interval = 500
};
using var console = TestConsoleHelper.CreateConsole();
// The subscribe command waits for cancellation. We need to cancel it.
// Use the console's cancellation to trigger stop.
var task = Task.Run(async () => { await command.ExecuteAsync(console); }, TestContext.Current.CancellationToken);
// Wait until the command has actually subscribed (deterministic — no fixed-sleep race), then cancel
await fakeService.SubscribeInvoked.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken);
console.RequestCancellation();
await task;
fakeService.SubscribeCalls.Count.ShouldBe(1);
fakeService.SubscribeCalls[0].IntervalMs.ShouldBe(500);
fakeService.SubscribeCalls[0].NodeId.IdentifierAsString.ShouldBe("TestVar");
}
/// <summary>Verifies that ExecuteAsync unsubscribes when cancellation is requested.</summary>
[Fact]
public async Task Execute_UnsubscribesOnCancellation()
{
var fakeService = new FakeOpcUaClientService();
var factory = new FakeOpcUaClientServiceFactory(fakeService);
var command = new SubscribeCommand(factory)
{
Url = "opc.tcp://localhost:4840",
NodeId = "ns=2;s=TestVar"
};
using var console = TestConsoleHelper.CreateConsole();
var task = Task.Run(async () => { await command.ExecuteAsync(console); }, TestContext.Current.CancellationToken);
await fakeService.SubscribeInvoked.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken);
console.RequestCancellation();
await task;
fakeService.UnsubscribeCalls.Count.ShouldBe(1);
}
/// <summary>Verifies that ExecuteAsync disconnects and disposes in a finally block.</summary>
[Fact]
public async Task Execute_DisconnectsInFinally()
{
var fakeService = new FakeOpcUaClientService();
var factory = new FakeOpcUaClientServiceFactory(fakeService);
var command = new SubscribeCommand(factory)
{
Url = "opc.tcp://localhost:4840",
NodeId = "ns=2;s=TestVar"
};
using var console = TestConsoleHelper.CreateConsole();
var task = Task.Run(async () => { await command.ExecuteAsync(console); }, TestContext.Current.CancellationToken);
await fakeService.SubscribeInvoked.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken);
console.RequestCancellation();
await task;
fakeService.DisconnectCalled.ShouldBeTrue();
fakeService.DisposeCalled.ShouldBeTrue();
}
/// <summary>Verifies that ExecuteAsync prints the correct subscription message.</summary>
[Fact]
public async Task Execute_PrintsSubscriptionMessage()
{
var fakeService = new FakeOpcUaClientService();
var factory = new FakeOpcUaClientServiceFactory(fakeService);
var command = new SubscribeCommand(factory)
{
Url = "opc.tcp://localhost:4840",
NodeId = "ns=2;s=TestVar",
Interval = 2000
};
using var console = TestConsoleHelper.CreateConsole();
var task = Task.Run(async () => { await command.ExecuteAsync(console); }, TestContext.Current.CancellationToken);
await fakeService.SubscribeInvoked.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken);
console.RequestCancellation();
await task;
var output = TestConsoleHelper.GetOutput(console);
// CLI now prints aggregate form "Subscribed to {count}/{total} nodes (interval: ...)" rather than
// the single-node form the original test asserted — the command supports multi-node now.
output.ShouldContain("Subscribed to 1/1 nodes (interval: 2000ms)");
}
/// <summary>#1000 S-4: a connection drop / recovery is printed instead of the run going silent.</summary>
[Fact]
public async Task Execute_PrintsConnectionStateTransitions()
{
var fakeService = new FakeOpcUaClientService();
var command = new SubscribeCommand(new FakeOpcUaClientServiceFactory(fakeService))
{
Url = "opc.tcp://localhost:4840",
NodeId = "ns=2;s=TestVar"
};
using var console = TestConsoleHelper.CreateConsole();
var task = Task.Run(async () => { await command.ExecuteAsync(console); }, TestContext.Current.CancellationToken);
await fakeService.SubscribeInvoked.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken);
fakeService.RaiseConnectionStateChanged(Shared.Models.ConnectionState.Connected,
Shared.Models.ConnectionState.Reconnecting, "opc.tcp://localhost:4840");
fakeService.RaiseConnectionStateChanged(Shared.Models.ConnectionState.Reconnecting,
Shared.Models.ConnectionState.Connected, "opc.tcp://backup:4840");
// The drain loop is asynchronous: poll for the last line instead of sleeping a fixed time.
var deadline = DateTime.UtcNow.AddSeconds(10);
while (!TestConsoleHelper.GetOutput(console).Contains("Reconnecting -> Connected") && DateTime.UtcNow < deadline)
await Task.Delay(20, TestContext.Current.CancellationToken);
console.RequestCancellation();
await task;
var output = TestConsoleHelper.GetOutput(console);
output.ShouldContain("CONNECTION Connected -> Reconnecting (opc.tcp://localhost:4840)");
output.ShouldContain("CONNECTION Reconnecting -> Connected (opc.tcp://backup:4840)");
}
/// <summary>
/// #1048: a connection that stays out of Connected past --reconnect-timeout ends the run with a WARNING, the
/// summary, and a non-zero exit — instead of waiting forever and reporting pre-outage values as final.
/// </summary>
[Fact]
public async Task Execute_ExitsNonZero_WhenTheConnectionNeverRecovers()
{
var fakeService = new FakeOpcUaClientService();
var command = new SubscribeCommand(new FakeOpcUaClientServiceFactory(fakeService))
{
Url = "opc.tcp://localhost:4840",
NodeId = "ns=2;s=TestVar",
ReconnectTimeoutSeconds = 1,
};
using var console = TestConsoleHelper.CreateConsole();
var task = Task.Run(async () => { await command.ExecuteAsync(console); }, TestContext.Current.CancellationToken);
await fakeService.SubscribeInvoked.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken);
fakeService.RaiseConnectionStateChanged(Shared.Models.ConnectionState.Connected,
Shared.Models.ConnectionState.Reconnecting, "opc.tcp://localhost:4840");
var ex = await Should.ThrowAsync<CommandException>(() => task.WaitAsync(TimeSpan.FromSeconds(15), TestContext.Current.CancellationToken));
ex.ExitCode.ShouldNotBe(0);
ex.Message.ShouldContain("did not recover within 1 s");
var output = TestConsoleHelper.GetOutput(console);
output.ShouldContain("WARNING");
output.ShouldContain("==================== SUMMARY ====================");
output.ShouldContain("Connection:");
fakeService.DisconnectCalled.ShouldBeTrue();
}
/// <summary>#1048 positive control: a recovery inside the window re-arms the watch and the run continues.</summary>
[Fact]
public async Task Execute_KeepsRunning_WhenTheConnectionRecoversInsideTheTimeout()
{
var fakeService = new FakeOpcUaClientService();
var command = new SubscribeCommand(new FakeOpcUaClientServiceFactory(fakeService))
{
Url = "opc.tcp://localhost:4840",
NodeId = "ns=2;s=TestVar",
ReconnectTimeoutSeconds = 2,
};
using var console = TestConsoleHelper.CreateConsole();
var task = Task.Run(async () => { await command.ExecuteAsync(console); }, TestContext.Current.CancellationToken);
await fakeService.SubscribeInvoked.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken);
fakeService.RaiseConnectionStateChanged(Shared.Models.ConnectionState.Connected,
Shared.Models.ConnectionState.Reconnecting, "opc.tcp://localhost:4840");
fakeService.RaiseConnectionStateChanged(Shared.Models.ConnectionState.Reconnecting,
Shared.Models.ConnectionState.Connected, "opc.tcp://backup:4840");
await Task.Delay(TimeSpan.FromSeconds(3), TestContext.Current.CancellationToken);
task.IsCompleted.ShouldBeFalse();
console.RequestCancellation();
await task; // a clean Ctrl+C exit: no exception
TestConsoleHelper.GetOutput(console).ShouldNotContain("WARNING");
}
/// <summary>#1048: the service landing Disconnected on its own is final — it will not retry — so exit at once.</summary>
[Fact]
public async Task Execute_ExitsNonZero_WhenTheServiceDisconnectsOnItsOwn()
{
var fakeService = new FakeOpcUaClientService();
var command = new SubscribeCommand(new FakeOpcUaClientServiceFactory(fakeService))
{
Url = "opc.tcp://localhost:4840",
NodeId = "ns=2;s=TestVar",
ReconnectTimeoutSeconds = 0, // no time limit — Disconnected still ends the run
};
using var console = TestConsoleHelper.CreateConsole();
var task = Task.Run(async () => { await command.ExecuteAsync(console); }, TestContext.Current.CancellationToken);
await fakeService.SubscribeInvoked.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken);
fakeService.RaiseConnectionStateChanged(Shared.Models.ConnectionState.Reconnecting,
Shared.Models.ConnectionState.Disconnected, "opc.tcp://localhost:4840");
var ex = await Should.ThrowAsync<CommandException>(() => task.WaitAsync(TimeSpan.FromSeconds(15), TestContext.Current.CancellationToken));
ex.Message.ShouldContain("gave up");
}
[Fact]
public async Task Execute_RejectsNegativeReconnectTimeout()
{
var command = new SubscribeCommand(new FakeOpcUaClientServiceFactory(new FakeOpcUaClientService()))
{
Url = "opc.tcp://localhost:4840",
NodeId = "ns=2;s=TestVar",
ReconnectTimeoutSeconds = -1,
};
using var console = TestConsoleHelper.CreateConsole();
var ex = await Should.ThrowAsync<CommandException>(async () => await command.ExecuteAsync(console));
ex.Message.ShouldContain("--reconnect-timeout");
}
}