using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
namespace ZB.MOM.WW.OtOpcUa.Driver.S7.Tests;
///
/// R07:P1 — once a pass has marked the connection dead (a wire op blew its deadline on a frozen
/// peer), the rest of that pass must not go to the wire: each further op would pay the full
/// timeout under the gate, so a 20-span pass took ~100 s and the comms-loss watchdog's clock only
/// started after it. The remaining items are stamped BadCommunicationError without I/O.
/// Every assertion counts wire operations; nothing is timed.
///
[Trait("Category", "Unit")]
public sealed class S7DeadHandleShortCircuitTests
{
private const uint BadCommunicationError = 0x80050000u;
private static S7DriverOptions Options(int maxGap, params S7TagDefinition[] tags) => new()
{
Host = "192.0.2.1",
Timeout = TimeSpan.FromSeconds(5),
Probe = new S7ProbeOptions { Enabled = false },
SpanReadMaxGapBytes = maxGap,
RawTags = S7RawTags.Entries(tags),
};
/// Five isolated words — far enough apart that each is its own span.
private static S7TagDefinition[] FarApartWords() =>
[.. Enumerable.Range(0, 5).Select(i => new S7TagDefinition($"W{i}", $"DB{i + 1}.DBW0", S7DataType.UInt16, Writable: true))];
private static string[] Refs(int n) => [.. Enumerable.Range(0, n).Select(i => $"W{i}")];
private static async Task<(S7Driver, ScriptedS7PlcFactory)> StartAsync(S7DriverOptions options)
{
var factory = new ScriptedS7PlcFactory();
var drv = new S7Driver(options, "s7-dead-short-circuit", factory);
await drv.InitializeAsync("{}", TestContext.Current.CancellationToken);
return (drv, factory);
}
/// Per-tag path: the first timeout ends the pass's wire traffic.
[Fact]
public async Task Per_tag_pass_stops_issuing_wire_ops_once_the_handle_is_dead()
{
var ct = TestContext.Current.CancellationToken;
var (drv, factory) = await StartAsync(Options(maxGap: -1, FarApartWords()));
using var _ = drv;
factory.Read = (_, _) => throw new TimeoutException("frozen peer");
var before = factory.WireOps;
var r = await drv.ReadAsync(Refs(5), ct);
(factory.WireOps - before).ShouldBe(1, "only the op that discovered the dead handle may go to the wire");
r.ShouldAllBe(s => s.StatusCode == BadCommunicationError);
drv.GetHealth().State.ShouldBe(DriverState.Degraded);
// Positive control: the next pass reopens and serves every tag.
factory.Read = (_, _) => Task.FromResult