97991e0476
Comms_loss_invalidates_every_remote_value_and_recovery_republishes_identical_values failed
1/40 on base 5bbe1e3c (and 1/29 on this branch): "Capabilities/Identity should be
CommunicationLost but was Supported". RetireAll -> Invalidate publishes every tag in authored
order under one lock, capability LAST, and the recorder sees each publish as it happens; the
test asserted the capability the instant the five value tags read BadNoCommunication, i.e.
before the pass's final publish. Now the wait includes the capability's CommunicationLost
(a presence the pass must produce) and additionally asserts no value went Good again during
the outage.
Second latent race fixed in the same test: Degraded holds through Backoff AND Connecting, but
the host status is Stopped only in Backoff (Unknown while a reconnect attempt is in flight),
so the test now waits for Degraded && Stopped instead of sampling whichever phase it hit.
After the fix: 79/80 filtered runs passed and 10/10 full-suite runs; the one non-pass was a vstest
"failed to connect to testhost after 90 s" host-startup timeout (the test never ran), not a test result.
320 lines
16 KiB
C#
320 lines
16 KiB
C#
using System.Collections.Concurrent;
|
|
using System.Text.Json;
|
|
using Shouldly;
|
|
using Xunit;
|
|
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
|
using ZB.MOM.WW.OtOpcUa.Core.Hosting;
|
|
using ZB.MOM.WW.OtOpcUa.Driver.Heidenhain.Tests.Simulator;
|
|
|
|
namespace ZB.MOM.WW.OtOpcUa.Driver.Heidenhain.Tests;
|
|
|
|
/// <summary>
|
|
/// End-to-end driver behaviour against the in-process LSV2 simulator: cached reads, subscription fan-out,
|
|
/// all-node invalidation on comms loss, recovery re-publish of IDENTICAL values, bounded reconnect,
|
|
/// re-init teardown, browse-without-connect and the read-only boundary.
|
|
/// </summary>
|
|
[Trait("Category", "Unit")]
|
|
public sealed class HeidenhainDriverTests
|
|
{
|
|
private static CancellationToken Ct => TestContext.Current.CancellationToken;
|
|
|
|
private static SimulatedControl Itnc()
|
|
{
|
|
var c = new SimulatedControl();
|
|
c.Runtime[23] = () => SimulatedControl.U16(4);
|
|
c.Runtime[26] = () => SimulatedControl.U16(7);
|
|
c.Runtime[25] = () => SimReply.Ok("S_RI", [0, 0, 0x27, 0x10, 0, 0, 0x1F, 0x40, 0, 0, 0, 0]);
|
|
c.Runtime[27] = () => SimReply.Refuse(57);
|
|
c.Memory = (_, n) => SimReply.Ok("S_MB", n == 4 ? [42, 0, 0, 0] : new byte[n]);
|
|
return c;
|
|
}
|
|
|
|
private static HeidenhainDriverOptions Options(int port, params RawTagEntry[] tags) => new()
|
|
{
|
|
Devices = [new HeidenhainDeviceOptions { Host = "127.0.0.1", Port = port, DeviceName = "dev1" }],
|
|
RawTags = tags,
|
|
TimeoutMs = 500,
|
|
Polling = new HeidenhainPollingOptions { StatusMs = 100, CustomMs = 100, SlowMs = 300 },
|
|
Reconnect = new HeidenhainReconnectOptions { InitialDelayMs = 100, MaxDelayMs = 400 },
|
|
};
|
|
|
|
private static RawTagEntry[] StandardTags() =>
|
|
[
|
|
TestTags.Raw("Status/ExecutionState"),
|
|
TestTags.Raw("Overrides/Feed"),
|
|
TestTags.Raw("Controller/Model"),
|
|
TestTags.Raw("Alarms/Count"),
|
|
TestTags.Raw("PLC:DWORD:0", "Int64"),
|
|
TestTags.Raw("Capabilities/Identity"),
|
|
];
|
|
|
|
private sealed class Recorder
|
|
{
|
|
public ConcurrentQueue<(string Ref, DataValueSnapshot Snapshot)> Events { get; } = new();
|
|
public void Attach(HeidenhainDriver d) => d.OnDataChange += (_, e) => Events.Enqueue((e.FullReference, e.Snapshot));
|
|
public IReadOnlyList<DataValueSnapshot> For(string rawPath) => Events.Where(e => e.Ref == rawPath).Select(e => e.Snapshot).ToList();
|
|
public DataValueSnapshot? Last(string rawPath) => For(rawPath).LastOrDefault();
|
|
}
|
|
|
|
private static async Task WaitUntil(Func<bool> condition, int timeoutMs = 5000)
|
|
{
|
|
var deadline = DateTime.UtcNow.AddMilliseconds(timeoutMs);
|
|
while (!condition())
|
|
{
|
|
if (DateTime.UtcNow > deadline) throw new TimeoutException("condition not reached");
|
|
await Task.Delay(20, Ct);
|
|
}
|
|
}
|
|
|
|
private static HeidenhainDriver Create(HeidenhainDriverOptions o) =>
|
|
new(o, "hh-1", null, new HeidenhainCredentials(null), null, null);
|
|
|
|
[Fact]
|
|
public async Task Initialize_and_discovery_never_contact_the_control()
|
|
{
|
|
var control = Itnc();
|
|
await using var sim = Lsv2Simulator.WithControl(control);
|
|
await using var d = Create(Options(sim.Port, StandardTags()));
|
|
await d.InitializeAsync("{}", Ct);
|
|
var builder = new CapturingBuilder();
|
|
await d.DiscoverAsync(builder, Ct);
|
|
await Task.Delay(200, Ct);
|
|
sim.Connections.ShouldBe(0);
|
|
builder.Variables.Count.ShouldBe(HeidenhainCatalog.Entries.Count);
|
|
builder.Variables.ShouldContain(v => v.FullName == "Axes/Positions" && v.IsArray && v.DriverDataType == DriverDataType.Float64);
|
|
builder.Variables.ShouldAllBe(v => v.SecurityClass == SecurityClassification.ViewOnly);
|
|
d.GetHealth().State.ShouldBe(DriverState.Healthy);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Subscribe_pushes_initial_state_then_cached_good_values_and_reads_never_touch_the_wire()
|
|
{
|
|
var control = Itnc();
|
|
await using var sim = Lsv2Simulator.WithControl(control);
|
|
var tags = StandardTags();
|
|
await using var d = Create(Options(sim.Port, tags));
|
|
var rec = new Recorder();
|
|
rec.Attach(d);
|
|
await d.InitializeAsync("{}", Ct);
|
|
await d.SubscribeAsync(tags.Select(t => t.RawPath).ToList(), TimeSpan.FromMilliseconds(100), Ct);
|
|
rec.For(tags[0].RawPath)[0].StatusCode.ShouldBe(HeidenhainStatus.BadWaitingForInitialData);
|
|
await WaitUntil(() => rec.Last(tags[3].RawPath)?.StatusCode == HeidenhainStatus.Good
|
|
&& rec.Last(tags[4].RawPath)?.StatusCode == HeidenhainStatus.Good);
|
|
rec.Last(tags[0].RawPath)!.Value.ShouldBe(4);
|
|
rec.Last(tags[1].RawPath)!.Value.ShouldBe(100.0);
|
|
rec.Last(tags[2].RawPath)!.Value.ShouldBe("iTNC 530");
|
|
rec.Last(tags[3].RawPath)!.Value.ShouldBe(0);
|
|
rec.Last(tags[4].RawPath)!.Value.ShouldBe(42L);
|
|
rec.Last(tags[5].RawPath)!.Value.ShouldBe("Supported");
|
|
|
|
var before = sim.Requests.Count;
|
|
var read = await d.ReadAsync([tags[0].RawPath, "Plant/H/dev1/nope"], Ct);
|
|
read[0].Value.ShouldBe(4);
|
|
read[1].StatusCode.ShouldBe(HeidenhainStatus.BadNodeIdUnknown);
|
|
sim.Requests.Count.ShouldBeLessThanOrEqualTo(before + 3); // the background loop may tick; the read itself is cache-only
|
|
d.GetHealth().State.ShouldBe(DriverState.Healthy);
|
|
d.GetHostStatuses().Single().State.ShouldBe(HostState.Running);
|
|
control.Violations.ShouldBeEmpty();
|
|
sim.Requests.Select(r => r.Command).Distinct().ShouldBeSubsetOf(new[] { "A_LG", "R_VR", "R_PR", "R_RI", "R_MB" });
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Unchanged_values_are_not_republished()
|
|
{
|
|
var control = Itnc();
|
|
await using var sim = Lsv2Simulator.WithControl(control);
|
|
var tag = TestTags.Raw("Status/ExecutionState");
|
|
await using var d = Create(Options(sim.Port, tag));
|
|
var rec = new Recorder();
|
|
rec.Attach(d);
|
|
await d.InitializeAsync("{}", Ct);
|
|
await d.SubscribeAsync([tag.RawPath], TimeSpan.FromMilliseconds(100), Ct);
|
|
await WaitUntil(() => sim.Requests.Count(r => r.Command == "R_RI") >= 5);
|
|
rec.For(tag.RawPath).Count.ShouldBe(2); // initial BadWaitingForInitialData + one Good
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Comms_loss_invalidates_every_remote_value_and_recovery_republishes_identical_values()
|
|
{
|
|
var control = Itnc();
|
|
await using var sim = Lsv2Simulator.WithControl(control);
|
|
var tags = StandardTags();
|
|
await using var d = Create(Options(sim.Port, tags));
|
|
var rec = new Recorder();
|
|
rec.Attach(d);
|
|
var hostEvents = new ConcurrentQueue<HostStatusChangedEventArgs>();
|
|
d.OnHostStatusChanged += (_, e) => hostEvents.Enqueue(e);
|
|
await d.InitializeAsync("{}", Ct);
|
|
await d.SubscribeAsync(tags.Select(t => t.RawPath).ToList(), TimeSpan.FromMilliseconds(100), Ct);
|
|
await WaitUntil(() => tags.All(t => rec.Last(t.RawPath)?.StatusCode == HeidenhainStatus.Good));
|
|
var lastGood = d.GetHealth().LastSuccessfulRead;
|
|
|
|
sim.GoOffline();
|
|
// EVERY remote leaf — fast status, slow identity/alarms and custom PLC — goes Bad at once.
|
|
// The invalidation is ONE pass over the device's tags (in authored order, capability last), delivered to this
|
|
// thread's recorder as it runs — so wait for the WHOLE pass to land (the capability's CommunicationLost is
|
|
// its last publication) before asserting on any of it. Asserting the capability the instant the five value
|
|
// tags read Bad raced the pass's final publish (1/40 on 5bbe1e3c: "Supported").
|
|
await WaitUntil(() => tags.Take(5).All(t => rec.Last(t.RawPath)?.StatusCode == HeidenhainStatus.BadNoCommunication)
|
|
&& rec.Last(tags[5].RawPath)?.Value is "CommunicationLost");
|
|
rec.Last(tags[5].RawPath)!.StatusCode.ShouldBe(HeidenhainStatus.Good);
|
|
// ...and it is one pass: no remote value published Good again after its outage invalidation.
|
|
foreach (var t in tags.Take(5))
|
|
{
|
|
var seq = rec.For(t.RawPath).Select(s => s.StatusCode).ToList();
|
|
seq.Skip(seq.LastIndexOf(HeidenhainStatus.BadNoCommunication)).ShouldAllBe(s => s == HeidenhainStatus.BadNoCommunication);
|
|
}
|
|
|
|
(await d.ReadAsync([tags[2].RawPath], Ct))[0].StatusCode.ShouldBe(HeidenhainStatus.BadNoCommunication);
|
|
// Degraded holds through every reconnect attempt (Backoff AND Connecting carry the last error), but the host
|
|
// status reads Stopped only in Backoff and Unknown while a reconnect attempt is in flight — so wait for the
|
|
// Backoff phase rather than sample whichever phase the loop happens to be in.
|
|
await WaitUntil(() => d.GetHealth().State == DriverState.Degraded && d.GetHostStatuses().Single().State == HostState.Stopped);
|
|
d.GetHealth().LastError.ShouldNotBeNullOrEmpty();
|
|
hostEvents.ShouldContain(e => e.NewState == HostState.Stopped);
|
|
var frozen = d.GetHealth().LastSuccessfulRead;
|
|
await Task.Delay(500, Ct);
|
|
d.GetHealth().LastSuccessfulRead.ShouldBe(frozen); // frozen while down — the comms-loss watchdog's evidence
|
|
(frozen <= lastGood!.Value.AddSeconds(1)).ShouldBeTrue();
|
|
|
|
sim.GoOnline();
|
|
// The control comes back holding the SAME readings: the (value, status) dedup must still re-publish.
|
|
await WaitUntil(() => tags.All(t => rec.Last(t.RawPath)?.StatusCode == HeidenhainStatus.Good), 8000);
|
|
foreach (var t in tags.Take(5))
|
|
{
|
|
var seq = rec.For(t.RawPath).Select(s => s.StatusCode).ToList();
|
|
seq.ShouldContain(HeidenhainStatus.BadNoCommunication);
|
|
seq[^1].ShouldBe(HeidenhainStatus.Good);
|
|
}
|
|
|
|
rec.Last(tags[0].RawPath)!.Value.ShouldBe(4);
|
|
rec.Last(tags[4].RawPath)!.Value.ShouldBe(42L);
|
|
d.GetHealth().State.ShouldBe(DriverState.Healthy);
|
|
hostEvents.Last().NewState.ShouldBe(HostState.Running);
|
|
control.Violations.ShouldBeEmpty();
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Reconnect_is_bounded_exponential_backoff()
|
|
{
|
|
int port;
|
|
await using (var probe = Lsv2Simulator.WithScript((_, _) => Task.CompletedTask)) port = probe.Port;
|
|
var tag = TestTags.Raw("Status/ExecutionState");
|
|
var o = Options(port, tag);
|
|
var attempts = new ConcurrentQueue<DateTime>();
|
|
var d = new HeidenhainDriver(o, "hh-1", null, new HeidenhainCredentials(null),
|
|
(h, p, t) => { attempts.Enqueue(DateTime.UtcNow); return new Lsv2.Lsv2Client(h, p, t); }, null);
|
|
await using (d)
|
|
{
|
|
await d.InitializeAsync("{}", Ct);
|
|
await d.SubscribeAsync([tag.RawPath], TimeSpan.FromSeconds(1), Ct);
|
|
await Task.Delay(2000, Ct);
|
|
var a = attempts.ToArray();
|
|
a.Length.ShouldBeInRange(3, 8); // 100, 200, 400, 400, … ms — never a hot loop
|
|
for (var i = 2; i < a.Length; i++)
|
|
(a[i] - a[i - 1]).TotalMilliseconds.ShouldBeGreaterThan(150);
|
|
d.GetHealth().State.ShouldBe(DriverState.Degraded);
|
|
(await d.ReadAsync([tag.RawPath], Ct))[0].StatusCode.ShouldBe(HeidenhainStatus.BadNoCommunication);
|
|
}
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Refusals_are_per_tag_quality_and_do_not_degrade_driver_health()
|
|
{
|
|
var control = Itnc();
|
|
control.Runtime[25] = () => SimReply.Refuse(23);
|
|
control.Login = (role, _) => role == "DNC" ? SimReply.Refuse(23) : SimReply.Ok("T_OK", []);
|
|
await using var sim = Lsv2Simulator.WithControl(control);
|
|
var tags = new[] { TestTags.Raw("Status/ExecutionState"), TestTags.Raw("Overrides/Feed"), TestTags.Raw("PLC:WORD:1", "Int32") };
|
|
control.Memory = null; // R_MB denied, as on every tested iTNC 530
|
|
await using var d = Create(Options(sim.Port, tags));
|
|
var rec = new Recorder();
|
|
rec.Attach(d);
|
|
await d.InitializeAsync("{}", Ct);
|
|
await d.SubscribeAsync(tags.Select(t => t.RawPath).ToList(), TimeSpan.FromMilliseconds(100), Ct);
|
|
await WaitUntil(() => rec.Last(tags[2].RawPath)?.StatusCode == HeidenhainStatus.BadUserAccessDenied);
|
|
rec.Last(tags[0].RawPath)!.Value.ShouldBe(4);
|
|
rec.Last(tags[1].RawPath)!.StatusCode.ShouldBe(HeidenhainStatus.BadUserAccessDenied);
|
|
d.GetHealth().State.ShouldBe(DriverState.Healthy);
|
|
d.GetHealth().LastSuccessfulRead.ShouldNotBeNull();
|
|
d.GetDiagnostics().Values.ShouldContain("Partial");
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Reinitialize_tears_down_the_previous_session_before_reconnecting()
|
|
{
|
|
var control = Itnc();
|
|
await using var sim = Lsv2Simulator.WithControl(control);
|
|
var tag = TestTags.Raw("Status/ExecutionState");
|
|
var json = JsonSerializer.Serialize(Options(sim.Port, tag));
|
|
await using var d = HeidenhainDriverFactoryExtensions.CreateInstance("hh-1", json);
|
|
for (var i = 0; i < 3; i++)
|
|
{
|
|
await d.InitializeAsync(json, Ct);
|
|
await d.SubscribeAsync([tag.RawPath], TimeSpan.FromMilliseconds(100), Ct);
|
|
await WaitUntil(() => sim.Connections == i + 1);
|
|
}
|
|
|
|
await d.ShutdownAsync(Ct);
|
|
await Task.Delay(200, Ct);
|
|
var after = sim.Requests.Count;
|
|
await Task.Delay(300, Ct);
|
|
sim.Requests.Count.ShouldBe(after); // nothing polls after shutdown
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Bad_tags_and_unknown_devices_are_skipped_and_reported()
|
|
{
|
|
var o = Options(19000,
|
|
TestTags.Raw("Status/ExecutionState"),
|
|
new RawTagEntry("Plant/H/dev1/bad", """{"address":"PLC:WORD:0","dataType":"Boolean"}""", false, "dev1"),
|
|
TestTags.Raw("Status/ProgramState", device: "other"));
|
|
o = new HeidenhainDriverOptions
|
|
{
|
|
Devices = [o.Devices[0], new HeidenhainDeviceOptions { Host = "127.0.0.2", DeviceName = "dev2" }],
|
|
RawTags = o.RawTags,
|
|
};
|
|
await using var d = Create(o);
|
|
await d.InitializeAsync("{}", Ct);
|
|
var report = d.GetSkippedTags()!;
|
|
report.AuthoredCount.ShouldBe(3);
|
|
report.SkippedCount.ShouldBe(2);
|
|
(await d.ReadAsync(["Plant/H/dev1/bad"], Ct))[0].StatusCode.ShouldBe(HeidenhainStatus.BadNodeIdUnknown);
|
|
d.ResolveHost("Plant/H/dev1/Status/ExecutionState").ShouldBe("127.0.0.1:19000");
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Factory_registers_under_the_canonical_type_and_rejects_literal_passwords()
|
|
{
|
|
var registry = new DriverFactoryRegistry();
|
|
HeidenhainDriverFactoryExtensions.Register(registry);
|
|
var json = """{"Devices":[{"Host":"10.0.0.5","DeviceName":"d"}],"Access":{"InspectPassword":"secret:heidenhain/inspect"}}""";
|
|
var driver = registry.TryGet(DriverTypeNames.Heidenhain)!("hh", json);
|
|
driver.ShouldBeOfType<HeidenhainDriver>();
|
|
driver.DriverType.ShouldBe(DriverTypeNames.Heidenhain);
|
|
Should.Throw<InvalidOperationException>(() =>
|
|
HeidenhainDriverFactoryExtensions.CreateInstance("hh", """{"Access":{"InspectPassword":"plain"}}"""));
|
|
await Task.CompletedTask;
|
|
}
|
|
|
|
private sealed class CapturingBuilder : IAddressSpaceBuilder
|
|
{
|
|
public List<DriverAttributeInfo> Variables { get; } = [];
|
|
public IAddressSpaceBuilder Folder(string browseName, string displayName) => this;
|
|
|
|
public IVariableHandle Variable(string browseName, string displayName, DriverAttributeInfo attributeInfo)
|
|
{
|
|
Variables.Add(attributeInfo);
|
|
return new Handle(attributeInfo.FullName);
|
|
}
|
|
|
|
public void AddProperty(string browseName, DriverDataType dataType, object? value) { }
|
|
|
|
private sealed class Handle(string fullReference) : IVariableHandle
|
|
{
|
|
public string FullReference => fullReference;
|
|
public IAlarmConditionSink MarkAsAlarmCondition(AlarmConditionInfo info) => throw new NotSupportedException();
|
|
}
|
|
}
|
|
}
|