eff2b8e573
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
248 lines
11 KiB
C#
248 lines
11 KiB
C#
using System.Net;
|
|
using System.Net.Sockets;
|
|
using Shouldly;
|
|
using Xunit;
|
|
|
|
namespace ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests;
|
|
|
|
/// <summary>
|
|
/// Unit tests for <see cref="OpcUaClientDriverProbe"/>. Uses an in-process
|
|
/// <see cref="TcpListener"/> on 127.0.0.1 to exercise the accept-then-close negative path
|
|
/// (non-OPC-UA TCP server). The happy path (real OPC UA endpoints) is covered live.
|
|
/// </summary>
|
|
[Trait("Category", "Unit")]
|
|
public sealed class OpcUaClientDriverProbeTests
|
|
{
|
|
private readonly OpcUaClientDriverProbe _probe = new();
|
|
|
|
// ── 1. Invalid JSON ──────────────────────────────────────────────────────────
|
|
|
|
/// <summary>
|
|
/// Invalid JSON returns Ok=false with a message containing "invalid".
|
|
/// </summary>
|
|
[Fact]
|
|
public async Task InvalidJson_returns_false_with_invalid_message()
|
|
{
|
|
var result = await _probe.ProbeAsync(
|
|
"not-json",
|
|
TimeSpan.FromSeconds(3),
|
|
TestContext.Current.CancellationToken);
|
|
|
|
result.Ok.ShouldBeFalse();
|
|
result.Message.ShouldNotBeNull();
|
|
result.Message!.ShouldContain("invalid", Case.Insensitive);
|
|
}
|
|
|
|
// ── 2. Config with no endpoint URL ───────────────────────────────────────────
|
|
|
|
/// <summary>
|
|
/// Config JSON that resolves to no endpoint URL returns Ok=false with a message
|
|
/// indicating no host/port was found.
|
|
/// </summary>
|
|
[Fact]
|
|
public async Task NoEndpointUrl_returns_false_with_no_host_port_message()
|
|
{
|
|
// Empty EndpointUrl + empty EndpointUrls → ExtractTarget returns ("", 0, "")
|
|
var result = await _probe.ProbeAsync(
|
|
"""{"EndpointUrl":"","EndpointUrls":[]}""",
|
|
TimeSpan.FromSeconds(3),
|
|
TestContext.Current.CancellationToken);
|
|
|
|
result.Ok.ShouldBeFalse();
|
|
result.Message.ShouldNotBeNull();
|
|
result.Message!.ShouldContain("no host", Case.Insensitive);
|
|
}
|
|
|
|
// ── 3. Unreachable closed port ────────────────────────────────────────────────
|
|
|
|
/// <summary>
|
|
/// Pointing at a TCP port that is not open returns Ok=false with a "Connect failed"
|
|
/// message from the socket layer.
|
|
/// </summary>
|
|
[Fact]
|
|
public async Task ClosedPort_returns_false_with_connect_failed_message()
|
|
{
|
|
// Find a free port by letting the OS assign one, then immediately close the listener
|
|
// so nothing is bound at that port when we probe it.
|
|
var listener = new TcpListener(IPAddress.Loopback, 0);
|
|
listener.Start();
|
|
var port = ((IPEndPoint)listener.LocalEndpoint).Port;
|
|
listener.Stop();
|
|
|
|
var configJson = $$"""{"EndpointUrl":"opc.tcp://127.0.0.1:{{port}}"}""";
|
|
|
|
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
|
|
var result = await _probe.ProbeAsync(configJson, TimeSpan.FromSeconds(5), cts.Token);
|
|
|
|
result.Ok.ShouldBeFalse();
|
|
result.Message.ShouldNotBeNull();
|
|
// SocketException on a closed port emits "Connect failed: ConnectionRefused" (or similar).
|
|
result.Message!.ShouldContain("Connect failed", Case.Insensitive);
|
|
}
|
|
|
|
// ── 4. TCP accept-then-close (non-OPC-UA server) ────────────────────────────
|
|
|
|
/// <summary>
|
|
/// A TCP server that accepts but immediately closes the connection (simulating a
|
|
/// non-OPC-UA process on the target port) causes the GetEndpoints handshake to fail.
|
|
/// The result must be Ok=false and the message must contain "handshake failed".
|
|
/// </summary>
|
|
[Fact]
|
|
public async Task NonOpcUaTcpServer_returns_false_with_handshake_failed_message()
|
|
{
|
|
// Start a listener that accepts the connection and immediately closes it, simulating
|
|
// a non-OPC UA TCP service (e.g. an HTTP server or an SSH daemon) on the target port.
|
|
var listener = new TcpListener(IPAddress.Loopback, 0);
|
|
listener.Start();
|
|
var port = ((IPEndPoint)listener.LocalEndpoint).Port;
|
|
|
|
var testCt = TestContext.Current.CancellationToken;
|
|
|
|
// Accept in background — immediately close the socket so the OPC UA client gets EOF.
|
|
var acceptTask = Task.Run(async () =>
|
|
{
|
|
try
|
|
{
|
|
using var client = await listener.AcceptTcpClientAsync(testCt);
|
|
// Close immediately — the OPC UA handshake will get an EOF / broken pipe.
|
|
}
|
|
catch
|
|
{
|
|
// Listener may be stopped before a second accept; ignore.
|
|
}
|
|
finally
|
|
{
|
|
listener.Stop();
|
|
}
|
|
}, testCt);
|
|
|
|
try
|
|
{
|
|
var configJson = $$"""{"EndpointUrl":"opc.tcp://127.0.0.1:{{port}}"}""";
|
|
|
|
// Use a generous timeout so the test is not fragile on a slow CI box, but short
|
|
// enough to not block the suite for long if something goes wrong.
|
|
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
|
|
var result = await _probe.ProbeAsync(configJson, TimeSpan.FromSeconds(10), cts.Token);
|
|
|
|
result.Ok.ShouldBeFalse();
|
|
result.Message.ShouldNotBeNull();
|
|
result.Message!.ShouldContain("handshake failed", Case.Insensitive);
|
|
}
|
|
finally
|
|
{
|
|
await acceptTask.WaitAsync(TimeSpan.FromSeconds(5), testCt);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// #676: a stored config still carrying the deleted <c>reconnectPeriod</c> key must reach the connect phase, not
|
|
/// fail as invalid JSON — the probe parses with the same skip-unknown-members options as the factory.
|
|
/// </summary>
|
|
[Fact]
|
|
public async Task A_config_still_carrying_reconnectPeriod_is_probed_not_rejected()
|
|
{
|
|
var listener = new TcpListener(IPAddress.Loopback, 0);
|
|
listener.Start();
|
|
var port = ((IPEndPoint)listener.LocalEndpoint).Port;
|
|
listener.Stop();
|
|
|
|
var result = await _probe.ProbeAsync(
|
|
$$"""{"EndpointUrl":"opc.tcp://127.0.0.1:{{port}}","reconnectPeriod":"00:00:05"}""",
|
|
TimeSpan.FromSeconds(5),
|
|
TestContext.Current.CancellationToken);
|
|
|
|
result.Ok.ShouldBeFalse();
|
|
var message = result.Message.ShouldNotBeNull();
|
|
message.ShouldNotContain("invalid", Case.Insensitive);
|
|
message.ShouldContain("Connect failed", Case.Insensitive);
|
|
}
|
|
|
|
// ── #992 G-15: the TCP preflight is dual-mode (IPv6 literal / AAAA-only hosts) ────────────────
|
|
|
|
/// <summary>
|
|
/// An IPv6 literal endpoint must pass the TCP preflight (it used to fail "Connect failed" on an IPv4-only
|
|
/// socket before any OPC UA traffic). A listener that accepts then closes proves the preflight connected: the
|
|
/// failure is then the discovery handshake, never "Connect failed".
|
|
/// </summary>
|
|
[Fact]
|
|
public async Task An_IPv6_literal_endpoint_passes_the_tcp_preflight()
|
|
{
|
|
if (!Socket.OSSupportsIPv6) Assert.Skip("IPv6 is not available on this host.");
|
|
var listener = new TcpListener(IPAddress.IPv6Loopback, 0);
|
|
listener.Start();
|
|
var port = ((IPEndPoint)listener.LocalEndpoint).Port;
|
|
var testCt = TestContext.Current.CancellationToken;
|
|
var accepted = Task.Run(async () =>
|
|
{
|
|
try { using var c = await listener.AcceptTcpClientAsync(testCt); return true; }
|
|
catch { return false; }
|
|
}, testCt);
|
|
try
|
|
{
|
|
var result = await _probe.ProbeAsync(
|
|
$$"""{"EndpointUrl":"opc.tcp://[::1]:{{port}}"}""", TimeSpan.FromSeconds(5), testCt);
|
|
|
|
result.Ok.ShouldBeFalse("the listener is not an OPC UA server");
|
|
result.Message.ShouldNotBeNull().ShouldNotContain("Connect failed", Case.Insensitive);
|
|
(await accepted.WaitAsync(TimeSpan.FromSeconds(5), testCt)).ShouldBeTrue("the preflight reached the IPv6 listener");
|
|
}
|
|
finally { listener.Stop(); }
|
|
}
|
|
|
|
// ── #1039: zone-qualified IPv6 hosts reach the preflight with their zone ───────────────────────
|
|
|
|
/// <summary>
|
|
/// The preflight dials the host <see cref="OpcUaClientDriverProbe.ExtractTarget"/> returns. .NET's
|
|
/// <see cref="Uri.Host"/> drops an IPv6 zone index (#819), so a link-local <c>fe80::1%eth0</c> endpoint was dialled
|
|
/// zone-less — unroutable, a false "Connect failed" before any OPC UA traffic. The host must carry the zone.
|
|
/// </summary>
|
|
[Theory]
|
|
[InlineData("opc.tcp://[fe80::1%eth0]:4841", "fe80::1%eth0", 4841)]
|
|
[InlineData("opc.tcp://[fe80::1%4]:4841/Ua", "fe80::1%4", 4841)]
|
|
// RFC 6874's encoded delimiter is accepted and normalised to the '%' the socket layer wants.
|
|
[InlineData("opc.tcp://[fe80::1%25eth0]:4841", "fe80::1%eth0", 4841)]
|
|
[InlineData("opc.tcp://[fe80::1%eth0]", "fe80::1%eth0", 4840)]
|
|
// Positive controls: a zone-less literal and a name are unchanged.
|
|
[InlineData("opc.tcp://[::1]:4841", "::1", 4841)]
|
|
[InlineData("opc.tcp://plc-host:4841", "plc-host", 4841)]
|
|
public void The_preflight_target_keeps_an_IPv6_zone_index(string endpointUrl, string expectedHost, int expectedPort)
|
|
{
|
|
var (host, port, url) = OpcUaClientDriverProbe.ExtractTarget(new OpcUaClientDriverOptions { EndpointUrl = endpointUrl });
|
|
|
|
host.ShouldBe(expectedHost);
|
|
port.ShouldBe(expectedPort);
|
|
url.ShouldBe(endpointUrl);
|
|
}
|
|
|
|
/// <summary>
|
|
/// End to end: a zone-qualified loopback literal reaches the preflight's socket connect (a listener that accepts
|
|
/// then closes proves it dialled), so the failure is the discovery handshake, never "Connect failed".
|
|
/// <c>::1%0</c> is a numeric zone that is valid everywhere an IPv6 socket is.
|
|
/// </summary>
|
|
[Fact]
|
|
public async Task A_zone_qualified_IPv6_literal_endpoint_passes_the_tcp_preflight()
|
|
{
|
|
if (!Socket.OSSupportsIPv6) Assert.Skip("IPv6 is not available on this host.");
|
|
var listener = new TcpListener(IPAddress.IPv6Loopback, 0);
|
|
listener.Start();
|
|
var port = ((IPEndPoint)listener.LocalEndpoint).Port;
|
|
var testCt = TestContext.Current.CancellationToken;
|
|
var accepted = Task.Run(async () =>
|
|
{
|
|
try { using var c = await listener.AcceptTcpClientAsync(testCt); return true; }
|
|
catch { return false; }
|
|
}, testCt);
|
|
try
|
|
{
|
|
var result = await _probe.ProbeAsync(
|
|
$$"""{"EndpointUrl":"opc.tcp://[::1%0]:{{port}}"}""", TimeSpan.FromSeconds(5), testCt);
|
|
|
|
result.Ok.ShouldBeFalse("the listener is not an OPC UA server");
|
|
result.Message.ShouldNotBeNull().ShouldNotContain("Connect failed", Case.Insensitive);
|
|
(await accepted.WaitAsync(TimeSpan.FromSeconds(5), testCt)).ShouldBeTrue("the preflight reached the listener");
|
|
}
|
|
finally { listener.Stop(); }
|
|
}
|
|
}
|