using Akka.Actor;
using Akka.TestKit.Xunit2;
using NSubstitute;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Protocol;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Services;
using ZB.MOM.WW.ScadaBridge.Commons.Messages.Management;
using ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Actors;
using ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Adapters;
using ZB.MOM.WW.ScadaBridge.HealthMonitoring;
namespace ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests.Actors;
///
/// DCL-6 (2026-12-02 review, WP3 task 3.4): browse/search while the connection has no session must
/// REPLY with a typed ConnectionNotConnected failure. An adapter that threw synchronously
/// (before returning a task) escaped the actor's faulted-task mapping, so the node-browser dialog
/// waited out its whole Ask timeout and the site logged a "threw exception, resuming" warning.
///
public class DataConnectionDisconnectedBrowseTests : TestKit
{
private readonly ISiteHealthCollector _health = Substitute.For();
private readonly IDataConnectionFactory _factory = Substitute.For();
private readonly DataConnectionOptions _options = new()
{
ReconnectInterval = TimeSpan.FromSeconds(30),
WriteTimeout = TimeSpan.FromSeconds(5),
};
/// An adapter that throws synchronously still yields a typed reply, in the Connecting state.
[Fact]
public void SynchronousThrowWhileConnecting_RepliesConnectionNotConnected()
{
var adapter = Substitute.For();
// Never connects: the actor stays in Connecting.
adapter.ConnectAsync(Arg.Any>(), Arg.Any())
.Returns(new TaskCompletionSource().Task);
((IBrowsableDataConnection)adapter)
.BrowseChildrenAsync(Arg.Any(), Arg.Any(), Arg.Any())
.Returns>(_ => throw new ConnectionNotConnectedException("not connected"));
((IAddressSpaceSearchable)adapter)
.SearchAddressSpaceAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any())
.Returns>(_ => throw new ConnectionNotConnectedException("not connected"));
var actor = Sys.ActorOf(Props.Create(() => new DataConnectionActor(
"conn", adapter, _options, _health, _factory, "OpcUa")));
actor.Tell(new SearchAddressSpaceCommand("conn", "Tag", 5, 100));
var search = ExpectMsg(TimeSpan.FromSeconds(5)); // pre-fix: no reply
Assert.Equal(BrowseFailureKind.ConnectionNotConnected, search.Failure?.Kind);
actor.Tell(new BrowseNodeCommand("conn", null));
var browse = ExpectMsg(TimeSpan.FromSeconds(5));
Assert.Equal(BrowseFailureKind.ConnectionNotConnected, browse.Failure?.Kind);
}
/// The OPC UA adapter with no client yet faults the task (typed) instead of throwing.
[Fact]
public async Task OpcUaAdapterWithoutClient_FaultsTheTask_WithTypedException()
{
var clientFactory = Substitute.For();
await using var adapter = new OpcUaDataConnection(clientFactory,
Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance);
// Calling the method must not throw synchronously (pre-fix: NullReferenceException /
// ConnectionNotConnectedException thrown before a task existed) — it returns a faulted task.
Task browse;
try { browse = adapter.BrowseChildrenAsync(null); }
catch (Exception ex) { throw new Xunit.Sdk.XunitException($"Browse threw synchronously: {ex.GetType().Name}"); }
await Assert.ThrowsAsync(() => browse);
Task search;
try { search = adapter.SearchAddressSpaceAsync("x", 3, 10); }
catch (Exception ex) { throw new Xunit.Sdk.XunitException($"Search threw synchronously: {ex.GetType().Name}"); }
await Assert.ThrowsAsync(() => search);
}
}