using Shouldly; using ZB.MOM.WW.OtOpcUa.Tests; using Xunit; namespace ZB.MOM.WW.OtOpcUa.Driver.TwinCAT.Tests; /// /// #630 (same pattern) — InitializeAsync on a live driver overwrote _devices[host] and /// orphaned the previous state's probe loop + client. It now releases them first. /// [Trait("Category", "Unit")] public sealed class TwinCATReinitializeReleasesStateTests(ITestOutputHelper output) { /// Initialize twice: the first state's probe loop has finished and its client is disposed. [Fact] public async Task SecondInitialize_StopsFirstStatesLoop_AndDisposesItsClient() { const string host = "ads://5.23.91.23.1.1:851"; var factory = new FakeTwinCATClientFactory(); var drv = new TwinCATDriver(new TwinCATDriverOptions { Devices = [new TwinCATDeviceOptions(host)], Probe = new TwinCATProbeOptions { Enabled = true, Interval = TimeSpan.FromMilliseconds(20), Timeout = TimeSpan.FromSeconds(1) }, }, "drv-reinit", factory); await FixtureCleanup.RunAsync(async () => { await drv.InitializeAsync("{}", CancellationToken.None); var first = drv.GetDeviceState(host)!; // Positive control: the first probe loop is running and holds a connected client. var deadline = DateTime.UtcNow.AddSeconds(5); while (!(factory.Clients.Count > 0 && factory.Clients[0].IsConnected)) { if (DateTime.UtcNow > deadline) throw new TimeoutException("probe never connected"); await Task.Delay(10); } var firstClient = factory.Clients[0]; var firstLoop = first.ProbeTask; _ = firstLoop.ShouldNotBeNull(); firstLoop!.IsCompleted.ShouldBeFalse(); await drv.InitializeAsync("{}", CancellationToken.None); firstLoop.IsCompleted.ShouldBeTrue(); // joined firstClient.DisposeCount.ShouldBeGreaterThanOrEqualTo(1); firstClient.IsConnected.ShouldBeFalse(); drv.GetDeviceState(host).ShouldNotBeSameAs(first); }, () => drv.ShutdownAsync(CancellationToken.None), failure => output.WriteLine($"TwinCAT SecondInitialize cleanup failed: {failure}")); } /// Failure after a live first or replacement state must release both owned resources. [Theory] [InlineData(false)] [InlineData(true)] public async Task Body_failure_releases_live_probe_resources(bool afterReplacement) { const string host = "ads://5.23.91.23.1.1:851"; var factory = new FakeTwinCATClientFactory(); var drv = new TwinCATDriver(new TwinCATDriverOptions { Devices = [new TwinCATDeviceOptions(host)], Probe = new TwinCATProbeOptions { Enabled = true, Interval = TimeSpan.FromMilliseconds(20), Timeout = TimeSpan.FromSeconds(1) }, }, "drv-reinit", factory); Task? firstLoop = null, secondLoop = null; FakeTwinCATClient? firstClient = null, secondClient = null; var sentinel = new InvalidOperationException("body sentinel"); var actual = await Should.ThrowAsync(() => FixtureCleanup.RunAsync(async () => { await drv.InitializeAsync("{}", CancellationToken.None); await WaitUntilAsync(() => factory.Clients.Count > 0 && factory.Clients[0].IsConnected); firstClient = factory.Clients[0]; firstLoop = drv.GetDeviceState(host)!.ProbeTask; _ = firstLoop.ShouldNotBeNull(); firstLoop!.IsCompleted.ShouldBeFalse(); if (afterReplacement) { await drv.InitializeAsync("{}", CancellationToken.None); await WaitUntilAsync(() => factory.Clients.Count > 1 && factory.Clients[1].IsConnected); secondClient = factory.Clients[1]; secondLoop = drv.GetDeviceState(host)!.ProbeTask; _ = secondLoop.ShouldNotBeNull(); secondLoop!.IsCompleted.ShouldBeFalse(); } throw sentinel; }, () => drv.ShutdownAsync(CancellationToken.None), failure => output.WriteLine($"TwinCAT failure fixture cleanup failed: {failure}"))); actual.ShouldBeSameAs(sentinel); firstLoop!.IsCompleted.ShouldBeTrue(); firstClient!.DisposeCount.ShouldBeGreaterThanOrEqualTo(1); firstClient.IsConnected.ShouldBeFalse(); if (afterReplacement) { secondLoop!.IsCompleted.ShouldBeTrue(); secondClient!.DisposeCount.ShouldBeGreaterThanOrEqualTo(1); secondClient.IsConnected.ShouldBeFalse(); } } private static async Task WaitUntilAsync(Func condition) { var deadline = DateTime.UtcNow.AddSeconds(5); while (!condition()) { if (DateTime.UtcNow > deadline) throw new TimeoutException("probe never connected"); await Task.Delay(10); } } }