using System.Diagnostics;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Driver.Heidenhain.Lsv2;
using ZB.MOM.WW.OtOpcUa.Driver.Heidenhain.Tests.Simulator;
namespace ZB.MOM.WW.OtOpcUa.Driver.Heidenhain.Tests;
/// Framing/transport regression ported from the reference Lsv2TransportTest (literal frames, independent of the encoder).
[Trait("Category", "Unit")]
public sealed class Lsv2TransportTests
{
private static CancellationToken Ct => TestContext.Current.CancellationToken;
private static async Task OpenAsync(Lsv2Simulator sim, int timeoutMs = 1000)
{
var c = new Lsv2Client("127.0.0.1", sim.Port, TimeSpan.FromMilliseconds(timeoutMs));
await c.OpenAsync(Ct);
return c;
}
[Fact]
public async Task Literal_runtime_request_and_byte_fragmented_response()
{
byte[]? seen = null;
await using var sim = Lsv2Simulator.WithScript(async (c, ct) =>
{
var req = await c.ReadRequestAsync(ct);
seen = SimConnection.Frame(req!.Command, req.Payload);
await c.WriteRawAsync(Convert.FromHexString("00000002535f52490003"), byteByByte: true, ct);
});
await using var client = await OpenAsync(sim);
(await client.ReadRuntimeAsync(23, Ct)).ShouldBe(new byte[] { 0, 3 });
seen.ShouldBe(Convert.FromHexString("00000002525f52490017"));
}
[Fact]
public async Task Controller_refusal_preserves_code_and_stream_sync()
{
await using var sim = Lsv2Simulator.WithScript(async (c, ct) =>
{
await c.ReadRequestAsync(ct);
await c.ReplyAsync("T_ER", [1, 23], ct);
await c.ReadRequestAsync(ct);
await c.ReplyAsync("S_VR", [65, 0], ct);
});
await using var client = await OpenAsync(sim);
var refusal = await Should.ThrowAsync(() => client.ReadRuntimeAsync(23, Ct));
refusal.Code.ShouldBe(23);
client.IsClosed.ShouldBeFalse();
(await client.ReadVersionAsync(Ct)).ShouldBe(new byte[] { 65, 0 });
}
[Theory]
[InlineData("00010000535f5249")] // oversized length: rejected before allocation
[InlineData("00000000535f5652")] // unexpected response type (S_VR for an R_RI)
[InlineData("00000002535f524900")] // partial body then EOF
[InlineData("00000003545f455201")] // malformed refusal (3-byte T_ER)
[InlineData("00000001545f4f4b00")] // T_OK with a body
public async Task Bad_frames_close_the_client_and_later_requests_fail(string hex)
{
await using var sim = Lsv2Simulator.WithScript(async (c, ct) =>
{
await c.ReadRequestAsync(ct);
await c.WriteRawAsync(Convert.FromHexString(hex), byteByByte: false, ct);
if (hex.EndsWith("00", StringComparison.Ordinal) && hex.Length == 18) c.Close();
await Task.Delay(2000, ct);
});
await using var client = await OpenAsync(sim);
var req = hex.Contains("545f4f4b", StringComparison.Ordinal)
? client.LoginAsync("INSPECT", "", Ct)
: client.ReadRuntimeAsync(23, Ct);
await Should.ThrowAsync(() => req);
client.IsClosed.ShouldBeTrue();
await Should.ThrowAsync(() => client.ReadVersionAsync(Ct));
}
[Fact]
public async Task Close_interrupts_a_blocked_read_without_waiting_for_the_gate()
{
var requested = new TaskCompletionSource();
await using var sim = Lsv2Simulator.WithScript(async (c, ct) =>
{
await c.ReadRequestAsync(ct);
requested.TrySetResult();
await c.ReadByteAsync(ct); // never answers
});
await using var client = await OpenAsync(sim, timeoutMs: 10_000);
var pending = client.ReadRuntimeAsync(23, Ct);
await requested.Task.WaitAsync(TimeSpan.FromSeconds(2), Ct);
var sw = Stopwatch.StartNew();
client.Close();
await Should.ThrowAsync(() => pending.WaitAsync(TimeSpan.FromSeconds(2), Ct));
sw.ElapsedMilliseconds.ShouldBeLessThan(2000);
}
[Fact]
public async Task Trickle_cannot_reset_the_transaction_deadline()
{
await using var sim = Lsv2Simulator.WithScript(async (c, ct) =>
{
await c.ReadRequestAsync(ct);
for (var i = 0; i < 20; i++)
{
await c.WriteRawAsync([0], byteByByte: false, ct);
await Task.Delay(40, ct);
}
});
await using var client = await OpenAsync(sim, timeoutMs: 120);
var sw = Stopwatch.StartNew();
await Should.ThrowAsync(() => client.ReadRuntimeAsync(23, Ct));
sw.ElapsedMilliseconds.ShouldBeLessThan(1000);
client.IsClosed.ShouldBeTrue();
}
[Fact]
public async Task Transactions_are_serialized_one_frame_at_a_time()
{
var concurrent = 0;
var maxConcurrent = 0;
await using var sim = Lsv2Simulator.WithScript(async (c, ct) =>
{
while (await c.ReadRequestAsync(ct) is not null)
{
var now = Interlocked.Increment(ref concurrent);
maxConcurrent = Math.Max(maxConcurrent, now);
await Task.Delay(10, ct);
Interlocked.Decrement(ref concurrent);
await c.ReplyAsync("S_RI", [0, 1], ct);
}
});
await using var client = await OpenAsync(sim);
await Task.WhenAll(Enumerable.Range(0, 8).Select(_ => client.ReadRuntimeAsync(23, Ct)));
maxConcurrent.ShouldBe(1);
}
[Fact]
public async Task Connect_to_a_closed_port_is_a_transport_failure()
{
int port;
await using (var sim = Lsv2Simulator.WithScript((_, _) => Task.CompletedTask)) port = sim.Port;
var client = new Lsv2Client("127.0.0.1", port, TimeSpan.FromMilliseconds(500));
await Should.ThrowAsync(() => client.OpenAsync(Ct));
client.IsClosed.ShouldBeTrue();
}
}