Add cross-platform OPC UA client stack: shared library, CLI tool, and Avalonia UI
Implements Client.Shared (IOpcUaClientService with connection lifecycle, failover, browse, read/write, subscriptions, alarms, history, redundancy), Client.CLI (8 CliFx commands mirroring tools/opcuacli-dotnet), and Client.UI (Avalonia desktop app with tree browser, read/write, subscriptions, alarms, and history tabs). All three target .NET 10 and are covered by 249 unit tests. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
168
tests/ZB.MOM.WW.LmxOpcUa.Client.CLI.Tests/AlarmsCommandTests.cs
Normal file
168
tests/ZB.MOM.WW.LmxOpcUa.Client.CLI.Tests/AlarmsCommandTests.cs
Normal file
@@ -0,0 +1,168 @@
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.CLI.Commands;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.CLI.Tests.Fakes;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.CLI.Tests;
|
||||
|
||||
public class AlarmsCommandTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task Execute_SubscribesToAlarms()
|
||||
{
|
||||
var fakeService = new FakeOpcUaClientService();
|
||||
var factory = new FakeOpcUaClientServiceFactory(fakeService);
|
||||
var command = new AlarmsCommand(factory)
|
||||
{
|
||||
Url = "opc.tcp://localhost:4840",
|
||||
Interval = 2000
|
||||
};
|
||||
|
||||
using var console = TestConsoleHelper.CreateConsole();
|
||||
|
||||
var task = Task.Run(async () =>
|
||||
{
|
||||
await command.ExecuteAsync(console);
|
||||
});
|
||||
|
||||
await Task.Delay(100);
|
||||
console.RequestCancellation();
|
||||
await task;
|
||||
|
||||
fakeService.SubscribeAlarmsCalls.Count.ShouldBe(1);
|
||||
fakeService.SubscribeAlarmsCalls[0].IntervalMs.ShouldBe(2000);
|
||||
fakeService.SubscribeAlarmsCalls[0].SourceNodeId.ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Execute_WithNode_PassesSourceNodeId()
|
||||
{
|
||||
var fakeService = new FakeOpcUaClientService();
|
||||
var factory = new FakeOpcUaClientServiceFactory(fakeService);
|
||||
var command = new AlarmsCommand(factory)
|
||||
{
|
||||
Url = "opc.tcp://localhost:4840",
|
||||
NodeId = "ns=2;s=AlarmSource"
|
||||
};
|
||||
|
||||
using var console = TestConsoleHelper.CreateConsole();
|
||||
|
||||
var task = Task.Run(async () =>
|
||||
{
|
||||
await command.ExecuteAsync(console);
|
||||
});
|
||||
|
||||
await Task.Delay(100);
|
||||
console.RequestCancellation();
|
||||
await task;
|
||||
|
||||
fakeService.SubscribeAlarmsCalls.Count.ShouldBe(1);
|
||||
fakeService.SubscribeAlarmsCalls[0].SourceNodeId.ShouldNotBeNull();
|
||||
fakeService.SubscribeAlarmsCalls[0].SourceNodeId!.Identifier.ShouldBe("AlarmSource");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Execute_WithRefresh_RequestsConditionRefresh()
|
||||
{
|
||||
var fakeService = new FakeOpcUaClientService();
|
||||
var factory = new FakeOpcUaClientServiceFactory(fakeService);
|
||||
var command = new AlarmsCommand(factory)
|
||||
{
|
||||
Url = "opc.tcp://localhost:4840",
|
||||
Refresh = true
|
||||
};
|
||||
|
||||
using var console = TestConsoleHelper.CreateConsole();
|
||||
|
||||
var task = Task.Run(async () =>
|
||||
{
|
||||
await command.ExecuteAsync(console);
|
||||
});
|
||||
|
||||
await Task.Delay(100);
|
||||
console.RequestCancellation();
|
||||
await task;
|
||||
|
||||
fakeService.RequestConditionRefreshCalled.ShouldBeTrue();
|
||||
var output = TestConsoleHelper.GetOutput(console);
|
||||
output.ShouldContain("Condition refresh requested.");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Execute_RefreshFailure_PrintsError()
|
||||
{
|
||||
var fakeService = new FakeOpcUaClientService
|
||||
{
|
||||
ConditionRefreshException = new NotSupportedException("Not supported")
|
||||
};
|
||||
var factory = new FakeOpcUaClientServiceFactory(fakeService);
|
||||
var command = new AlarmsCommand(factory)
|
||||
{
|
||||
Url = "opc.tcp://localhost:4840",
|
||||
Refresh = true
|
||||
};
|
||||
|
||||
using var console = TestConsoleHelper.CreateConsole();
|
||||
|
||||
var task = Task.Run(async () =>
|
||||
{
|
||||
await command.ExecuteAsync(console);
|
||||
});
|
||||
|
||||
await Task.Delay(100);
|
||||
console.RequestCancellation();
|
||||
await task;
|
||||
|
||||
var output = TestConsoleHelper.GetOutput(console);
|
||||
output.ShouldContain("Condition refresh not supported:");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Execute_UnsubscribesOnCancellation()
|
||||
{
|
||||
var fakeService = new FakeOpcUaClientService();
|
||||
var factory = new FakeOpcUaClientServiceFactory(fakeService);
|
||||
var command = new AlarmsCommand(factory)
|
||||
{
|
||||
Url = "opc.tcp://localhost:4840"
|
||||
};
|
||||
|
||||
using var console = TestConsoleHelper.CreateConsole();
|
||||
|
||||
var task = Task.Run(async () =>
|
||||
{
|
||||
await command.ExecuteAsync(console);
|
||||
});
|
||||
|
||||
await Task.Delay(100);
|
||||
console.RequestCancellation();
|
||||
await task;
|
||||
|
||||
fakeService.UnsubscribeAlarmsCalled.ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Execute_DisconnectsInFinally()
|
||||
{
|
||||
var fakeService = new FakeOpcUaClientService();
|
||||
var factory = new FakeOpcUaClientServiceFactory(fakeService);
|
||||
var command = new AlarmsCommand(factory)
|
||||
{
|
||||
Url = "opc.tcp://localhost:4840"
|
||||
};
|
||||
|
||||
using var console = TestConsoleHelper.CreateConsole();
|
||||
|
||||
var task = Task.Run(async () =>
|
||||
{
|
||||
await command.ExecuteAsync(console);
|
||||
});
|
||||
|
||||
await Task.Delay(100);
|
||||
console.RequestCancellation();
|
||||
await task;
|
||||
|
||||
fakeService.DisconnectCalled.ShouldBeTrue();
|
||||
fakeService.DisposeCalled.ShouldBeTrue();
|
||||
}
|
||||
}
|
||||
146
tests/ZB.MOM.WW.LmxOpcUa.Client.CLI.Tests/BrowseCommandTests.cs
Normal file
146
tests/ZB.MOM.WW.LmxOpcUa.Client.CLI.Tests/BrowseCommandTests.cs
Normal file
@@ -0,0 +1,146 @@
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.CLI.Commands;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.CLI.Tests.Fakes;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
|
||||
using BrowseResult = ZB.MOM.WW.LmxOpcUa.Client.Shared.Models.BrowseResult;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.CLI.Tests;
|
||||
|
||||
public class BrowseCommandTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task Execute_PrintsBrowseResults()
|
||||
{
|
||||
var fakeService = new FakeOpcUaClientService
|
||||
{
|
||||
BrowseResults = new List<BrowseResult>
|
||||
{
|
||||
new BrowseResult("ns=2;s=Obj1", "Object1", "Object", true),
|
||||
new BrowseResult("ns=2;s=Var1", "Variable1", "Variable", false),
|
||||
new BrowseResult("ns=2;s=Meth1", "Method1", "Method", false)
|
||||
}
|
||||
};
|
||||
var factory = new FakeOpcUaClientServiceFactory(fakeService);
|
||||
var command = new BrowseCommand(factory)
|
||||
{
|
||||
Url = "opc.tcp://localhost:4840"
|
||||
};
|
||||
|
||||
using var console = TestConsoleHelper.CreateConsole();
|
||||
await command.ExecuteAsync(console);
|
||||
|
||||
var output = TestConsoleHelper.GetOutput(console);
|
||||
output.ShouldContain("[Object] Object1 (NodeId: ns=2;s=Obj1)");
|
||||
output.ShouldContain("[Variable] Variable1 (NodeId: ns=2;s=Var1)");
|
||||
output.ShouldContain("[Method] Method1 (NodeId: ns=2;s=Meth1)");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Execute_BrowsesFromSpecifiedNode()
|
||||
{
|
||||
var fakeService = new FakeOpcUaClientService
|
||||
{
|
||||
BrowseResults = new List<BrowseResult>()
|
||||
};
|
||||
var factory = new FakeOpcUaClientServiceFactory(fakeService);
|
||||
var command = new BrowseCommand(factory)
|
||||
{
|
||||
Url = "opc.tcp://localhost:4840",
|
||||
NodeId = "ns=2;s=StartNode"
|
||||
};
|
||||
|
||||
using var console = TestConsoleHelper.CreateConsole();
|
||||
await command.ExecuteAsync(console);
|
||||
|
||||
fakeService.BrowseNodeIds.Count.ShouldBe(1);
|
||||
fakeService.BrowseNodeIds[0].ShouldNotBeNull();
|
||||
fakeService.BrowseNodeIds[0]!.Identifier.ShouldBe("StartNode");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Execute_DefaultBrowsesFromNull()
|
||||
{
|
||||
var fakeService = new FakeOpcUaClientService
|
||||
{
|
||||
BrowseResults = new List<BrowseResult>()
|
||||
};
|
||||
var factory = new FakeOpcUaClientServiceFactory(fakeService);
|
||||
var command = new BrowseCommand(factory)
|
||||
{
|
||||
Url = "opc.tcp://localhost:4840"
|
||||
};
|
||||
|
||||
using var console = TestConsoleHelper.CreateConsole();
|
||||
await command.ExecuteAsync(console);
|
||||
|
||||
fakeService.BrowseNodeIds.Count.ShouldBe(1);
|
||||
fakeService.BrowseNodeIds[0].ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Execute_NonRecursive_BrowsesSingleLevel()
|
||||
{
|
||||
var fakeService = new FakeOpcUaClientService
|
||||
{
|
||||
BrowseResults = new List<BrowseResult>
|
||||
{
|
||||
new BrowseResult("ns=2;s=Child", "Child", "Object", true)
|
||||
}
|
||||
};
|
||||
var factory = new FakeOpcUaClientServiceFactory(fakeService);
|
||||
var command = new BrowseCommand(factory)
|
||||
{
|
||||
Url = "opc.tcp://localhost:4840",
|
||||
Depth = 5 // Should be ignored without recursive flag
|
||||
};
|
||||
|
||||
using var console = TestConsoleHelper.CreateConsole();
|
||||
await command.ExecuteAsync(console);
|
||||
|
||||
// Only the root level browse should happen, not child
|
||||
fakeService.BrowseNodeIds.Count.ShouldBe(1);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Execute_Recursive_BrowsesChildren()
|
||||
{
|
||||
var fakeService = new FakeOpcUaClientService();
|
||||
// Override browse to return children only on first call
|
||||
// We can't easily do this with the simple fake, but the default returns results with HasChildren=true
|
||||
// which will trigger child browse with recursive=true, depth=2
|
||||
var factory = new FakeOpcUaClientServiceFactory(fakeService);
|
||||
var command = new BrowseCommand(factory)
|
||||
{
|
||||
Url = "opc.tcp://localhost:4840",
|
||||
Recursive = true,
|
||||
Depth = 2
|
||||
};
|
||||
|
||||
using var console = TestConsoleHelper.CreateConsole();
|
||||
await command.ExecuteAsync(console);
|
||||
|
||||
// Root browse + child browse (for Node1 which HasChildren=true)
|
||||
fakeService.BrowseNodeIds.Count.ShouldBeGreaterThan(1);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Execute_DisconnectsInFinally()
|
||||
{
|
||||
var fakeService = new FakeOpcUaClientService
|
||||
{
|
||||
BrowseResults = new List<BrowseResult>()
|
||||
};
|
||||
var factory = new FakeOpcUaClientServiceFactory(fakeService);
|
||||
var command = new BrowseCommand(factory)
|
||||
{
|
||||
Url = "opc.tcp://localhost:4840"
|
||||
};
|
||||
|
||||
using var console = TestConsoleHelper.CreateConsole();
|
||||
await command.ExecuteAsync(console);
|
||||
|
||||
fakeService.DisconnectCalled.ShouldBeTrue();
|
||||
fakeService.DisposeCalled.ShouldBeTrue();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
using CliFx.Infrastructure;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.CLI.Commands;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.CLI.Tests.Fakes;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.CLI.Tests;
|
||||
|
||||
public class CommandBaseTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task CommonOptions_MapToConnectionSettings_Correctly()
|
||||
{
|
||||
var fakeService = new FakeOpcUaClientService();
|
||||
var factory = new FakeOpcUaClientServiceFactory(fakeService);
|
||||
var command = new ConnectCommand(factory)
|
||||
{
|
||||
Url = "opc.tcp://myserver:4840",
|
||||
Username = "admin",
|
||||
Password = "secret",
|
||||
Security = "sign",
|
||||
FailoverUrls = "opc.tcp://backup1:4840,opc.tcp://backup2:4840"
|
||||
};
|
||||
|
||||
using var console = TestConsoleHelper.CreateConsole();
|
||||
await command.ExecuteAsync(console);
|
||||
|
||||
var settings = fakeService.LastConnectionSettings;
|
||||
settings.ShouldNotBeNull();
|
||||
settings.EndpointUrl.ShouldBe("opc.tcp://myserver:4840");
|
||||
settings.Username.ShouldBe("admin");
|
||||
settings.Password.ShouldBe("secret");
|
||||
settings.SecurityMode.ShouldBe(SecurityMode.Sign);
|
||||
settings.FailoverUrls.ShouldNotBeNull();
|
||||
settings.FailoverUrls!.Length.ShouldBe(3); // primary + 2 failover
|
||||
settings.FailoverUrls[0].ShouldBe("opc.tcp://myserver:4840");
|
||||
settings.AutoAcceptCertificates.ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SecurityOption_Encrypt_MapsToSignAndEncrypt()
|
||||
{
|
||||
var fakeService = new FakeOpcUaClientService();
|
||||
var factory = new FakeOpcUaClientServiceFactory(fakeService);
|
||||
var command = new ConnectCommand(factory)
|
||||
{
|
||||
Url = "opc.tcp://localhost:4840",
|
||||
Security = "encrypt"
|
||||
};
|
||||
|
||||
using var console = TestConsoleHelper.CreateConsole();
|
||||
await command.ExecuteAsync(console);
|
||||
|
||||
fakeService.LastConnectionSettings!.SecurityMode.ShouldBe(SecurityMode.SignAndEncrypt);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SecurityOption_None_MapsToNone()
|
||||
{
|
||||
var fakeService = new FakeOpcUaClientService();
|
||||
var factory = new FakeOpcUaClientServiceFactory(fakeService);
|
||||
var command = new ConnectCommand(factory)
|
||||
{
|
||||
Url = "opc.tcp://localhost:4840",
|
||||
Security = "none"
|
||||
};
|
||||
|
||||
using var console = TestConsoleHelper.CreateConsole();
|
||||
await command.ExecuteAsync(console);
|
||||
|
||||
fakeService.LastConnectionSettings!.SecurityMode.ShouldBe(SecurityMode.None);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task NoFailoverUrls_FailoverUrlsIsNull()
|
||||
{
|
||||
var fakeService = new FakeOpcUaClientService();
|
||||
var factory = new FakeOpcUaClientServiceFactory(fakeService);
|
||||
var command = new ConnectCommand(factory)
|
||||
{
|
||||
Url = "opc.tcp://localhost:4840"
|
||||
};
|
||||
|
||||
using var console = TestConsoleHelper.CreateConsole();
|
||||
await command.ExecuteAsync(console);
|
||||
|
||||
fakeService.LastConnectionSettings!.FailoverUrls.ShouldBeNull();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.CLI.Commands;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.CLI.Tests.Fakes;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.CLI.Tests;
|
||||
|
||||
public class ConnectCommandTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task Execute_PrintsConnectionInfo()
|
||||
{
|
||||
var fakeService = new FakeOpcUaClientService
|
||||
{
|
||||
ConnectionInfoResult = new ConnectionInfo(
|
||||
"opc.tcp://testhost:4840",
|
||||
"MyServer",
|
||||
"SignAndEncrypt",
|
||||
"http://opcfoundation.org/UA/SecurityPolicy#Basic256Sha256",
|
||||
"session-42",
|
||||
"MySession")
|
||||
};
|
||||
var factory = new FakeOpcUaClientServiceFactory(fakeService);
|
||||
var command = new ConnectCommand(factory)
|
||||
{
|
||||
Url = "opc.tcp://testhost:4840"
|
||||
};
|
||||
|
||||
using var console = TestConsoleHelper.CreateConsole();
|
||||
await command.ExecuteAsync(console);
|
||||
|
||||
var output = TestConsoleHelper.GetOutput(console);
|
||||
output.ShouldContain("Connected to: opc.tcp://testhost:4840");
|
||||
output.ShouldContain("Server: MyServer");
|
||||
output.ShouldContain("Security Mode: SignAndEncrypt");
|
||||
output.ShouldContain("Security Policy: http://opcfoundation.org/UA/SecurityPolicy#Basic256Sha256");
|
||||
output.ShouldContain("Connection successful.");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Execute_CallsConnectAndDisconnect()
|
||||
{
|
||||
var fakeService = new FakeOpcUaClientService();
|
||||
var factory = new FakeOpcUaClientServiceFactory(fakeService);
|
||||
var command = new ConnectCommand(factory)
|
||||
{
|
||||
Url = "opc.tcp://localhost:4840"
|
||||
};
|
||||
|
||||
using var console = TestConsoleHelper.CreateConsole();
|
||||
await command.ExecuteAsync(console);
|
||||
|
||||
fakeService.ConnectCalled.ShouldBeTrue();
|
||||
fakeService.DisconnectCalled.ShouldBeTrue();
|
||||
fakeService.DisposeCalled.ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Execute_DisconnectsOnError()
|
||||
{
|
||||
var fakeService = new FakeOpcUaClientService
|
||||
{
|
||||
ConnectException = new InvalidOperationException("Connection refused")
|
||||
};
|
||||
var factory = new FakeOpcUaClientServiceFactory(fakeService);
|
||||
var command = new ConnectCommand(factory)
|
||||
{
|
||||
Url = "opc.tcp://localhost:4840"
|
||||
};
|
||||
|
||||
using var console = TestConsoleHelper.CreateConsole();
|
||||
// The command should propagate the exception but still clean up.
|
||||
// Since connect fails, service is null in finally, so no disconnect.
|
||||
await Should.ThrowAsync<InvalidOperationException>(
|
||||
async () => await command.ExecuteAsync(console));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
using Opc.Ua;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.Shared;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
|
||||
using BrowseResult = ZB.MOM.WW.LmxOpcUa.Client.Shared.Models.BrowseResult;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.CLI.Tests.Fakes;
|
||||
|
||||
/// <summary>
|
||||
/// Fake implementation of <see cref="IOpcUaClientService"/> for unit testing commands.
|
||||
/// Records all method calls and returns configurable results.
|
||||
/// </summary>
|
||||
public sealed class FakeOpcUaClientService : IOpcUaClientService
|
||||
{
|
||||
// Track calls
|
||||
public bool ConnectCalled { get; private set; }
|
||||
public ConnectionSettings? LastConnectionSettings { get; private set; }
|
||||
public bool DisconnectCalled { get; private set; }
|
||||
public bool DisposeCalled { get; private set; }
|
||||
public List<NodeId> ReadNodeIds { get; } = new();
|
||||
public List<(NodeId NodeId, object Value)> WriteValues { get; } = new();
|
||||
public List<NodeId?> BrowseNodeIds { get; } = new();
|
||||
public List<(NodeId NodeId, int IntervalMs)> SubscribeCalls { get; } = new();
|
||||
public List<NodeId> UnsubscribeCalls { get; } = new();
|
||||
public List<(NodeId? SourceNodeId, int IntervalMs)> SubscribeAlarmsCalls { get; } = new();
|
||||
public bool UnsubscribeAlarmsCalled { get; private set; }
|
||||
public bool RequestConditionRefreshCalled { get; private set; }
|
||||
public List<(NodeId NodeId, DateTime Start, DateTime End, int MaxValues)> HistoryReadRawCalls { get; } = new();
|
||||
public List<(NodeId NodeId, DateTime Start, DateTime End, AggregateType Aggregate, double IntervalMs)> HistoryReadAggregateCalls { get; } = new();
|
||||
public bool GetRedundancyInfoCalled { get; private set; }
|
||||
|
||||
// Configurable results
|
||||
public ConnectionInfo ConnectionInfoResult { get; set; } = new ConnectionInfo(
|
||||
"opc.tcp://localhost:4840",
|
||||
"TestServer",
|
||||
"None",
|
||||
"http://opcfoundation.org/UA/SecurityPolicy#None",
|
||||
"session-1",
|
||||
"TestSession");
|
||||
|
||||
public DataValue ReadValueResult { get; set; } = new DataValue(
|
||||
new Variant(42),
|
||||
StatusCodes.Good,
|
||||
DateTime.UtcNow,
|
||||
DateTime.UtcNow);
|
||||
|
||||
public StatusCode WriteStatusCodeResult { get; set; } = StatusCodes.Good;
|
||||
|
||||
public IReadOnlyList<BrowseResult> BrowseResults { get; set; } = new List<BrowseResult>
|
||||
{
|
||||
new BrowseResult("ns=2;s=Node1", "Node1", "Object", true),
|
||||
new BrowseResult("ns=2;s=Node2", "Node2", "Variable", false)
|
||||
};
|
||||
|
||||
public IReadOnlyList<DataValue> HistoryReadResult { get; set; } = new List<DataValue>
|
||||
{
|
||||
new DataValue(new Variant(10.0), StatusCodes.Good, DateTime.UtcNow.AddHours(-1), DateTime.UtcNow),
|
||||
new DataValue(new Variant(20.0), StatusCodes.Good, DateTime.UtcNow, DateTime.UtcNow)
|
||||
};
|
||||
|
||||
public RedundancyInfo RedundancyInfoResult { get; set; } = new RedundancyInfo(
|
||||
"Warm", 200, new[] { "urn:server1", "urn:server2" }, "urn:app:test");
|
||||
|
||||
public Exception? ConnectException { get; set; }
|
||||
public Exception? ReadException { get; set; }
|
||||
public Exception? WriteException { get; set; }
|
||||
public Exception? ConditionRefreshException { get; set; }
|
||||
|
||||
// IOpcUaClientService implementation
|
||||
public bool IsConnected => ConnectCalled && !DisconnectCalled;
|
||||
public ConnectionInfo? CurrentConnectionInfo => ConnectCalled ? ConnectionInfoResult : null;
|
||||
|
||||
public event EventHandler<DataChangedEventArgs>? DataChanged;
|
||||
public event EventHandler<AlarmEventArgs>? AlarmEvent;
|
||||
public event EventHandler<ConnectionStateChangedEventArgs>? ConnectionStateChanged;
|
||||
|
||||
public Task<ConnectionInfo> ConnectAsync(ConnectionSettings settings, CancellationToken ct = default)
|
||||
{
|
||||
ConnectCalled = true;
|
||||
LastConnectionSettings = settings;
|
||||
if (ConnectException != null) throw ConnectException;
|
||||
return Task.FromResult(ConnectionInfoResult);
|
||||
}
|
||||
|
||||
public Task DisconnectAsync(CancellationToken ct = default)
|
||||
{
|
||||
DisconnectCalled = true;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task<DataValue> ReadValueAsync(NodeId nodeId, CancellationToken ct = default)
|
||||
{
|
||||
ReadNodeIds.Add(nodeId);
|
||||
if (ReadException != null) throw ReadException;
|
||||
return Task.FromResult(ReadValueResult);
|
||||
}
|
||||
|
||||
public Task<StatusCode> WriteValueAsync(NodeId nodeId, object value, CancellationToken ct = default)
|
||||
{
|
||||
WriteValues.Add((nodeId, value));
|
||||
if (WriteException != null) throw WriteException;
|
||||
return Task.FromResult(WriteStatusCodeResult);
|
||||
}
|
||||
|
||||
public Task<IReadOnlyList<BrowseResult>> BrowseAsync(NodeId? parentNodeId = null, CancellationToken ct = default)
|
||||
{
|
||||
BrowseNodeIds.Add(parentNodeId);
|
||||
return Task.FromResult(BrowseResults);
|
||||
}
|
||||
|
||||
public Task SubscribeAsync(NodeId nodeId, int intervalMs = 1000, CancellationToken ct = default)
|
||||
{
|
||||
SubscribeCalls.Add((nodeId, intervalMs));
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task UnsubscribeAsync(NodeId nodeId, CancellationToken ct = default)
|
||||
{
|
||||
UnsubscribeCalls.Add(nodeId);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task SubscribeAlarmsAsync(NodeId? sourceNodeId = null, int intervalMs = 1000, CancellationToken ct = default)
|
||||
{
|
||||
SubscribeAlarmsCalls.Add((sourceNodeId, intervalMs));
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task UnsubscribeAlarmsAsync(CancellationToken ct = default)
|
||||
{
|
||||
UnsubscribeAlarmsCalled = true;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task RequestConditionRefreshAsync(CancellationToken ct = default)
|
||||
{
|
||||
RequestConditionRefreshCalled = true;
|
||||
if (ConditionRefreshException != null) throw ConditionRefreshException;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task<IReadOnlyList<DataValue>> HistoryReadRawAsync(
|
||||
NodeId nodeId, DateTime startTime, DateTime endTime, int maxValues = 1000, CancellationToken ct = default)
|
||||
{
|
||||
HistoryReadRawCalls.Add((nodeId, startTime, endTime, maxValues));
|
||||
return Task.FromResult(HistoryReadResult);
|
||||
}
|
||||
|
||||
public Task<IReadOnlyList<DataValue>> HistoryReadAggregateAsync(
|
||||
NodeId nodeId, DateTime startTime, DateTime endTime, AggregateType aggregate,
|
||||
double intervalMs = 3600000, CancellationToken ct = default)
|
||||
{
|
||||
HistoryReadAggregateCalls.Add((nodeId, startTime, endTime, aggregate, intervalMs));
|
||||
return Task.FromResult(HistoryReadResult);
|
||||
}
|
||||
|
||||
public Task<RedundancyInfo> GetRedundancyInfoAsync(CancellationToken ct = default)
|
||||
{
|
||||
GetRedundancyInfoCalled = true;
|
||||
return Task.FromResult(RedundancyInfoResult);
|
||||
}
|
||||
|
||||
/// <summary>Raises the DataChanged event for testing subscribe commands.</summary>
|
||||
public void RaiseDataChanged(string nodeId, DataValue value)
|
||||
{
|
||||
DataChanged?.Invoke(this, new DataChangedEventArgs(nodeId, value));
|
||||
}
|
||||
|
||||
/// <summary>Raises the AlarmEvent for testing alarm commands.</summary>
|
||||
public void RaiseAlarmEvent(AlarmEventArgs args)
|
||||
{
|
||||
AlarmEvent?.Invoke(this, args);
|
||||
}
|
||||
|
||||
/// <summary>Raises the ConnectionStateChanged event for testing.</summary>
|
||||
public void RaiseConnectionStateChanged(ConnectionState oldState, ConnectionState newState, string endpointUrl)
|
||||
{
|
||||
ConnectionStateChanged?.Invoke(this, new ConnectionStateChangedEventArgs(oldState, newState, endpointUrl));
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
DisposeCalled = true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.Shared;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.CLI.Tests.Fakes;
|
||||
|
||||
/// <summary>
|
||||
/// Fake factory that returns a pre-configured <see cref="FakeOpcUaClientService"/> for testing.
|
||||
/// </summary>
|
||||
public sealed class FakeOpcUaClientServiceFactory : IOpcUaClientServiceFactory
|
||||
{
|
||||
private readonly FakeOpcUaClientService _service;
|
||||
|
||||
public FakeOpcUaClientServiceFactory(FakeOpcUaClientService service)
|
||||
{
|
||||
_service = service;
|
||||
}
|
||||
|
||||
public IOpcUaClientService Create() => _service;
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
using Opc.Ua;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.CLI.Commands;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.CLI.Tests.Fakes;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.CLI.Tests;
|
||||
|
||||
public class HistoryReadCommandTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task Execute_RawRead_PrintsValues()
|
||||
{
|
||||
var time1 = new DateTime(2025, 6, 15, 10, 0, 0, DateTimeKind.Utc);
|
||||
var time2 = new DateTime(2025, 6, 15, 11, 0, 0, DateTimeKind.Utc);
|
||||
var fakeService = new FakeOpcUaClientService
|
||||
{
|
||||
HistoryReadResult = new List<DataValue>
|
||||
{
|
||||
new DataValue(new Variant(10.5), StatusCodes.Good, time1, time1),
|
||||
new DataValue(new Variant(20.3), StatusCodes.Good, time2, time2)
|
||||
}
|
||||
};
|
||||
var factory = new FakeOpcUaClientServiceFactory(fakeService);
|
||||
var command = new HistoryReadCommand(factory)
|
||||
{
|
||||
Url = "opc.tcp://localhost:4840",
|
||||
NodeId = "ns=2;s=HistNode",
|
||||
StartTime = "2025-06-15T00:00:00Z",
|
||||
EndTime = "2025-06-15T23:59:59Z"
|
||||
};
|
||||
|
||||
using var console = TestConsoleHelper.CreateConsole();
|
||||
await command.ExecuteAsync(console);
|
||||
|
||||
var output = TestConsoleHelper.GetOutput(console);
|
||||
output.ShouldContain("History for ns=2;s=HistNode");
|
||||
output.ShouldContain("Timestamp");
|
||||
output.ShouldContain("Value");
|
||||
output.ShouldContain("Status");
|
||||
output.ShouldContain("2 values returned.");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Execute_RawRead_CallsHistoryReadRaw()
|
||||
{
|
||||
var fakeService = new FakeOpcUaClientService();
|
||||
var factory = new FakeOpcUaClientServiceFactory(fakeService);
|
||||
var command = new HistoryReadCommand(factory)
|
||||
{
|
||||
Url = "opc.tcp://localhost:4840",
|
||||
NodeId = "ns=2;s=HistNode",
|
||||
MaxValues = 500
|
||||
};
|
||||
|
||||
using var console = TestConsoleHelper.CreateConsole();
|
||||
await command.ExecuteAsync(console);
|
||||
|
||||
fakeService.HistoryReadRawCalls.Count.ShouldBe(1);
|
||||
fakeService.HistoryReadRawCalls[0].MaxValues.ShouldBe(500);
|
||||
fakeService.HistoryReadRawCalls[0].NodeId.Identifier.ShouldBe("HistNode");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Execute_AggregateRead_CallsHistoryReadAggregate()
|
||||
{
|
||||
var fakeService = new FakeOpcUaClientService();
|
||||
var factory = new FakeOpcUaClientServiceFactory(fakeService);
|
||||
var command = new HistoryReadCommand(factory)
|
||||
{
|
||||
Url = "opc.tcp://localhost:4840",
|
||||
NodeId = "ns=2;s=HistNode",
|
||||
Aggregate = "Average",
|
||||
IntervalMs = 60000
|
||||
};
|
||||
|
||||
using var console = TestConsoleHelper.CreateConsole();
|
||||
await command.ExecuteAsync(console);
|
||||
|
||||
fakeService.HistoryReadAggregateCalls.Count.ShouldBe(1);
|
||||
fakeService.HistoryReadAggregateCalls[0].Aggregate.ShouldBe(AggregateType.Average);
|
||||
fakeService.HistoryReadAggregateCalls[0].IntervalMs.ShouldBe(60000);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Execute_AggregateRead_PrintsAggregateInfo()
|
||||
{
|
||||
var fakeService = new FakeOpcUaClientService();
|
||||
var factory = new FakeOpcUaClientServiceFactory(fakeService);
|
||||
var command = new HistoryReadCommand(factory)
|
||||
{
|
||||
Url = "opc.tcp://localhost:4840",
|
||||
NodeId = "ns=2;s=HistNode",
|
||||
Aggregate = "Maximum",
|
||||
IntervalMs = 7200000
|
||||
};
|
||||
|
||||
using var console = TestConsoleHelper.CreateConsole();
|
||||
await command.ExecuteAsync(console);
|
||||
|
||||
var output = TestConsoleHelper.GetOutput(console);
|
||||
output.ShouldContain("Maximum");
|
||||
output.ShouldContain("7200000");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Execute_InvalidAggregate_ThrowsArgumentException()
|
||||
{
|
||||
var fakeService = new FakeOpcUaClientService();
|
||||
var factory = new FakeOpcUaClientServiceFactory(fakeService);
|
||||
var command = new HistoryReadCommand(factory)
|
||||
{
|
||||
Url = "opc.tcp://localhost:4840",
|
||||
NodeId = "ns=2;s=HistNode",
|
||||
Aggregate = "InvalidAgg"
|
||||
};
|
||||
|
||||
using var console = TestConsoleHelper.CreateConsole();
|
||||
await Should.ThrowAsync<ArgumentException>(
|
||||
async () => await command.ExecuteAsync(console));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Execute_DisconnectsInFinally()
|
||||
{
|
||||
var fakeService = new FakeOpcUaClientService();
|
||||
var factory = new FakeOpcUaClientServiceFactory(fakeService);
|
||||
var command = new HistoryReadCommand(factory)
|
||||
{
|
||||
Url = "opc.tcp://localhost:4840",
|
||||
NodeId = "ns=2;s=HistNode"
|
||||
};
|
||||
|
||||
using var console = TestConsoleHelper.CreateConsole();
|
||||
await command.ExecuteAsync(console);
|
||||
|
||||
fakeService.DisconnectCalled.ShouldBeTrue();
|
||||
fakeService.DisposeCalled.ShouldBeTrue();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
using Opc.Ua;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.CLI.Helpers;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.CLI.Tests;
|
||||
|
||||
public class NodeIdParserTests
|
||||
{
|
||||
[Fact]
|
||||
public void Parse_NullInput_ReturnsNull()
|
||||
{
|
||||
NodeIdParser.Parse(null).ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Parse_EmptyString_ReturnsNull()
|
||||
{
|
||||
NodeIdParser.Parse("").ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Parse_WhitespaceOnly_ReturnsNull()
|
||||
{
|
||||
NodeIdParser.Parse(" ").ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Parse_StandardStringFormat_ReturnsNodeId()
|
||||
{
|
||||
var result = NodeIdParser.Parse("ns=2;s=MyNode");
|
||||
result.ShouldNotBeNull();
|
||||
result.NamespaceIndex.ShouldBe((ushort)2);
|
||||
result.Identifier.ShouldBe("MyNode");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Parse_NumericFormat_ReturnsNodeId()
|
||||
{
|
||||
var result = NodeIdParser.Parse("i=85");
|
||||
result.ShouldNotBeNull();
|
||||
result.IdType.ShouldBe(IdType.Numeric);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Parse_BareNumeric_ReturnsNamespace0NumericNodeId()
|
||||
{
|
||||
var result = NodeIdParser.Parse("85");
|
||||
result.ShouldNotBeNull();
|
||||
result.NamespaceIndex.ShouldBe((ushort)0);
|
||||
result.Identifier.ShouldBe((uint)85);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Parse_WithWhitespacePadding_Trims()
|
||||
{
|
||||
var result = NodeIdParser.Parse(" ns=2;s=MyNode ");
|
||||
result.ShouldNotBeNull();
|
||||
result.Identifier.ShouldBe("MyNode");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Parse_InvalidFormat_ThrowsFormatException()
|
||||
{
|
||||
Should.Throw<FormatException>(() => NodeIdParser.Parse("not-a-node-id"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ParseRequired_NullInput_ThrowsArgumentException()
|
||||
{
|
||||
Should.Throw<ArgumentException>(() => NodeIdParser.ParseRequired(null));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ParseRequired_EmptyInput_ThrowsArgumentException()
|
||||
{
|
||||
Should.Throw<ArgumentException>(() => NodeIdParser.ParseRequired(""));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ParseRequired_ValidInput_ReturnsNodeId()
|
||||
{
|
||||
var result = NodeIdParser.ParseRequired("ns=2;s=TestNode");
|
||||
result.ShouldNotBeNull();
|
||||
result.Identifier.ShouldBe("TestNode");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
// This file intentionally left empty. Real tests are in separate files.
|
||||
@@ -0,0 +1,99 @@
|
||||
using Opc.Ua;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.CLI.Commands;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.CLI.Tests.Fakes;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.CLI.Tests;
|
||||
|
||||
public class ReadCommandTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task Execute_PrintsReadValue()
|
||||
{
|
||||
var sourceTime = new DateTime(2025, 6, 15, 10, 30, 0, DateTimeKind.Utc);
|
||||
var serverTime = new DateTime(2025, 6, 15, 10, 30, 1, DateTimeKind.Utc);
|
||||
var fakeService = new FakeOpcUaClientService
|
||||
{
|
||||
ReadValueResult = new DataValue(
|
||||
new Variant("Hello"),
|
||||
StatusCodes.Good,
|
||||
sourceTime,
|
||||
serverTime)
|
||||
};
|
||||
var factory = new FakeOpcUaClientServiceFactory(fakeService);
|
||||
var command = new ReadCommand(factory)
|
||||
{
|
||||
Url = "opc.tcp://localhost:4840",
|
||||
NodeId = "ns=2;s=TestNode"
|
||||
};
|
||||
|
||||
using var console = TestConsoleHelper.CreateConsole();
|
||||
await command.ExecuteAsync(console);
|
||||
|
||||
var output = TestConsoleHelper.GetOutput(console);
|
||||
output.ShouldContain("Node: ns=2;s=TestNode");
|
||||
output.ShouldContain("Value: Hello");
|
||||
output.ShouldContain("Status:");
|
||||
output.ShouldContain("Source Time:");
|
||||
output.ShouldContain("Server Time:");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Execute_CallsReadValueWithCorrectNodeId()
|
||||
{
|
||||
var fakeService = new FakeOpcUaClientService();
|
||||
var factory = new FakeOpcUaClientServiceFactory(fakeService);
|
||||
var command = new ReadCommand(factory)
|
||||
{
|
||||
Url = "opc.tcp://localhost:4840",
|
||||
NodeId = "ns=2;s=MyVariable"
|
||||
};
|
||||
|
||||
using var console = TestConsoleHelper.CreateConsole();
|
||||
await command.ExecuteAsync(console);
|
||||
|
||||
fakeService.ReadNodeIds.Count.ShouldBe(1);
|
||||
fakeService.ReadNodeIds[0].Identifier.ShouldBe("MyVariable");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Execute_DisconnectsInFinally()
|
||||
{
|
||||
var fakeService = new FakeOpcUaClientService();
|
||||
var factory = new FakeOpcUaClientServiceFactory(fakeService);
|
||||
var command = new ReadCommand(factory)
|
||||
{
|
||||
Url = "opc.tcp://localhost:4840",
|
||||
NodeId = "ns=2;s=TestNode"
|
||||
};
|
||||
|
||||
using var console = TestConsoleHelper.CreateConsole();
|
||||
await command.ExecuteAsync(console);
|
||||
|
||||
fakeService.DisconnectCalled.ShouldBeTrue();
|
||||
fakeService.DisposeCalled.ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Execute_DisconnectsEvenOnReadError()
|
||||
{
|
||||
var fakeService = new FakeOpcUaClientService
|
||||
{
|
||||
ReadException = new InvalidOperationException("Read failed")
|
||||
};
|
||||
var factory = new FakeOpcUaClientServiceFactory(fakeService);
|
||||
var command = new ReadCommand(factory)
|
||||
{
|
||||
Url = "opc.tcp://localhost:4840",
|
||||
NodeId = "ns=2;s=TestNode"
|
||||
};
|
||||
|
||||
using var console = TestConsoleHelper.CreateConsole();
|
||||
await Should.ThrowAsync<InvalidOperationException>(
|
||||
async () => await command.ExecuteAsync(console));
|
||||
|
||||
fakeService.DisconnectCalled.ShouldBeTrue();
|
||||
fakeService.DisposeCalled.ShouldBeTrue();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.CLI.Commands;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.CLI.Tests.Fakes;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.CLI.Tests;
|
||||
|
||||
public class RedundancyCommandTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task Execute_PrintsRedundancyInfo()
|
||||
{
|
||||
var fakeService = new FakeOpcUaClientService
|
||||
{
|
||||
RedundancyInfoResult = new RedundancyInfo(
|
||||
"Hot", 250, new[] { "urn:server:primary", "urn:server:secondary" }, "urn:app:myserver")
|
||||
};
|
||||
var factory = new FakeOpcUaClientServiceFactory(fakeService);
|
||||
var command = new RedundancyCommand(factory)
|
||||
{
|
||||
Url = "opc.tcp://localhost:4840"
|
||||
};
|
||||
|
||||
using var console = TestConsoleHelper.CreateConsole();
|
||||
await command.ExecuteAsync(console);
|
||||
|
||||
var output = TestConsoleHelper.GetOutput(console);
|
||||
output.ShouldContain("Redundancy Mode: Hot");
|
||||
output.ShouldContain("Service Level: 250");
|
||||
output.ShouldContain("Server URIs:");
|
||||
output.ShouldContain(" - urn:server:primary");
|
||||
output.ShouldContain(" - urn:server:secondary");
|
||||
output.ShouldContain("Application URI: urn:app:myserver");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Execute_NoServerUris_OmitsUriSection()
|
||||
{
|
||||
var fakeService = new FakeOpcUaClientService
|
||||
{
|
||||
RedundancyInfoResult = new RedundancyInfo(
|
||||
"None", 100, Array.Empty<string>(), "urn:app:standalone")
|
||||
};
|
||||
var factory = new FakeOpcUaClientServiceFactory(fakeService);
|
||||
var command = new RedundancyCommand(factory)
|
||||
{
|
||||
Url = "opc.tcp://localhost:4840"
|
||||
};
|
||||
|
||||
using var console = TestConsoleHelper.CreateConsole();
|
||||
await command.ExecuteAsync(console);
|
||||
|
||||
var output = TestConsoleHelper.GetOutput(console);
|
||||
output.ShouldContain("Redundancy Mode: None");
|
||||
output.ShouldContain("Service Level: 100");
|
||||
output.ShouldNotContain("Server URIs:");
|
||||
output.ShouldContain("Application URI: urn:app:standalone");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Execute_CallsGetRedundancyInfo()
|
||||
{
|
||||
var fakeService = new FakeOpcUaClientService();
|
||||
var factory = new FakeOpcUaClientServiceFactory(fakeService);
|
||||
var command = new RedundancyCommand(factory)
|
||||
{
|
||||
Url = "opc.tcp://localhost:4840"
|
||||
};
|
||||
|
||||
using var console = TestConsoleHelper.CreateConsole();
|
||||
await command.ExecuteAsync(console);
|
||||
|
||||
fakeService.GetRedundancyInfoCalled.ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Execute_DisconnectsInFinally()
|
||||
{
|
||||
var fakeService = new FakeOpcUaClientService();
|
||||
var factory = new FakeOpcUaClientServiceFactory(fakeService);
|
||||
var command = new RedundancyCommand(factory)
|
||||
{
|
||||
Url = "opc.tcp://localhost:4840"
|
||||
};
|
||||
|
||||
using var console = TestConsoleHelper.CreateConsole();
|
||||
await command.ExecuteAsync(console);
|
||||
|
||||
fakeService.DisconnectCalled.ShouldBeTrue();
|
||||
fakeService.DisposeCalled.ShouldBeTrue();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
using Opc.Ua;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.CLI.Commands;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.CLI.Tests.Fakes;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.CLI.Tests;
|
||||
|
||||
public class SubscribeCommandTests
|
||||
{
|
||||
[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);
|
||||
});
|
||||
|
||||
// Give it a moment to subscribe, then cancel
|
||||
await Task.Delay(100);
|
||||
console.RequestCancellation();
|
||||
await task;
|
||||
|
||||
fakeService.SubscribeCalls.Count.ShouldBe(1);
|
||||
fakeService.SubscribeCalls[0].IntervalMs.ShouldBe(500);
|
||||
fakeService.SubscribeCalls[0].NodeId.Identifier.ShouldBe("TestVar");
|
||||
}
|
||||
|
||||
[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);
|
||||
});
|
||||
|
||||
await Task.Delay(100);
|
||||
console.RequestCancellation();
|
||||
await task;
|
||||
|
||||
fakeService.UnsubscribeCalls.Count.ShouldBe(1);
|
||||
}
|
||||
|
||||
[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);
|
||||
});
|
||||
|
||||
await Task.Delay(100);
|
||||
console.RequestCancellation();
|
||||
await task;
|
||||
|
||||
fakeService.DisconnectCalled.ShouldBeTrue();
|
||||
fakeService.DisposeCalled.ShouldBeTrue();
|
||||
}
|
||||
|
||||
[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);
|
||||
});
|
||||
|
||||
await Task.Delay(100);
|
||||
console.RequestCancellation();
|
||||
await task;
|
||||
|
||||
var output = TestConsoleHelper.GetOutput(console);
|
||||
output.ShouldContain("Subscribed to ns=2;s=TestVar (interval: 2000ms)");
|
||||
output.ShouldContain("Unsubscribed.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
using CliFx.Infrastructure;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.CLI.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Helper for creating CliFx <see cref="FakeInMemoryConsole"/> instances and reading their output.
|
||||
/// </summary>
|
||||
public static class TestConsoleHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="FakeInMemoryConsole"/> for testing.
|
||||
/// </summary>
|
||||
public static FakeInMemoryConsole CreateConsole()
|
||||
{
|
||||
return new FakeInMemoryConsole();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads all text written to the console's standard output.
|
||||
/// </summary>
|
||||
public static string GetOutput(FakeInMemoryConsole console)
|
||||
{
|
||||
console.Output.Flush();
|
||||
return console.ReadOutputString();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads all text written to the console's standard error.
|
||||
/// </summary>
|
||||
public static string GetError(FakeInMemoryConsole console)
|
||||
{
|
||||
console.Error.Flush();
|
||||
return console.ReadErrorString();
|
||||
}
|
||||
}
|
||||
103
tests/ZB.MOM.WW.LmxOpcUa.Client.CLI.Tests/WriteCommandTests.cs
Normal file
103
tests/ZB.MOM.WW.LmxOpcUa.Client.CLI.Tests/WriteCommandTests.cs
Normal file
@@ -0,0 +1,103 @@
|
||||
using Opc.Ua;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.CLI.Commands;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.CLI.Tests.Fakes;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.CLI.Tests;
|
||||
|
||||
public class WriteCommandTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task Execute_WritesSuccessfully()
|
||||
{
|
||||
var fakeService = new FakeOpcUaClientService
|
||||
{
|
||||
ReadValueResult = new DataValue(new Variant(42)),
|
||||
WriteStatusCodeResult = StatusCodes.Good
|
||||
};
|
||||
var factory = new FakeOpcUaClientServiceFactory(fakeService);
|
||||
var command = new WriteCommand(factory)
|
||||
{
|
||||
Url = "opc.tcp://localhost:4840",
|
||||
NodeId = "ns=2;s=MyVar",
|
||||
Value = "100"
|
||||
};
|
||||
|
||||
using var console = TestConsoleHelper.CreateConsole();
|
||||
await command.ExecuteAsync(console);
|
||||
|
||||
var output = TestConsoleHelper.GetOutput(console);
|
||||
output.ShouldContain("Write successful: ns=2;s=MyVar = 100");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Execute_ReportsFailure()
|
||||
{
|
||||
var fakeService = new FakeOpcUaClientService
|
||||
{
|
||||
ReadValueResult = new DataValue(new Variant("current")),
|
||||
WriteStatusCodeResult = StatusCodes.BadNotWritable
|
||||
};
|
||||
var factory = new FakeOpcUaClientServiceFactory(fakeService);
|
||||
var command = new WriteCommand(factory)
|
||||
{
|
||||
Url = "opc.tcp://localhost:4840",
|
||||
NodeId = "ns=2;s=ReadOnly",
|
||||
Value = "newvalue"
|
||||
};
|
||||
|
||||
using var console = TestConsoleHelper.CreateConsole();
|
||||
await command.ExecuteAsync(console);
|
||||
|
||||
var output = TestConsoleHelper.GetOutput(console);
|
||||
output.ShouldContain("Write failed:");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Execute_ReadsCurrentValueThenWrites()
|
||||
{
|
||||
var fakeService = new FakeOpcUaClientService
|
||||
{
|
||||
ReadValueResult = new DataValue(new Variant(3.14)),
|
||||
WriteStatusCodeResult = StatusCodes.Good
|
||||
};
|
||||
var factory = new FakeOpcUaClientServiceFactory(fakeService);
|
||||
var command = new WriteCommand(factory)
|
||||
{
|
||||
Url = "opc.tcp://localhost:4840",
|
||||
NodeId = "ns=2;s=FloatVar",
|
||||
Value = "2.718"
|
||||
};
|
||||
|
||||
using var console = TestConsoleHelper.CreateConsole();
|
||||
await command.ExecuteAsync(console);
|
||||
|
||||
// Should read first to get current type, then write
|
||||
fakeService.ReadNodeIds.Count.ShouldBe(1);
|
||||
fakeService.WriteValues.Count.ShouldBe(1);
|
||||
fakeService.WriteValues[0].Value.ShouldBeOfType<double>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Execute_DisconnectsInFinally()
|
||||
{
|
||||
var fakeService = new FakeOpcUaClientService
|
||||
{
|
||||
ReadValueResult = new DataValue(new Variant("test"))
|
||||
};
|
||||
var factory = new FakeOpcUaClientServiceFactory(fakeService);
|
||||
var command = new WriteCommand(factory)
|
||||
{
|
||||
Url = "opc.tcp://localhost:4840",
|
||||
NodeId = "ns=2;s=Node",
|
||||
Value = "value"
|
||||
};
|
||||
|
||||
using var console = TestConsoleHelper.CreateConsole();
|
||||
await command.ExecuteAsync(console);
|
||||
|
||||
fakeService.DisconnectCalled.ShouldBeTrue();
|
||||
fakeService.DisposeCalled.ShouldBeTrue();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<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.LmxOpcUa.Client.CLI.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="CliFx" Version="2.3.6" />
|
||||
<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.LmxOpcUa.Client.CLI\ZB.MOM.WW.LmxOpcUa.Client.CLI.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,38 @@
|
||||
using Opc.Ua;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Adapters;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
using Opc.Ua;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Adapters;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.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"
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
using Opc.Ua;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Adapters;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared.Tests.Fakes;
|
||||
|
||||
internal sealed class FakeSessionAdapter : ISessionAdapter
|
||||
{
|
||||
private Action<bool>? _keepAliveCallback;
|
||||
private readonly List<FakeSubscriptionAdapter> _createdSubscriptions = new();
|
||||
|
||||
public bool Connected { get; set; } = true;
|
||||
public string SessionId { get; set; } = "ns=0;i=12345";
|
||||
public string SessionName { get; set; } = "FakeSession";
|
||||
public string EndpointUrl { get; set; } = "opc.tcp://localhost:4840";
|
||||
public string ServerName { get; set; } = "FakeServer";
|
||||
public string SecurityMode { get; set; } = "None";
|
||||
public string SecurityPolicyUri { get; set; } = "http://opcfoundation.org/UA/SecurityPolicy#None";
|
||||
public NamespaceTable NamespaceUris { get; set; } = new();
|
||||
|
||||
public bool Closed { get; private set; }
|
||||
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; } = new();
|
||||
public byte[]? BrowseContinuationPoint { get; set; }
|
||||
public ReferenceDescriptionCollection BrowseNextResponse { get; set; } = new();
|
||||
public byte[]? BrowseNextContinuationPoint { get; set; }
|
||||
public bool HasChildrenResponse { get; set; } = false;
|
||||
|
||||
public List<DataValue> HistoryReadRawResponse { get; set; } = new();
|
||||
public List<DataValue> HistoryReadAggregateResponse { get; set; } = new();
|
||||
public bool ThrowOnHistoryReadRaw { get; set; }
|
||||
public bool ThrowOnHistoryReadAggregate { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The next FakeSubscriptionAdapter to return from CreateSubscriptionAsync.
|
||||
/// If null, a new one is created automatically.
|
||||
/// </summary>
|
||||
public FakeSubscriptionAdapter? NextSubscription { get; set; }
|
||||
|
||||
public IReadOnlyList<FakeSubscriptionAdapter> CreatedSubscriptions => _createdSubscriptions;
|
||||
|
||||
public void RegisterKeepAliveHandler(Action<bool> callback)
|
||||
{
|
||||
_keepAliveCallback = callback;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Simulates a keep-alive event.
|
||||
/// </summary>
|
||||
public void SimulateKeepAlive(bool isGood)
|
||||
{
|
||||
_keepAliveCallback?.Invoke(isGood);
|
||||
}
|
||||
|
||||
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));
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
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));
|
||||
}
|
||||
|
||||
public Task<(byte[]? ContinuationPoint, ReferenceDescriptionCollection References)> BrowseNextAsync(
|
||||
byte[] continuationPoint, CancellationToken ct)
|
||||
{
|
||||
BrowseNextCount++;
|
||||
return Task.FromResult((BrowseNextContinuationPoint, BrowseNextResponse));
|
||||
}
|
||||
|
||||
public Task<bool> HasChildrenAsync(NodeId nodeId, CancellationToken ct)
|
||||
{
|
||||
HasChildrenCount++;
|
||||
return Task.FromResult(HasChildrenResponse);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
public Task<ISubscriptionAdapter> CreateSubscriptionAsync(int publishingIntervalMs, CancellationToken ct)
|
||||
{
|
||||
var sub = NextSubscription ?? new FakeSubscriptionAdapter();
|
||||
NextSubscription = null;
|
||||
_createdSubscriptions.Add(sub);
|
||||
return Task.FromResult<ISubscriptionAdapter>(sub);
|
||||
}
|
||||
|
||||
public Task CloseAsync(CancellationToken ct)
|
||||
{
|
||||
Closed = true;
|
||||
Connected = false;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Disposed = true;
|
||||
Connected = false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
using Opc.Ua;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Adapters;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared.Tests.Fakes;
|
||||
|
||||
internal sealed class FakeSessionFactory : ISessionFactory
|
||||
{
|
||||
private readonly Queue<FakeSessionAdapter> _sessions = new();
|
||||
private readonly List<FakeSessionAdapter> _createdSessions = new();
|
||||
|
||||
public int CreateCallCount { get; private set; }
|
||||
public bool ThrowOnCreate { get; set; }
|
||||
public string? LastEndpointUrl { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Enqueues a session adapter to be returned on the next call to CreateSessionAsync.
|
||||
/// </summary>
|
||||
public void EnqueueSession(FakeSessionAdapter session)
|
||||
{
|
||||
_sessions.Enqueue(session);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
using Opc.Ua;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Adapters;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared.Tests.Fakes;
|
||||
|
||||
internal sealed class FakeSubscriptionAdapter : ISubscriptionAdapter
|
||||
{
|
||||
private uint _nextHandle = 100;
|
||||
private readonly Dictionary<uint, (NodeId NodeId, Action<string, DataValue>? DataCallback, Action<EventFieldList>? EventCallback)> _items = new();
|
||||
|
||||
public uint SubscriptionId { get; set; } = 42;
|
||||
public bool Deleted { get; private set; }
|
||||
public bool ConditionRefreshCalled { get; private set; }
|
||||
public bool ThrowOnConditionRefresh { get; set; }
|
||||
public int AddDataChangeCount { get; private set; }
|
||||
public int AddEventCount { get; private set; }
|
||||
public int RemoveCount { get; private set; }
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
public Task RemoveMonitoredItemAsync(uint clientHandle, CancellationToken ct)
|
||||
{
|
||||
RemoveCount++;
|
||||
_items.Remove(clientHandle);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
public Task ConditionRefreshAsync(CancellationToken ct)
|
||||
{
|
||||
ConditionRefreshCalled = true;
|
||||
if (ThrowOnConditionRefresh)
|
||||
throw new InvalidOperationException("Condition refresh not supported");
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task DeleteAsync(CancellationToken ct)
|
||||
{
|
||||
Deleted = true;
|
||||
_items.Clear();
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the handles of all active items.
|
||||
/// </summary>
|
||||
public IReadOnlyCollection<uint> ActiveHandles => _items.Keys.ToList();
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
using Opc.Ua;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Helpers;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.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)]
|
||||
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_InvalidValue_Throws()
|
||||
{
|
||||
Should.Throw<ArgumentOutOfRangeException>(() =>
|
||||
AggregateTypeMapper.ToNodeId((AggregateType)99));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Helpers;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.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(new[] { "opc.tcp://primary:4840" });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Parse_CsvEmpty_ReturnsPrimaryOnly()
|
||||
{
|
||||
var result = FailoverUrlParser.Parse("opc.tcp://primary:4840", "");
|
||||
result.ShouldBe(new[] { "opc.tcp://primary:4840" });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Parse_CsvWhitespace_ReturnsPrimaryOnly()
|
||||
{
|
||||
var result = FailoverUrlParser.Parse("opc.tcp://primary:4840", " ");
|
||||
result.ShouldBe(new[] { "opc.tcp://primary:4840" });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Parse_SingleFailover_ReturnsBoth()
|
||||
{
|
||||
var result = FailoverUrlParser.Parse("opc.tcp://primary:4840", "opc.tcp://backup:4840");
|
||||
result.ShouldBe(new[] { "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(new[] { "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(new[] { "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(new[] { "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(new[] { "opc.tcp://Primary:4840" });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Parse_ArrayNull_ReturnsPrimaryOnly()
|
||||
{
|
||||
var result = FailoverUrlParser.Parse("opc.tcp://primary:4840", (string[]?)null);
|
||||
result.ShouldBe(new[] { "opc.tcp://primary:4840" });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Parse_ArrayEmpty_ReturnsPrimaryOnly()
|
||||
{
|
||||
var result = FailoverUrlParser.Parse("opc.tcp://primary:4840", Array.Empty<string>());
|
||||
result.ShouldBe(new[] { "opc.tcp://primary:4840" });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Parse_ArrayWithUrls_ReturnsAll()
|
||||
{
|
||||
var result = FailoverUrlParser.Parse("opc.tcp://primary:4840",
|
||||
new[] { "opc.tcp://backup1:4840", "opc.tcp://backup2:4840" });
|
||||
result.ShouldBe(new[] { "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",
|
||||
new[] { "opc.tcp://primary:4840", "opc.tcp://backup:4840" });
|
||||
result.ShouldBe(new[] { "opc.tcp://primary:4840", "opc.tcp://backup:4840" });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Parse_ArrayTrimsWhitespace()
|
||||
{
|
||||
var result = FailoverUrlParser.Parse("opc.tcp://primary:4840",
|
||||
new[] { " opc.tcp://backup:4840 " });
|
||||
result.ShouldBe(new[] { "opc.tcp://primary:4840", "opc.tcp://backup:4840" });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Parse_ArraySkipsNullAndEmpty()
|
||||
{
|
||||
var result = FailoverUrlParser.Parse("opc.tcp://primary:4840",
|
||||
new[] { null!, "", "opc.tcp://backup:4840" });
|
||||
result.ShouldBe(new[] { "opc.tcp://primary:4840", "opc.tcp://backup:4840" });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
using Opc.Ua;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Helpers;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Helpers;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.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));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.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());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
using Opc.Ua;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared.Tests.Models;
|
||||
|
||||
public class ModelConstructionTests
|
||||
{
|
||||
[Fact]
|
||||
public void BrowseResult_ConstructsCorrectly()
|
||||
{
|
||||
var result = new ZB.MOM.WW.LmxOpcUa.Client.Shared.Models.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 ZB.MOM.WW.LmxOpcUa.Client.Shared.Models.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, Array.Empty<string>(), 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(6);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,816 @@
|
||||
using Opc.Ua;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Tests.Fakes;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared.Tests;
|
||||
|
||||
public class OpcUaClientServiceTests : IDisposable
|
||||
{
|
||||
private readonly FakeApplicationConfigurationFactory _configFactory = new();
|
||||
private readonly FakeEndpointDiscovery _endpointDiscovery = new();
|
||||
private readonly FakeSessionFactory _sessionFactory = new();
|
||||
private readonly OpcUaClientService _service;
|
||||
|
||||
public OpcUaClientServiceTests()
|
||||
{
|
||||
_service = new OpcUaClientService(_configFactory, _endpointDiscovery, _sessionFactory);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_service.Dispose();
|
||||
}
|
||||
|
||||
private ConnectionSettings ValidSettings(string url = "opc.tcp://localhost:4840") => new()
|
||||
{
|
||||
EndpointUrl = url,
|
||||
SessionTimeoutSeconds = 60
|
||||
};
|
||||
|
||||
// --- Connection tests ---
|
||||
|
||||
[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);
|
||||
}
|
||||
|
||||
[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();
|
||||
}
|
||||
|
||||
[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");
|
||||
}
|
||||
|
||||
[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);
|
||||
}
|
||||
|
||||
[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);
|
||||
}
|
||||
|
||||
[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 ---
|
||||
|
||||
[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();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DisconnectAsync_WhenNotConnected_IsIdempotent()
|
||||
{
|
||||
await _service.DisconnectAsync(); // Should not throw
|
||||
_service.IsConnected.ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DisconnectAsync_CalledTwice_IsIdempotent()
|
||||
{
|
||||
await _service.ConnectAsync(ValidSettings());
|
||||
await _service.DisconnectAsync();
|
||||
await _service.DisconnectAsync(); // Should not throw
|
||||
}
|
||||
|
||||
// --- Read tests ---
|
||||
|
||||
[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);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ReadValueAsync_WhenDisconnected_Throws()
|
||||
{
|
||||
await Should.ThrowAsync<InvalidOperationException>(() =>
|
||||
_service.ReadValueAsync(new NodeId("ns=2;s=MyNode")));
|
||||
}
|
||||
|
||||
[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 ---
|
||||
|
||||
[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);
|
||||
}
|
||||
|
||||
[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
|
||||
}
|
||||
|
||||
[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
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task WriteValueAsync_WhenDisconnected_Throws()
|
||||
{
|
||||
await Should.ThrowAsync<InvalidOperationException>(() =>
|
||||
_service.WriteValueAsync(new NodeId("ns=2;s=MyNode"), 42));
|
||||
}
|
||||
|
||||
// --- Browse tests ---
|
||||
|
||||
[Fact]
|
||||
public async Task BrowseAsync_WhenConnected_ReturnsMappedResults()
|
||||
{
|
||||
var session = new FakeSessionAdapter
|
||||
{
|
||||
BrowseResponse = new ReferenceDescriptionCollection
|
||||
{
|
||||
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
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task BrowseAsync_NullParent_UsesObjectsFolder()
|
||||
{
|
||||
var session = new FakeSessionAdapter
|
||||
{
|
||||
BrowseResponse = new ReferenceDescriptionCollection()
|
||||
};
|
||||
_sessionFactory.EnqueueSession(session);
|
||||
await _service.ConnectAsync(ValidSettings());
|
||||
|
||||
await _service.BrowseAsync(null);
|
||||
|
||||
session.BrowseCount.ShouldBe(1);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task BrowseAsync_ObjectNode_ChecksHasChildren()
|
||||
{
|
||||
var session = new FakeSessionAdapter
|
||||
{
|
||||
BrowseResponse = new ReferenceDescriptionCollection
|
||||
{
|
||||
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);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task BrowseAsync_WithContinuationPoint_FollowsIt()
|
||||
{
|
||||
var session = new FakeSessionAdapter
|
||||
{
|
||||
BrowseResponse = new ReferenceDescriptionCollection
|
||||
{
|
||||
new ReferenceDescription
|
||||
{
|
||||
NodeId = new ExpandedNodeId("ns=2;s=A"),
|
||||
DisplayName = new LocalizedText("A"),
|
||||
NodeClass = NodeClass.Variable
|
||||
}
|
||||
},
|
||||
BrowseContinuationPoint = new byte[] { 1, 2, 3 },
|
||||
BrowseNextResponse = new ReferenceDescriptionCollection
|
||||
{
|
||||
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);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task BrowseAsync_WhenDisconnected_Throws()
|
||||
{
|
||||
await Should.ThrowAsync<InvalidOperationException>(() => _service.BrowseAsync());
|
||||
}
|
||||
|
||||
// --- Subscribe tests ---
|
||||
|
||||
[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);
|
||||
}
|
||||
|
||||
[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);
|
||||
}
|
||||
|
||||
[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);
|
||||
}
|
||||
|
||||
[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);
|
||||
}
|
||||
|
||||
[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
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SubscribeAsync_WhenDisconnected_Throws()
|
||||
{
|
||||
await Should.ThrowAsync<InvalidOperationException>(() =>
|
||||
_service.SubscribeAsync(new NodeId("ns=2;s=MyNode")));
|
||||
}
|
||||
|
||||
// --- Alarm subscription tests ---
|
||||
|
||||
[Fact]
|
||||
public async Task SubscribeAlarmsAsync_CreatesEventSubscription()
|
||||
{
|
||||
var session = new FakeSessionAdapter();
|
||||
_sessionFactory.EnqueueSession(session);
|
||||
await _service.ConnectAsync(ValidSettings());
|
||||
|
||||
await _service.SubscribeAlarmsAsync(null, 1000);
|
||||
|
||||
session.CreatedSubscriptions.Count.ShouldBe(1);
|
||||
session.CreatedSubscriptions[0].AddEventCount.ShouldBe(1);
|
||||
}
|
||||
|
||||
[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);
|
||||
}
|
||||
|
||||
[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 VariantCollection
|
||||
{
|
||||
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) // 11: SuppressedOrShelved
|
||||
}
|
||||
};
|
||||
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();
|
||||
}
|
||||
|
||||
[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();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UnsubscribeAlarmsAsync_WhenNoSubscription_DoesNotThrow()
|
||||
{
|
||||
var session = new FakeSessionAdapter();
|
||||
_sessionFactory.EnqueueSession(session);
|
||||
await _service.ConnectAsync(ValidSettings());
|
||||
|
||||
await _service.UnsubscribeAlarmsAsync(); // Should not throw
|
||||
}
|
||||
|
||||
[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();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RequestConditionRefreshAsync_NoAlarmSubscription_Throws()
|
||||
{
|
||||
var session = new FakeSessionAdapter();
|
||||
_sessionFactory.EnqueueSession(session);
|
||||
await _service.ConnectAsync(ValidSettings());
|
||||
|
||||
await Should.ThrowAsync<InvalidOperationException>(() =>
|
||||
_service.RequestConditionRefreshAsync());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SubscribeAlarmsAsync_WhenDisconnected_Throws()
|
||||
{
|
||||
await Should.ThrowAsync<InvalidOperationException>(() =>
|
||||
_service.SubscribeAlarmsAsync());
|
||||
}
|
||||
|
||||
// --- History read tests ---
|
||||
|
||||
[Fact]
|
||||
public async Task HistoryReadRawAsync_ReturnsValues()
|
||||
{
|
||||
var expectedValues = new List<DataValue>
|
||||
{
|
||||
new DataValue(new Variant(1.0), StatusCodes.Good),
|
||||
new DataValue(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);
|
||||
}
|
||||
|
||||
[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));
|
||||
}
|
||||
|
||||
[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));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HistoryReadAggregateAsync_ReturnsValues()
|
||||
{
|
||||
var expectedValues = new List<DataValue>
|
||||
{
|
||||
new DataValue(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);
|
||||
}
|
||||
|
||||
[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));
|
||||
}
|
||||
|
||||
[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 ---
|
||||
|
||||
[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(new[] { "urn:server1", "urn:server2" }), StatusCodes.Good);
|
||||
if (nodeId == VariableIds.Server_ServerArray)
|
||||
return new DataValue(new Variant(new[] { "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(new[] { "urn:server1", "urn:server2" });
|
||||
info.ApplicationUri.ShouldBe("urn:server1");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRedundancyInfoAsync_MissingOptionalArrays_ReturnsGracefully()
|
||||
{
|
||||
int 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();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRedundancyInfoAsync_WhenDisconnected_Throws()
|
||||
{
|
||||
await Should.ThrowAsync<InvalidOperationException>(() =>
|
||||
_service.GetRedundancyInfoAsync());
|
||||
}
|
||||
|
||||
// --- Failover tests ---
|
||||
|
||||
[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 = new[] { "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");
|
||||
}
|
||||
|
||||
[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 = new[] { "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");
|
||||
}
|
||||
|
||||
[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 ---
|
||||
|
||||
[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();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Dispose_WhenNotConnected_DoesNotThrow()
|
||||
{
|
||||
_service.Dispose(); // Should not throw
|
||||
}
|
||||
|
||||
[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 ---
|
||||
|
||||
[Fact]
|
||||
public void OpcUaClientServiceFactory_CreatesService()
|
||||
{
|
||||
var factory = new OpcUaClientServiceFactory();
|
||||
var service = factory.Create();
|
||||
service.ShouldNotBeNull();
|
||||
service.ShouldBeAssignableTo<IOpcUaClientService>();
|
||||
service.Dispose();
|
||||
}
|
||||
}
|
||||
@@ -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.LmxOpcUa.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.LmxOpcUa.Client.Shared\ZB.MOM.WW.LmxOpcUa.Client.Shared.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
141
tests/ZB.MOM.WW.LmxOpcUa.Client.UI.Tests/AlarmsViewModelTests.cs
Normal file
141
tests/ZB.MOM.WW.LmxOpcUa.Client.UI.Tests/AlarmsViewModelTests.cs
Normal file
@@ -0,0 +1,141 @@
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.UI.Services;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.UI.Tests.Fakes;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.UI.ViewModels;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.UI.Tests;
|
||||
|
||||
public class AlarmsViewModelTests
|
||||
{
|
||||
private readonly FakeOpcUaClientService _service;
|
||||
private readonly AlarmsViewModel _vm;
|
||||
|
||||
public AlarmsViewModelTests()
|
||||
{
|
||||
_service = new FakeOpcUaClientService();
|
||||
var dispatcher = new SynchronousUiDispatcher();
|
||||
_vm = new AlarmsViewModel(_service, dispatcher);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SubscribeCommand_CannotExecute_WhenDisconnected()
|
||||
{
|
||||
_vm.IsConnected = false;
|
||||
_vm.SubscribeCommand.CanExecute(null).ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SubscribeCommand_CannotExecute_WhenAlreadySubscribed()
|
||||
{
|
||||
_vm.IsConnected = true;
|
||||
_vm.IsSubscribed = true;
|
||||
_vm.SubscribeCommand.CanExecute(null).ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SubscribeCommand_CanExecute_WhenConnectedAndNotSubscribed()
|
||||
{
|
||||
_vm.IsConnected = true;
|
||||
_vm.IsSubscribed = false;
|
||||
_vm.SubscribeCommand.CanExecute(null).ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SubscribeCommand_SetsIsSubscribed()
|
||||
{
|
||||
_vm.IsConnected = true;
|
||||
|
||||
await _vm.SubscribeCommand.ExecuteAsync(null);
|
||||
|
||||
_vm.IsSubscribed.ShouldBeTrue();
|
||||
_service.SubscribeAlarmsCallCount.ShouldBe(1);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UnsubscribeCommand_CannotExecute_WhenNotSubscribed()
|
||||
{
|
||||
_vm.IsConnected = true;
|
||||
_vm.IsSubscribed = false;
|
||||
_vm.UnsubscribeCommand.CanExecute(null).ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UnsubscribeCommand_ClearsIsSubscribed()
|
||||
{
|
||||
_vm.IsConnected = true;
|
||||
await _vm.SubscribeCommand.ExecuteAsync(null);
|
||||
|
||||
await _vm.UnsubscribeCommand.ExecuteAsync(null);
|
||||
|
||||
_vm.IsSubscribed.ShouldBeFalse();
|
||||
_service.UnsubscribeAlarmsCallCount.ShouldBe(1);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RefreshCommand_CallsService()
|
||||
{
|
||||
_vm.IsConnected = true;
|
||||
_vm.IsSubscribed = true;
|
||||
|
||||
await _vm.RefreshCommand.ExecuteAsync(null);
|
||||
|
||||
_service.RequestConditionRefreshCallCount.ShouldBe(1);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RefreshCommand_CannotExecute_WhenNotSubscribed()
|
||||
{
|
||||
_vm.IsConnected = true;
|
||||
_vm.IsSubscribed = false;
|
||||
_vm.RefreshCommand.CanExecute(null).ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AlarmEvent_AddsToCollection()
|
||||
{
|
||||
var alarm = new AlarmEventArgs(
|
||||
"Source1", "HighAlarm", 500, "Temperature high",
|
||||
true, true, false, DateTime.UtcNow);
|
||||
|
||||
_service.RaiseAlarmEvent(alarm);
|
||||
|
||||
_vm.AlarmEvents.Count.ShouldBe(1);
|
||||
_vm.AlarmEvents[0].SourceName.ShouldBe("Source1");
|
||||
_vm.AlarmEvents[0].ConditionName.ShouldBe("HighAlarm");
|
||||
_vm.AlarmEvents[0].Severity.ShouldBe((ushort)500);
|
||||
_vm.AlarmEvents[0].Message.ShouldBe("Temperature high");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Clear_ResetsState()
|
||||
{
|
||||
_vm.IsSubscribed = true;
|
||||
_vm.AlarmEvents.Add(new AlarmEventViewModel("Src", "Cond", 100, "Msg", true, true, false, DateTime.UtcNow));
|
||||
|
||||
_vm.Clear();
|
||||
|
||||
_vm.AlarmEvents.ShouldBeEmpty();
|
||||
_vm.IsSubscribed.ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Teardown_UnhooksEventHandler()
|
||||
{
|
||||
_vm.Teardown();
|
||||
|
||||
var alarm = new AlarmEventArgs(
|
||||
"Source1", "HighAlarm", 500, "Test",
|
||||
true, true, false, DateTime.UtcNow);
|
||||
_service.RaiseAlarmEvent(alarm);
|
||||
|
||||
_vm.AlarmEvents.ShouldBeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DefaultInterval_Is1000()
|
||||
{
|
||||
_vm.Interval.ShouldBe(1000);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.UI.Services;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.UI.Tests.Fakes;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.UI.ViewModels;
|
||||
using BrowseResult = ZB.MOM.WW.LmxOpcUa.Client.Shared.Models.BrowseResult;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.UI.Tests;
|
||||
|
||||
public class BrowseTreeViewModelTests
|
||||
{
|
||||
private readonly FakeOpcUaClientService _service;
|
||||
private readonly SynchronousUiDispatcher _dispatcher;
|
||||
private readonly BrowseTreeViewModel _vm;
|
||||
|
||||
public BrowseTreeViewModelTests()
|
||||
{
|
||||
_service = new FakeOpcUaClientService
|
||||
{
|
||||
BrowseResults = new[]
|
||||
{
|
||||
new BrowseResult("ns=2;s=Node1", "Node1", "Object", true),
|
||||
new BrowseResult("ns=2;s=Node2", "Node2", "Variable", false)
|
||||
}
|
||||
};
|
||||
_dispatcher = new SynchronousUiDispatcher();
|
||||
_vm = new BrowseTreeViewModel(_service, _dispatcher);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task LoadRootsAsync_PopulatesRootNodes()
|
||||
{
|
||||
await _vm.LoadRootsAsync();
|
||||
|
||||
_vm.RootNodes.Count.ShouldBe(2);
|
||||
_vm.RootNodes[0].DisplayName.ShouldBe("Node1");
|
||||
_vm.RootNodes[1].DisplayName.ShouldBe("Node2");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task LoadRootsAsync_BrowsesWithNullParent()
|
||||
{
|
||||
await _vm.LoadRootsAsync();
|
||||
|
||||
_service.BrowseCallCount.ShouldBe(1);
|
||||
_service.LastBrowseParentNodeId.ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Clear_RemovesAllRootNodes()
|
||||
{
|
||||
_vm.RootNodes.Add(new TreeNodeViewModel("ns=2;s=X", "X", "Object", false, _service, _dispatcher));
|
||||
_vm.Clear();
|
||||
|
||||
_vm.RootNodes.ShouldBeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task LoadRootsAsync_NodeWithChildren_HasPlaceholder()
|
||||
{
|
||||
await _vm.LoadRootsAsync();
|
||||
|
||||
var nodeWithChildren = _vm.RootNodes[0];
|
||||
nodeWithChildren.HasChildren.ShouldBeTrue();
|
||||
nodeWithChildren.Children.Count.ShouldBe(1);
|
||||
nodeWithChildren.Children[0].IsPlaceholder.ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task LoadRootsAsync_NodeWithoutChildren_HasNoPlaceholder()
|
||||
{
|
||||
await _vm.LoadRootsAsync();
|
||||
|
||||
var leafNode = _vm.RootNodes[1];
|
||||
leafNode.HasChildren.ShouldBeFalse();
|
||||
leafNode.Children.ShouldBeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TreeNode_FirstExpand_TriggersChildBrowse()
|
||||
{
|
||||
_service.BrowseResults = new[]
|
||||
{
|
||||
new BrowseResult("ns=2;s=Parent", "Parent", "Object", true)
|
||||
};
|
||||
|
||||
await _vm.LoadRootsAsync();
|
||||
|
||||
// Reset browse results for child browse
|
||||
_service.BrowseResults = new[]
|
||||
{
|
||||
new BrowseResult("ns=2;s=Child1", "Child1", "Variable", false)
|
||||
};
|
||||
|
||||
var parent = _vm.RootNodes[0];
|
||||
var initialBrowseCount = _service.BrowseCallCount;
|
||||
|
||||
parent.IsExpanded = true;
|
||||
|
||||
// Allow async operation to complete
|
||||
await Task.Delay(50);
|
||||
|
||||
_service.BrowseCallCount.ShouldBe(initialBrowseCount + 1);
|
||||
parent.Children.Count.ShouldBe(1);
|
||||
parent.Children[0].DisplayName.ShouldBe("Child1");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TreeNode_SecondExpand_DoesNotBrowseAgain()
|
||||
{
|
||||
_service.BrowseResults = new[]
|
||||
{
|
||||
new BrowseResult("ns=2;s=Parent", "Parent", "Object", true)
|
||||
};
|
||||
|
||||
await _vm.LoadRootsAsync();
|
||||
|
||||
_service.BrowseResults = new[]
|
||||
{
|
||||
new BrowseResult("ns=2;s=Child1", "Child1", "Variable", false)
|
||||
};
|
||||
|
||||
var parent = _vm.RootNodes[0];
|
||||
parent.IsExpanded = true;
|
||||
await Task.Delay(50);
|
||||
|
||||
var browseCountAfterFirst = _service.BrowseCallCount;
|
||||
|
||||
parent.IsExpanded = false;
|
||||
parent.IsExpanded = true;
|
||||
await Task.Delay(50);
|
||||
|
||||
_service.BrowseCallCount.ShouldBe(browseCountAfterFirst);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TreeNode_IsLoading_TransitionsDuringBrowse()
|
||||
{
|
||||
_service.BrowseResults = new[]
|
||||
{
|
||||
new BrowseResult("ns=2;s=Parent", "Parent", "Object", true)
|
||||
};
|
||||
|
||||
await _vm.LoadRootsAsync();
|
||||
|
||||
_service.BrowseResults = Array.Empty<BrowseResult>();
|
||||
|
||||
var parent = _vm.RootNodes[0];
|
||||
parent.IsExpanded = true;
|
||||
await Task.Delay(50);
|
||||
|
||||
// After completion, IsLoading should be false
|
||||
parent.IsLoading.ShouldBeFalse();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
using Opc.Ua;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.Shared;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
|
||||
using BrowseResult = ZB.MOM.WW.LmxOpcUa.Client.Shared.Models.BrowseResult;
|
||||
using ConnectionState = ZB.MOM.WW.LmxOpcUa.Client.Shared.Models.ConnectionState;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.UI.Tests.Fakes;
|
||||
|
||||
/// <summary>
|
||||
/// Fake IOpcUaClientService for unit testing.
|
||||
/// </summary>
|
||||
public sealed class FakeOpcUaClientService : IOpcUaClientService
|
||||
{
|
||||
// Configurable responses
|
||||
public ConnectionInfo? ConnectResult { get; set; }
|
||||
public Exception? ConnectException { get; set; }
|
||||
public IReadOnlyList<BrowseResult> BrowseResults { get; set; } = Array.Empty<BrowseResult>();
|
||||
public Exception? BrowseException { get; set; }
|
||||
public DataValue ReadResult { get; set; } = new DataValue(new Variant(42), StatusCodes.Good, DateTime.UtcNow, DateTime.UtcNow);
|
||||
public Exception? ReadException { get; set; }
|
||||
public StatusCode WriteResult { get; set; } = StatusCodes.Good;
|
||||
public Exception? WriteException { get; set; }
|
||||
public RedundancyInfo? RedundancyResult { get; set; }
|
||||
public Exception? RedundancyException { get; set; }
|
||||
public IReadOnlyList<DataValue> HistoryRawResult { get; set; } = Array.Empty<DataValue>();
|
||||
public IReadOnlyList<DataValue> HistoryAggregateResult { get; set; } = Array.Empty<DataValue>();
|
||||
public Exception? HistoryException { get; set; }
|
||||
|
||||
// Call tracking
|
||||
public int ConnectCallCount { get; private set; }
|
||||
public int DisconnectCallCount { get; private set; }
|
||||
public int ReadCallCount { get; private set; }
|
||||
public int WriteCallCount { get; private set; }
|
||||
public int BrowseCallCount { get; private set; }
|
||||
public int SubscribeCallCount { get; private set; }
|
||||
public int UnsubscribeCallCount { get; private set; }
|
||||
public int SubscribeAlarmsCallCount { get; private set; }
|
||||
public int UnsubscribeAlarmsCallCount { get; private set; }
|
||||
public int RequestConditionRefreshCallCount { get; private set; }
|
||||
public int HistoryReadRawCallCount { get; private set; }
|
||||
public int HistoryReadAggregateCallCount { get; private set; }
|
||||
public int GetRedundancyInfoCallCount { get; private set; }
|
||||
|
||||
public NodeId? LastReadNodeId { get; private set; }
|
||||
public NodeId? LastWriteNodeId { get; private set; }
|
||||
public object? LastWriteValue { get; private set; }
|
||||
public NodeId? LastBrowseParentNodeId { get; private set; }
|
||||
public NodeId? LastSubscribeNodeId { get; private set; }
|
||||
public int LastSubscribeIntervalMs { get; private set; }
|
||||
public NodeId? LastUnsubscribeNodeId { get; private set; }
|
||||
public AggregateType? LastAggregateType { get; private set; }
|
||||
|
||||
public bool IsConnected { get; set; }
|
||||
public ConnectionInfo? CurrentConnectionInfo { get; set; }
|
||||
|
||||
public event EventHandler<DataChangedEventArgs>? DataChanged;
|
||||
public event EventHandler<AlarmEventArgs>? AlarmEvent;
|
||||
public event EventHandler<ConnectionStateChangedEventArgs>? ConnectionStateChanged;
|
||||
|
||||
public Task<ConnectionInfo> ConnectAsync(ConnectionSettings settings, CancellationToken ct = default)
|
||||
{
|
||||
ConnectCallCount++;
|
||||
if (ConnectException != null) throw ConnectException;
|
||||
IsConnected = true;
|
||||
CurrentConnectionInfo = ConnectResult;
|
||||
return Task.FromResult(ConnectResult!);
|
||||
}
|
||||
|
||||
public Task DisconnectAsync(CancellationToken ct = default)
|
||||
{
|
||||
DisconnectCallCount++;
|
||||
IsConnected = false;
|
||||
CurrentConnectionInfo = null;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task<DataValue> ReadValueAsync(NodeId nodeId, CancellationToken ct = default)
|
||||
{
|
||||
ReadCallCount++;
|
||||
LastReadNodeId = nodeId;
|
||||
if (ReadException != null) throw ReadException;
|
||||
return Task.FromResult(ReadResult);
|
||||
}
|
||||
|
||||
public Task<StatusCode> WriteValueAsync(NodeId nodeId, object value, CancellationToken ct = default)
|
||||
{
|
||||
WriteCallCount++;
|
||||
LastWriteNodeId = nodeId;
|
||||
LastWriteValue = value;
|
||||
if (WriteException != null) throw WriteException;
|
||||
return Task.FromResult(WriteResult);
|
||||
}
|
||||
|
||||
public Task<IReadOnlyList<BrowseResult>> BrowseAsync(NodeId? parentNodeId = null, CancellationToken ct = default)
|
||||
{
|
||||
BrowseCallCount++;
|
||||
LastBrowseParentNodeId = parentNodeId;
|
||||
if (BrowseException != null) throw BrowseException;
|
||||
return Task.FromResult(BrowseResults);
|
||||
}
|
||||
|
||||
public Task SubscribeAsync(NodeId nodeId, int intervalMs = 1000, CancellationToken ct = default)
|
||||
{
|
||||
SubscribeCallCount++;
|
||||
LastSubscribeNodeId = nodeId;
|
||||
LastSubscribeIntervalMs = intervalMs;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task UnsubscribeAsync(NodeId nodeId, CancellationToken ct = default)
|
||||
{
|
||||
UnsubscribeCallCount++;
|
||||
LastUnsubscribeNodeId = nodeId;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task SubscribeAlarmsAsync(NodeId? sourceNodeId = null, int intervalMs = 1000, CancellationToken ct = default)
|
||||
{
|
||||
SubscribeAlarmsCallCount++;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task UnsubscribeAlarmsAsync(CancellationToken ct = default)
|
||||
{
|
||||
UnsubscribeAlarmsCallCount++;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task RequestConditionRefreshAsync(CancellationToken ct = default)
|
||||
{
|
||||
RequestConditionRefreshCallCount++;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task<IReadOnlyList<DataValue>> HistoryReadRawAsync(NodeId nodeId, DateTime startTime, DateTime endTime, int maxValues = 1000, CancellationToken ct = default)
|
||||
{
|
||||
HistoryReadRawCallCount++;
|
||||
if (HistoryException != null) throw HistoryException;
|
||||
return Task.FromResult(HistoryRawResult);
|
||||
}
|
||||
|
||||
public Task<IReadOnlyList<DataValue>> HistoryReadAggregateAsync(NodeId nodeId, DateTime startTime, DateTime endTime, AggregateType aggregate, double intervalMs = 3600000, CancellationToken ct = default)
|
||||
{
|
||||
HistoryReadAggregateCallCount++;
|
||||
LastAggregateType = aggregate;
|
||||
if (HistoryException != null) throw HistoryException;
|
||||
return Task.FromResult(HistoryAggregateResult);
|
||||
}
|
||||
|
||||
public Task<RedundancyInfo> GetRedundancyInfoAsync(CancellationToken ct = default)
|
||||
{
|
||||
GetRedundancyInfoCallCount++;
|
||||
if (RedundancyException != null) throw RedundancyException;
|
||||
return Task.FromResult(RedundancyResult!);
|
||||
}
|
||||
|
||||
// Methods to raise events from tests
|
||||
public void RaiseDataChanged(DataChangedEventArgs args) => DataChanged?.Invoke(this, args);
|
||||
public void RaiseAlarmEvent(AlarmEventArgs args) => AlarmEvent?.Invoke(this, args);
|
||||
public void RaiseConnectionStateChanged(ConnectionStateChangedEventArgs args) => ConnectionStateChanged?.Invoke(this, args);
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
// No-op for testing
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.Shared;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.UI.Tests.Fakes;
|
||||
|
||||
/// <summary>
|
||||
/// Fake factory that returns a preconfigured FakeOpcUaClientService.
|
||||
/// </summary>
|
||||
public sealed class FakeOpcUaClientServiceFactory : IOpcUaClientServiceFactory
|
||||
{
|
||||
private readonly FakeOpcUaClientService _service;
|
||||
|
||||
public FakeOpcUaClientServiceFactory(FakeOpcUaClientService service)
|
||||
{
|
||||
_service = service;
|
||||
}
|
||||
|
||||
public IOpcUaClientService Create() => _service;
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
using Opc.Ua;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.UI.Services;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.UI.Tests.Fakes;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.UI.ViewModels;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.UI.Tests;
|
||||
|
||||
public class HistoryViewModelTests
|
||||
{
|
||||
private readonly FakeOpcUaClientService _service;
|
||||
private readonly HistoryViewModel _vm;
|
||||
|
||||
public HistoryViewModelTests()
|
||||
{
|
||||
_service = new FakeOpcUaClientService
|
||||
{
|
||||
HistoryRawResult = new[]
|
||||
{
|
||||
new DataValue(new Variant(10), StatusCodes.Good, DateTime.UtcNow, DateTime.UtcNow),
|
||||
new DataValue(new Variant(20), StatusCodes.Good, DateTime.UtcNow, DateTime.UtcNow)
|
||||
},
|
||||
HistoryAggregateResult = new[]
|
||||
{
|
||||
new DataValue(new Variant(15.0), StatusCodes.Good, DateTime.UtcNow, DateTime.UtcNow)
|
||||
}
|
||||
};
|
||||
var dispatcher = new SynchronousUiDispatcher();
|
||||
_vm = new HistoryViewModel(_service, dispatcher);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ReadHistoryCommand_CannotExecute_WhenDisconnected()
|
||||
{
|
||||
_vm.IsConnected = false;
|
||||
_vm.SelectedNodeId = "ns=2;s=SomeNode";
|
||||
_vm.ReadHistoryCommand.CanExecute(null).ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ReadHistoryCommand_CannotExecute_WhenNoNodeSelected()
|
||||
{
|
||||
_vm.IsConnected = true;
|
||||
_vm.SelectedNodeId = null;
|
||||
_vm.ReadHistoryCommand.CanExecute(null).ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ReadHistoryCommand_CanExecute_WhenConnectedAndNodeSelected()
|
||||
{
|
||||
_vm.IsConnected = true;
|
||||
_vm.SelectedNodeId = "ns=2;s=SomeNode";
|
||||
_vm.ReadHistoryCommand.CanExecute(null).ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ReadHistoryCommand_Raw_PopulatesResults()
|
||||
{
|
||||
_vm.IsConnected = true;
|
||||
_vm.SelectedNodeId = "ns=2;s=SomeNode";
|
||||
_vm.SelectedAggregateType = null; // Raw
|
||||
|
||||
await _vm.ReadHistoryCommand.ExecuteAsync(null);
|
||||
|
||||
_vm.Results.Count.ShouldBe(2);
|
||||
_vm.Results[0].Value.ShouldBe("10");
|
||||
_vm.Results[1].Value.ShouldBe("20");
|
||||
_service.HistoryReadRawCallCount.ShouldBe(1);
|
||||
_service.HistoryReadAggregateCallCount.ShouldBe(0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ReadHistoryCommand_Aggregate_PopulatesResults()
|
||||
{
|
||||
_vm.IsConnected = true;
|
||||
_vm.SelectedNodeId = "ns=2;s=SomeNode";
|
||||
_vm.SelectedAggregateType = AggregateType.Average;
|
||||
|
||||
await _vm.ReadHistoryCommand.ExecuteAsync(null);
|
||||
|
||||
_vm.Results.Count.ShouldBe(1);
|
||||
_vm.Results[0].Value.ShouldBe("15");
|
||||
_service.HistoryReadAggregateCallCount.ShouldBe(1);
|
||||
_service.LastAggregateType.ShouldBe(AggregateType.Average);
|
||||
_service.HistoryReadRawCallCount.ShouldBe(0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ReadHistoryCommand_ClearsResultsBefore()
|
||||
{
|
||||
_vm.Results.Add(new HistoryValueViewModel("old", "Good", "t1", "t2"));
|
||||
_vm.IsConnected = true;
|
||||
_vm.SelectedNodeId = "ns=2;s=SomeNode";
|
||||
|
||||
await _vm.ReadHistoryCommand.ExecuteAsync(null);
|
||||
|
||||
_vm.Results.ShouldNotContain(r => r.Value == "old");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ReadHistoryCommand_IsLoading_FalseAfterComplete()
|
||||
{
|
||||
_vm.IsConnected = true;
|
||||
_vm.SelectedNodeId = "ns=2;s=SomeNode";
|
||||
|
||||
await _vm.ReadHistoryCommand.ExecuteAsync(null);
|
||||
|
||||
_vm.IsLoading.ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DefaultValues_AreCorrect()
|
||||
{
|
||||
_vm.MaxValues.ShouldBe(1000);
|
||||
_vm.IntervalMs.ShouldBe(3600000);
|
||||
_vm.SelectedAggregateType.ShouldBeNull();
|
||||
_vm.IsAggregateRead.ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsAggregateRead_TrueWhenAggregateSelected()
|
||||
{
|
||||
_vm.SelectedAggregateType = AggregateType.Maximum;
|
||||
_vm.IsAggregateRead.ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AggregateTypes_ContainsNullForRaw()
|
||||
{
|
||||
_vm.AggregateTypes.ShouldContain((AggregateType?)null);
|
||||
_vm.AggregateTypes.Count.ShouldBe(7); // null + 6 enum values
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Clear_ResetsState()
|
||||
{
|
||||
_vm.SelectedNodeId = "ns=2;s=SomeNode";
|
||||
_vm.Results.Add(new HistoryValueViewModel("v", "s", "t1", "t2"));
|
||||
|
||||
_vm.Clear();
|
||||
|
||||
_vm.Results.ShouldBeEmpty();
|
||||
_vm.SelectedNodeId.ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ReadHistoryCommand_Error_ShowsErrorInResults()
|
||||
{
|
||||
_service.HistoryException = new Exception("History not supported");
|
||||
_vm.IsConnected = true;
|
||||
_vm.SelectedNodeId = "ns=2;s=SomeNode";
|
||||
|
||||
await _vm.ReadHistoryCommand.ExecuteAsync(null);
|
||||
|
||||
_vm.Results.Count.ShouldBe(1);
|
||||
_vm.Results[0].Value.ShouldContain("History not supported");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.UI.Services;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.UI.Tests.Fakes;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.UI.ViewModels;
|
||||
using BrowseResult = ZB.MOM.WW.LmxOpcUa.Client.Shared.Models.BrowseResult;
|
||||
using ConnectionState = ZB.MOM.WW.LmxOpcUa.Client.Shared.Models.ConnectionState;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.UI.Tests;
|
||||
|
||||
public class MainWindowViewModelTests
|
||||
{
|
||||
private readonly FakeOpcUaClientService _service;
|
||||
private readonly MainWindowViewModel _vm;
|
||||
|
||||
public MainWindowViewModelTests()
|
||||
{
|
||||
_service = new FakeOpcUaClientService
|
||||
{
|
||||
ConnectResult = new ConnectionInfo(
|
||||
"opc.tcp://localhost:4840",
|
||||
"TestServer",
|
||||
"None",
|
||||
"http://opcfoundation.org/UA/SecurityPolicy#None",
|
||||
"session-1",
|
||||
"TestSession"),
|
||||
BrowseResults = new[]
|
||||
{
|
||||
new BrowseResult("ns=2;s=Root", "Root", "Object", true)
|
||||
},
|
||||
RedundancyResult = new RedundancyInfo("None", 200, new[] { "urn:test" }, "urn:test")
|
||||
};
|
||||
|
||||
var factory = new FakeOpcUaClientServiceFactory(_service);
|
||||
var dispatcher = new SynchronousUiDispatcher();
|
||||
_vm = new MainWindowViewModel(factory, dispatcher);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DefaultState_IsDisconnected()
|
||||
{
|
||||
_vm.ConnectionState.ShouldBe(ConnectionState.Disconnected);
|
||||
_vm.IsConnected.ShouldBeFalse();
|
||||
_vm.EndpointUrl.ShouldBe("opc.tcp://localhost:4840");
|
||||
_vm.StatusMessage.ShouldBe("Disconnected");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ConnectCommand_CanExecute_WhenDisconnected()
|
||||
{
|
||||
_vm.ConnectCommand.CanExecute(null).ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DisconnectCommand_CannotExecute_WhenDisconnected()
|
||||
{
|
||||
_vm.DisconnectCommand.CanExecute(null).ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ConnectCommand_TransitionsToConnected()
|
||||
{
|
||||
await _vm.ConnectCommand.ExecuteAsync(null);
|
||||
|
||||
_vm.ConnectionState.ShouldBe(ConnectionState.Connected);
|
||||
_vm.IsConnected.ShouldBeTrue();
|
||||
_service.ConnectCallCount.ShouldBe(1);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ConnectCommand_LoadsRootNodes()
|
||||
{
|
||||
await _vm.ConnectCommand.ExecuteAsync(null);
|
||||
|
||||
_vm.BrowseTree.RootNodes.Count.ShouldBe(1);
|
||||
_vm.BrowseTree.RootNodes[0].DisplayName.ShouldBe("Root");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ConnectCommand_FetchesRedundancyInfo()
|
||||
{
|
||||
await _vm.ConnectCommand.ExecuteAsync(null);
|
||||
|
||||
_vm.RedundancyInfo.ShouldNotBeNull();
|
||||
_vm.RedundancyInfo!.Mode.ShouldBe("None");
|
||||
_vm.RedundancyInfo.ServiceLevel.ShouldBe((byte)200);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ConnectCommand_SetsSessionLabel()
|
||||
{
|
||||
await _vm.ConnectCommand.ExecuteAsync(null);
|
||||
|
||||
_vm.SessionLabel.ShouldContain("TestServer");
|
||||
_vm.SessionLabel.ShouldContain("TestSession");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DisconnectCommand_TransitionsToDisconnected()
|
||||
{
|
||||
await _vm.ConnectCommand.ExecuteAsync(null);
|
||||
await _vm.DisconnectCommand.ExecuteAsync(null);
|
||||
|
||||
_vm.ConnectionState.ShouldBe(ConnectionState.Disconnected);
|
||||
_vm.IsConnected.ShouldBeFalse();
|
||||
_service.DisconnectCallCount.ShouldBe(1);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Disconnect_ClearsStateAndChildren()
|
||||
{
|
||||
await _vm.ConnectCommand.ExecuteAsync(null);
|
||||
await _vm.DisconnectCommand.ExecuteAsync(null);
|
||||
|
||||
_vm.SessionLabel.ShouldBe(string.Empty);
|
||||
_vm.RedundancyInfo.ShouldBeNull();
|
||||
_vm.BrowseTree.RootNodes.ShouldBeEmpty();
|
||||
_vm.SubscriptionCount.ShouldBe(0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ConnectionStateChangedEvent_UpdatesState()
|
||||
{
|
||||
_service.RaiseConnectionStateChanged(
|
||||
new ConnectionStateChangedEventArgs(ConnectionState.Disconnected, ConnectionState.Reconnecting, "opc.tcp://localhost:4840"));
|
||||
|
||||
_vm.ConnectionState.ShouldBe(ConnectionState.Reconnecting);
|
||||
_vm.StatusMessage.ShouldBe("Reconnecting...");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SelectedTreeNode_PropagatesToChildViewModels()
|
||||
{
|
||||
await _vm.ConnectCommand.ExecuteAsync(null);
|
||||
|
||||
var node = _vm.BrowseTree.RootNodes[0];
|
||||
_vm.SelectedTreeNode = node;
|
||||
|
||||
_vm.ReadWrite.SelectedNodeId.ShouldBe(node.NodeId);
|
||||
_vm.History.SelectedNodeId.ShouldBe(node.NodeId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ConnectCommand_PropagatesIsConnectedToChildViewModels()
|
||||
{
|
||||
await _vm.ConnectCommand.ExecuteAsync(null);
|
||||
|
||||
_vm.ReadWrite.IsConnected.ShouldBeTrue();
|
||||
_vm.Subscriptions.IsConnected.ShouldBeTrue();
|
||||
_vm.Alarms.IsConnected.ShouldBeTrue();
|
||||
_vm.History.IsConnected.ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DisconnectCommand_PropagatesIsConnectedFalseToChildViewModels()
|
||||
{
|
||||
await _vm.ConnectCommand.ExecuteAsync(null);
|
||||
await _vm.DisconnectCommand.ExecuteAsync(null);
|
||||
|
||||
_vm.ReadWrite.IsConnected.ShouldBeFalse();
|
||||
_vm.Subscriptions.IsConnected.ShouldBeFalse();
|
||||
_vm.Alarms.IsConnected.ShouldBeFalse();
|
||||
_vm.History.IsConnected.ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ConnectFailure_RevertsToDisconnected()
|
||||
{
|
||||
_service.ConnectException = new Exception("Connection refused");
|
||||
|
||||
await _vm.ConnectCommand.ExecuteAsync(null);
|
||||
|
||||
_vm.ConnectionState.ShouldBe(ConnectionState.Disconnected);
|
||||
_vm.StatusMessage.ShouldContain("Connection refused");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PropertyChanged_FiredForConnectionState()
|
||||
{
|
||||
var changed = new List<string>();
|
||||
_vm.PropertyChanged += (_, e) => changed.Add(e.PropertyName!);
|
||||
|
||||
_service.RaiseConnectionStateChanged(
|
||||
new ConnectionStateChangedEventArgs(ConnectionState.Disconnected, ConnectionState.Connected, "opc.tcp://localhost:4840"));
|
||||
|
||||
changed.ShouldContain(nameof(MainWindowViewModel.ConnectionState));
|
||||
changed.ShouldContain(nameof(MainWindowViewModel.IsConnected));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
using Opc.Ua;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.UI.Services;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.UI.Tests.Fakes;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.UI.ViewModels;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.UI.Tests;
|
||||
|
||||
public class ReadWriteViewModelTests
|
||||
{
|
||||
private readonly FakeOpcUaClientService _service;
|
||||
private readonly ReadWriteViewModel _vm;
|
||||
|
||||
public ReadWriteViewModelTests()
|
||||
{
|
||||
_service = new FakeOpcUaClientService
|
||||
{
|
||||
ReadResult = new DataValue(new Variant("TestValue"), StatusCodes.Good, DateTime.UtcNow, DateTime.UtcNow)
|
||||
};
|
||||
var dispatcher = new SynchronousUiDispatcher();
|
||||
_vm = new ReadWriteViewModel(_service, dispatcher);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ReadCommand_CannotExecute_WhenDisconnected()
|
||||
{
|
||||
_vm.IsConnected = false;
|
||||
_vm.SelectedNodeId = "ns=2;s=SomeNode";
|
||||
_vm.ReadCommand.CanExecute(null).ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ReadCommand_CannotExecute_WhenNoNodeSelected()
|
||||
{
|
||||
_vm.IsConnected = true;
|
||||
_vm.SelectedNodeId = null;
|
||||
_vm.ReadCommand.CanExecute(null).ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ReadCommand_CanExecute_WhenConnectedAndNodeSelected()
|
||||
{
|
||||
_vm.IsConnected = true;
|
||||
_vm.SelectedNodeId = "ns=2;s=SomeNode";
|
||||
_vm.ReadCommand.CanExecute(null).ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ReadCommand_UpdatesValueAndStatus()
|
||||
{
|
||||
_vm.IsConnected = true;
|
||||
_vm.SelectedNodeId = "ns=2;s=SomeNode";
|
||||
// auto-read fires on selection change, so reset count
|
||||
var countBefore = _service.ReadCallCount;
|
||||
|
||||
await _vm.ReadCommand.ExecuteAsync(null);
|
||||
|
||||
_vm.CurrentValue.ShouldBe("TestValue");
|
||||
_vm.CurrentStatus.ShouldNotBeNull();
|
||||
_vm.SourceTimestamp.ShouldNotBeNull();
|
||||
_vm.ServerTimestamp.ShouldNotBeNull();
|
||||
(_service.ReadCallCount - countBefore).ShouldBe(1);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AutoRead_OnSelectionChange_WhenConnected()
|
||||
{
|
||||
_vm.IsConnected = true;
|
||||
_vm.SelectedNodeId = "ns=2;s=SomeNode";
|
||||
|
||||
// The auto-read fires asynchronously; give it a moment
|
||||
// In synchronous dispatcher it should fire immediately
|
||||
_service.ReadCallCount.ShouldBeGreaterThanOrEqualTo(1);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NullSelection_DoesNotCallService()
|
||||
{
|
||||
_vm.IsConnected = true;
|
||||
_vm.SelectedNodeId = null;
|
||||
|
||||
_service.ReadCallCount.ShouldBe(0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task WriteCommand_UpdatesWriteStatus()
|
||||
{
|
||||
_vm.IsConnected = true;
|
||||
_vm.SelectedNodeId = "ns=2;s=SomeNode";
|
||||
_vm.WriteValue = "NewValue";
|
||||
|
||||
// Reset read count from auto-read
|
||||
var readCountBefore = _service.ReadCallCount;
|
||||
|
||||
await _vm.WriteCommand.ExecuteAsync(null);
|
||||
|
||||
_vm.WriteStatus.ShouldNotBeNull();
|
||||
_service.WriteCallCount.ShouldBe(1);
|
||||
_service.LastWriteValue.ShouldBe("NewValue");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WriteCommand_CannotExecute_WhenDisconnected()
|
||||
{
|
||||
_vm.IsConnected = false;
|
||||
_vm.SelectedNodeId = "ns=2;s=SomeNode";
|
||||
_vm.WriteCommand.CanExecute(null).ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ReadCommand_Error_SetsErrorStatus()
|
||||
{
|
||||
_service.ReadException = new Exception("Read failed");
|
||||
_vm.IsConnected = true;
|
||||
|
||||
// We need to set SelectedNodeId and manually trigger read
|
||||
// because auto-read catches the exception too
|
||||
_vm.SelectedNodeId = "ns=2;s=SomeNode";
|
||||
|
||||
_vm.CurrentStatus.ShouldContain("Error");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Clear_ResetsAllProperties()
|
||||
{
|
||||
_vm.IsConnected = true;
|
||||
_vm.SelectedNodeId = "ns=2;s=SomeNode";
|
||||
_vm.WriteValue = "test";
|
||||
_vm.WriteStatus = "Good";
|
||||
|
||||
_vm.Clear();
|
||||
|
||||
_vm.SelectedNodeId.ShouldBeNull();
|
||||
_vm.CurrentValue.ShouldBeNull();
|
||||
_vm.CurrentStatus.ShouldBeNull();
|
||||
_vm.SourceTimestamp.ShouldBeNull();
|
||||
_vm.ServerTimestamp.ShouldBeNull();
|
||||
_vm.WriteValue.ShouldBeNull();
|
||||
_vm.WriteStatus.ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsNodeSelected_TracksSelectedNodeId()
|
||||
{
|
||||
_vm.IsNodeSelected.ShouldBeFalse();
|
||||
_vm.SelectedNodeId = "ns=2;s=SomeNode";
|
||||
_vm.IsNodeSelected.ShouldBeTrue();
|
||||
_vm.SelectedNodeId = null;
|
||||
_vm.IsNodeSelected.ShouldBeFalse();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
using Opc.Ua;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.UI.Services;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.UI.Tests.Fakes;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.UI.ViewModels;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.UI.Tests;
|
||||
|
||||
public class SubscriptionsViewModelTests
|
||||
{
|
||||
private readonly FakeOpcUaClientService _service;
|
||||
private readonly SubscriptionsViewModel _vm;
|
||||
|
||||
public SubscriptionsViewModelTests()
|
||||
{
|
||||
_service = new FakeOpcUaClientService();
|
||||
var dispatcher = new SynchronousUiDispatcher();
|
||||
_vm = new SubscriptionsViewModel(_service, dispatcher);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AddSubscriptionCommand_CannotExecute_WhenDisconnected()
|
||||
{
|
||||
_vm.IsConnected = false;
|
||||
_vm.NewNodeIdText = "ns=2;s=SomeNode";
|
||||
_vm.AddSubscriptionCommand.CanExecute(null).ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AddSubscriptionCommand_CannotExecute_WhenNoNodeId()
|
||||
{
|
||||
_vm.IsConnected = true;
|
||||
_vm.NewNodeIdText = null;
|
||||
_vm.AddSubscriptionCommand.CanExecute(null).ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddSubscriptionCommand_AddsItem()
|
||||
{
|
||||
_vm.IsConnected = true;
|
||||
_vm.NewNodeIdText = "ns=2;s=SomeNode";
|
||||
_vm.NewInterval = 500;
|
||||
|
||||
await _vm.AddSubscriptionCommand.ExecuteAsync(null);
|
||||
|
||||
_vm.ActiveSubscriptions.Count.ShouldBe(1);
|
||||
_vm.ActiveSubscriptions[0].NodeId.ShouldBe("ns=2;s=SomeNode");
|
||||
_vm.ActiveSubscriptions[0].IntervalMs.ShouldBe(500);
|
||||
_vm.SubscriptionCount.ShouldBe(1);
|
||||
_service.SubscribeCallCount.ShouldBe(1);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RemoveSubscriptionCommand_RemovesItem()
|
||||
{
|
||||
_vm.IsConnected = true;
|
||||
_vm.NewNodeIdText = "ns=2;s=SomeNode";
|
||||
await _vm.AddSubscriptionCommand.ExecuteAsync(null);
|
||||
|
||||
_vm.SelectedSubscription = _vm.ActiveSubscriptions[0];
|
||||
await _vm.RemoveSubscriptionCommand.ExecuteAsync(null);
|
||||
|
||||
_vm.ActiveSubscriptions.ShouldBeEmpty();
|
||||
_vm.SubscriptionCount.ShouldBe(0);
|
||||
_service.UnsubscribeCallCount.ShouldBe(1);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RemoveSubscriptionCommand_CannotExecute_WhenNoSelection()
|
||||
{
|
||||
_vm.IsConnected = true;
|
||||
_vm.SelectedSubscription = null;
|
||||
_vm.RemoveSubscriptionCommand.CanExecute(null).ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DataChanged_UpdatesMatchingRow()
|
||||
{
|
||||
_vm.IsConnected = true;
|
||||
_vm.NewNodeIdText = "ns=2;s=SomeNode";
|
||||
await _vm.AddSubscriptionCommand.ExecuteAsync(null);
|
||||
|
||||
var dataValue = new DataValue(new Variant(42), StatusCodes.Good, DateTime.UtcNow);
|
||||
_service.RaiseDataChanged(new DataChangedEventArgs("ns=2;s=SomeNode", dataValue));
|
||||
|
||||
_vm.ActiveSubscriptions[0].Value.ShouldBe("42");
|
||||
_vm.ActiveSubscriptions[0].Status.ShouldNotBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DataChanged_DoesNotUpdateNonMatchingRow()
|
||||
{
|
||||
_vm.IsConnected = true;
|
||||
_vm.NewNodeIdText = "ns=2;s=SomeNode";
|
||||
await _vm.AddSubscriptionCommand.ExecuteAsync(null);
|
||||
|
||||
var dataValue = new DataValue(new Variant(42), StatusCodes.Good, DateTime.UtcNow);
|
||||
_service.RaiseDataChanged(new DataChangedEventArgs("ns=2;s=OtherNode", dataValue));
|
||||
|
||||
_vm.ActiveSubscriptions[0].Value.ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Clear_RemovesAllSubscriptions()
|
||||
{
|
||||
_vm.ActiveSubscriptions.Add(new SubscriptionItemViewModel("ns=2;s=X", 1000));
|
||||
_vm.SubscriptionCount = 1;
|
||||
|
||||
_vm.Clear();
|
||||
|
||||
_vm.ActiveSubscriptions.ShouldBeEmpty();
|
||||
_vm.SubscriptionCount.ShouldBe(0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Teardown_UnhooksEventHandler()
|
||||
{
|
||||
_vm.Teardown();
|
||||
|
||||
// After teardown, raising event should not update anything
|
||||
_vm.ActiveSubscriptions.Add(new SubscriptionItemViewModel("ns=2;s=X", 1000));
|
||||
var dataValue = new DataValue(new Variant(42), StatusCodes.Good, DateTime.UtcNow);
|
||||
_service.RaiseDataChanged(new DataChangedEventArgs("ns=2;s=X", dataValue));
|
||||
|
||||
_vm.ActiveSubscriptions[0].Value.ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DefaultInterval_Is1000()
|
||||
{
|
||||
_vm.NewInterval.ShouldBe(1000);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<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.LmxOpcUa.Client.UI.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.LmxOpcUa.Client.UI\ZB.MOM.WW.LmxOpcUa.Client.UI.csproj" />
|
||||
<ProjectReference Include="..\..\src\ZB.MOM.WW.LmxOpcUa.Client.Shared\ZB.MOM.WW.LmxOpcUa.Client.Shared.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
Reference in New Issue
Block a user