test: pass TestContext.Current.CancellationToken at xUnit1051 call sites (analyzer code fix, 451 sites) (lmxopcua#725)

Claude-Session: https://claude.ai/code/session_01GT67AEHd2Acv1YPwGfXEoV
This commit is contained in:
Joseph Doherty
2026-11-09 13:19:34 -05:00
parent 5db01053e8
commit 1d7a4b7a53
77 changed files with 452 additions and 457 deletions
@@ -67,9 +67,9 @@ public sealed class ClusterAuditQueryTests : IDisposable
// Noise that must NOT appear: other cluster's structured row + an orphan NodeId.
SeedAudit("Published", clusterId: null, nodeId: "OTHER-A", ts: t0.AddMinutes(3));
SeedAudit("Published", clusterId: null, nodeId: "UNKNOWN-NODE", ts: t0.AddMinutes(4));
await _db.SaveChangesAsync();
await _db.SaveChangesAsync(TestContext.Current.CancellationToken);
var rows = await ClusterAuditQuery.ForClusterAsync(_db, "LINE3-OPCUA", pageSize: 200);
var rows = await ClusterAuditQuery.ForClusterAsync(_db, "LINE3-OPCUA", pageSize: 200, ct: TestContext.Current.CancellationToken);
rows.Select(r => r.EventType).ShouldBe(
["NodeApplied", "DraftEdited", "Published"], // newest first
@@ -83,9 +83,9 @@ public sealed class ClusterAuditQueryTests : IDisposable
SeedNode("LINE3-OPCUA", "LINE3-OPCUA-A");
var t0 = new DateTime(2026, 6, 2, 10, 0, 0, DateTimeKind.Utc);
SeedAudit("Published", clusterId: "OTHER-CLUSTER", nodeId: null, ts: t0);
await _db.SaveChangesAsync();
await _db.SaveChangesAsync(TestContext.Current.CancellationToken);
var rows = await ClusterAuditQuery.ForClusterAsync(_db, "LINE3-OPCUA", pageSize: 200);
var rows = await ClusterAuditQuery.ForClusterAsync(_db, "LINE3-OPCUA", pageSize: 200, ct: TestContext.Current.CancellationToken);
rows.ShouldBeEmpty();
}
@@ -98,9 +98,9 @@ public sealed class ClusterAuditQueryTests : IDisposable
var t0 = new DateTime(2026, 6, 2, 10, 0, 0, DateTimeKind.Utc);
for (var i = 0; i < 5; i++)
SeedAudit("DraftEdited", clusterId: null, nodeId: "LINE3-OPCUA-A", ts: t0.AddMinutes(i));
await _db.SaveChangesAsync();
await _db.SaveChangesAsync(TestContext.Current.CancellationToken);
var rows = await ClusterAuditQuery.ForClusterAsync(_db, "LINE3-OPCUA", pageSize: 3);
var rows = await ClusterAuditQuery.ForClusterAsync(_db, "LINE3-OPCUA", pageSize: 3, ct: TestContext.Current.CancellationToken);
rows.Count.ShouldBe(3);
rows.First().Timestamp.ShouldBe(t0.AddMinutes(4)); // newest
@@ -35,16 +35,16 @@ public sealed class ClusterNodeTransportPortsTests(SchemaComplianceFixture fixtu
// GrpcPort is deliberately nullable: nothing listens on it until Phase 5, and a non-null
// default would assert a port that does not exist.
ctx.ClusterNodes.Add(NewNode(clusterId, "defaulted"));
await ctx.SaveChangesAsync();
await ctx.SaveChangesAsync(TestContext.Current.CancellationToken);
await using var read = NewContext();
var explicitNode = await read.ClusterNodes.AsNoTracking()
.SingleAsync(n => n.NodeId == $"{clusterId}-explicit:4053");
.SingleAsync(n => n.NodeId == $"{clusterId}-explicit:4053", cancellationToken: TestContext.Current.CancellationToken);
explicitNode.AkkaPort.ShouldBe(4055);
explicitNode.GrpcPort.ShouldBe(5223);
var defaulted = await read.ClusterNodes.AsNoTracking()
.SingleAsync(n => n.NodeId == $"{clusterId}-defaulted:4053");
.SingleAsync(n => n.NodeId == $"{clusterId}-defaulted:4053", cancellationToken: TestContext.Current.CancellationToken);
defaulted.AkkaPort.ShouldBe(4053);
defaulted.GrpcPort.ShouldBeNull();
}
@@ -74,12 +74,12 @@ public sealed class ClusterNodeTransportPortsTests(SchemaComplianceFixture fixtu
cmd.Parameters.AddWithValue("@clusterId", clusterId);
cmd.Parameters.AddWithValue("@host", $"{clusterId}-raw");
cmd.Parameters.AddWithValue("@uri", $"urn:OtOpcUa:{clusterId}-raw");
await cmd.ExecuteNonQueryAsync();
await cmd.ExecuteNonQueryAsync(TestContext.Current.CancellationToken);
}
await using var read = NewContext();
var row = await read.ClusterNodes.AsNoTracking()
.SingleAsync(n => n.NodeId == $"{clusterId}-raw:4053");
.SingleAsync(n => n.NodeId == $"{clusterId}-raw:4053", cancellationToken: TestContext.Current.CancellationToken);
row.AkkaPort.ShouldBe(4053);
row.GrpcPort.ShouldBeNull();
}
@@ -96,13 +96,13 @@ public sealed class ClusterNodeTransportPortsTests(SchemaComplianceFixture fixtu
var clusterId = await SeedClusterAsync(ctx);
ctx.ClusterNodes.Add(NewNode(clusterId, "a", n => n.GrpcPort = 5223));
ctx.ClusterNodes.Add(NewNode(clusterId, "b"));
await ctx.SaveChangesAsync();
await ctx.SaveChangesAsync(TestContext.Current.CancellationToken);
await using var read = NewContext();
var contacts = await read.ClusterNodes.AsNoTracking()
.Where(n => n.ClusterId == clusterId && n.GrpcPort != null)
.Select(n => new { n.Host, n.AkkaPort, n.GrpcPort })
.ToListAsync();
.ToListAsync(cancellationToken: TestContext.Current.CancellationToken);
contacts.Count.ShouldBe(1);
contacts[0].AkkaPort.ShouldBe(4053);
@@ -52,7 +52,7 @@ public sealed class DraftSnapshotFactorySqlServerTests
ClusterId = clusterId, Name = "snapshot-read", Enterprise = "zb", Site = "test",
NodeCount = 1, RedundancyMode = RedundancyMode.None, CreatedBy = "test",
});
await seed.SaveChangesAsync();
await seed.SaveChangesAsync(TestContext.Current.CancellationToken);
}
try
@@ -64,7 +64,7 @@ public sealed class DraftSnapshotFactorySqlServerTests
await using (var db = new OtOpcUaConfigDbContext(options))
{
var snapshot = await DraftSnapshotFactory.FromConfigDbAsync(db);
var snapshot = await DraftSnapshotFactory.FromConfigDbAsync(db, TestContext.Current.CancellationToken);
// The interceptor committed a Script while ServerClusters (the FIRST table read) was being
// materialised. Scripts is read later in the same transaction and must not see it.
snapshot.ServerClusters.ShouldContain(c => c.ClusterId == clusterId);
@@ -74,16 +74,16 @@ public sealed class DraftSnapshotFactorySqlServerTests
await using (var verify = NewContext())
{
// Positive control: the edit really landed, and a read started afterwards sees it.
(await verify.Scripts.AnyAsync(s => s.ScriptId == scriptId)).ShouldBeTrue();
var later = await DraftSnapshotFactory.FromConfigDbAsync(verify);
(await verify.Scripts.AnyAsync(s => s.ScriptId == scriptId, cancellationToken: TestContext.Current.CancellationToken)).ShouldBeTrue();
var later = await DraftSnapshotFactory.FromConfigDbAsync(verify, TestContext.Current.CancellationToken);
later.Scripts.ShouldContain(s => s.ScriptId == scriptId);
}
}
finally
{
await using var cleanup = NewContext();
await cleanup.Scripts.Where(s => s.ScriptId == scriptId).ExecuteDeleteAsync();
await cleanup.ServerClusters.Where(c => c.ClusterId == clusterId).ExecuteDeleteAsync();
await cleanup.Scripts.Where(s => s.ScriptId == scriptId).ExecuteDeleteAsync(cancellationToken: TestContext.Current.CancellationToken);
await cleanup.ServerClusters.Where(c => c.ClusterId == clusterId).ExecuteDeleteAsync(cancellationToken: TestContext.Current.CancellationToken);
}
}
@@ -39,9 +39,9 @@ public sealed class DraftSnapshotFactoryTests : IDisposable
_db.Tags.Add(BuildTag(name: "speed"));
_db.VirtualTags.Add(BuildVirtualTag(equipmentId: "eq-1", name: "speed", suffix: "a"));
_db.VirtualTags.Add(BuildVirtualTag(equipmentId: "eq-1", name: "speed", suffix: "b"));
await _db.SaveChangesAsync();
await _db.SaveChangesAsync(TestContext.Current.CancellationToken);
var snapshot = await DraftSnapshotFactory.FromConfigDbAsync(_db);
var snapshot = await DraftSnapshotFactory.FromConfigDbAsync(_db, TestContext.Current.CancellationToken);
snapshot.Tags.Count.ShouldBe(1);
snapshot.VirtualTags.Count.ShouldBe(2);
@@ -56,9 +56,9 @@ public sealed class DraftSnapshotFactoryTests : IDisposable
SeedEquipment("eq-1");
_db.Tags.Add(BuildTag(name: "speed"));
_db.VirtualTags.Add(BuildVirtualTag(equipmentId: "eq-1", name: "temperature"));
await _db.SaveChangesAsync();
await _db.SaveChangesAsync(TestContext.Current.CancellationToken);
var snapshot = await DraftSnapshotFactory.FromConfigDbAsync(_db);
var snapshot = await DraftSnapshotFactory.FromConfigDbAsync(_db, TestContext.Current.CancellationToken);
snapshot.Tags.Count.ShouldBe(1);
snapshot.VirtualTags.Count.ShouldBe(1);
@@ -94,9 +94,9 @@ public sealed class DraftSnapshotFactoryTests : IDisposable
ReleasedBy = "test",
ReleaseReason = "retired",
});
await _db.SaveChangesAsync();
await _db.SaveChangesAsync(TestContext.Current.CancellationToken);
var snapshot = await DraftSnapshotFactory.FromConfigDbAsync(_db);
var snapshot = await DraftSnapshotFactory.FromConfigDbAsync(_db, TestContext.Current.CancellationToken);
snapshot.ActiveReservations.Count.ShouldBe(1);
snapshot.ActiveReservations[0].Value.ShouldBe("ZT-001");
@@ -124,9 +124,9 @@ public sealed class DraftSnapshotFactoryTests : IDisposable
{
ApiKeyId = "k1", Name = "scada", SecretHash = "hash", Principal = "scadabridge", Enabled = true,
});
await _db.SaveChangesAsync();
await _db.SaveChangesAsync(TestContext.Current.CancellationToken);
var snapshot = await DraftSnapshotFactory.FromConfigDbAsync(_db);
var snapshot = await DraftSnapshotFactory.FromConfigDbAsync(_db, TestContext.Current.CancellationToken);
snapshot.ServerClusters.ShouldHaveSingleItem().ClusterId.ShouldBe("SITE-A");
snapshot.ClusterNodes.ShouldHaveSingleItem().NodeId.ShouldBe("site-a-1:4053");
@@ -107,7 +107,7 @@ public sealed class ScriptedAlarmEngineRunGuardTests
await WaitForAsync(() => eng.RunGuard.StartedRunCount > before);
}
eng.RunGuard.StartedRunCount.ShouldBe(1 + 1 + pushes, "one runaway dispatch, then healthy-only dispatches");
await Task.Delay(300); // absence window for trailing emissions
await Task.Delay(300, TestContext.Current.CancellationToken); // absence window for trailing emissions
ScriptedAlarmEvent[] snapshot;
lock (events) snapshot = events.ToArray();
@@ -215,7 +215,7 @@ public sealed class ScriptedAlarmEngineTests
eng.OnEvent += (_, e) => events.Add(e);
up.Push("Temp", 150);
await Task.Delay(200);
await Task.Delay(200, TestContext.Current.CancellationToken);
events.Any(e => e.Emission == EmissionKind.Activated).ShouldBeFalse(
"OneShot shelve suppresses activation emission");
@@ -252,7 +252,7 @@ public sealed class ScriptedAlarmEngineTests
await eng.DisableAsync("HighTemp", "alice", TestContext.Current.CancellationToken);
up.Push("Temp", 150);
await Task.Delay(100);
await Task.Delay(100, TestContext.Current.CancellationToken);
eng.GetState("HighTemp")!.Active.ShouldBe(AlarmActiveState.Inactive,
"disabled alarm ignores predicate");
@@ -353,7 +353,7 @@ public sealed class ScriptedAlarmEngineTests
up.Push($"Temp{round % alarmCount}", round % 2 == 0 ? 150 : 50);
round++;
}
});
}, TestContext.Current.CancellationToken);
// Readers: continuously touch the three unguarded read paths.
var readers = Enumerable.Range(0, 4).Select(_reader => Task.Run(() =>
@@ -839,7 +839,7 @@ public sealed class ScriptedAlarmEngineTests
// Dispose must wait for the in-flight reevaluation to complete rather
// than returning while a background task still runs.
var disposeTask = Task.Run(() => eng.Dispose());
var disposeTask = Task.Run(() => eng.Dispose(), TestContext.Current.CancellationToken);
// Verify Dispose does NOT complete immediately — it should block waiting
// for the in-flight task. Without the -006 fix Dispose returns straight
@@ -1003,7 +1003,7 @@ public sealed class ScriptedAlarmEngineTests
// load could keep firing between the failed second load and Dispose.
// After the fix, it is stopped at the START of every LoadAsync attempt
// (successful or not), so Dispose always finds a clean timer state.
var disposeTask = Task.Run(() => eng.Dispose());
var disposeTask = Task.Run(() => eng.Dispose(), TestContext.Current.CancellationToken);
await disposeTask.WaitAsync(TimeSpan.FromSeconds(3), TestContext.Current.CancellationToken);
// If Dispose threw or hung, the WaitAsync would surface it.
}
@@ -1748,12 +1748,12 @@ public sealed class ScriptedAlarmEngineTests
eng.TrackBackgroundTaskForTest(() => gate.Task);
eng.InFlightCountForTest.ShouldBe(1);
var disposeTask = Task.Run(() => eng.Dispose());
var disposeTask = Task.Run(() => eng.Dispose(), TestContext.Current.CancellationToken);
var raced = await Task.WhenAny(disposeTask, Task.Delay(300));
raced.ShouldNotBe(disposeTask, "Dispose must not return while registered background work is still running");
gate.SetResult();
await disposeTask.WaitAsync(TimeSpan.FromSeconds(5));
await disposeTask.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
eng.InFlightCountForTest.ShouldBe(0, "completed work must unregister itself");
}
@@ -1785,7 +1785,7 @@ public sealed class ScriptedAlarmEngineTests
() => throw new InvalidOperationException("factory failed (test)")));
eng.InFlightCountForTest.ShouldBe(0, "work that never started must not be left registered");
await Task.Run(() => eng.Dispose()).WaitAsync(TimeSpan.FromSeconds(5));
await Task.Run(() => eng.Dispose(), TestContext.Current.CancellationToken).WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
}
/// <summary>Verifies a faulted background task is still drained by Dispose and its failure is
@@ -1801,11 +1801,11 @@ public sealed class ScriptedAlarmEngineTests
// Fault it while Dispose is actually blocked on the drain, so the WhenAll observes
// the failure rather than finding an already-unregistered task.
var disposeTask = Task.Run(() => Should.NotThrow(() => eng.Dispose()));
await Task.Delay(200);
var disposeTask = Task.Run(() => Should.NotThrow(() => eng.Dispose()), TestContext.Current.CancellationToken);
await Task.Delay(200, TestContext.Current.CancellationToken);
gate.SetException(new InvalidOperationException("background failed (test)"));
await disposeTask.WaitAsync(TimeSpan.FromSeconds(5));
await disposeTask.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
eng.InFlightCountForTest.ShouldBe(0);
}
@@ -46,7 +46,7 @@ public sealed class ScriptedAlarmSourceLoggingTests
if (sinkCapture.Events.Any(e => e.Level == LogEventLevel.Warning && e.Exception?.Message == "subscriber broke"))
break;
}
await Task.Delay(25);
await Task.Delay(25, TestContext.Current.CancellationToken);
}
LogEvent warning;
@@ -53,7 +53,7 @@ public sealed class ScriptedAlarmSourceTests
var handle = await source.SubscribeAlarmsAsync([], TestContext.Current.CancellationToken);
up.Push("Temp", 150);
await Task.Delay(200);
await Task.Delay(200, TestContext.Current.CancellationToken);
events.Count.ShouldBe(1);
events[0].ConditionId.ShouldBe("Plant/Line1::HighTemp");
@@ -80,7 +80,7 @@ public sealed class ScriptedAlarmSourceTests
var handle = await source.SubscribeAlarmsAsync(["Plant/Line1"], TestContext.Current.CancellationToken);
up.Push("Temp", 150);
await Task.Delay(200);
await Task.Delay(200, TestContext.Current.CancellationToken);
events.Count.ShouldBe(1);
events[0].SourceNodeId.ShouldBe("Plant/Line1");
@@ -102,7 +102,7 @@ public sealed class ScriptedAlarmSourceTests
await source.UnsubscribeAlarmsAsync(handle, TestContext.Current.CancellationToken);
up.Push("Temp", 150);
await Task.Delay(200);
await Task.Delay(200, TestContext.Current.CancellationToken);
events.Count.ShouldBe(0);
}
@@ -124,7 +124,7 @@ public sealed class ScriptedAlarmSourceTests
// Drive HighTemp's input Bad: the predicate freezes (no transition), but the worst-quality bucket
// moves Good→Bad → the engine emits QualityChanged. The source must swallow it.
up.Push("Temp", 50, 0x80000000u);
await Task.Delay(200);
await Task.Delay(200, TestContext.Current.CancellationToken);
events.ShouldBeEmpty();
}
@@ -138,7 +138,7 @@ public sealed class ScriptedAlarmSourceTests
using var _s = source;
up.Push("Temp", 150);
await Task.Delay(200);
await Task.Delay(200, TestContext.Current.CancellationToken);
engine.GetState("Plant/Line1::HighTemp")!.Acked.ShouldBe(AlarmAckedState.Unacknowledged);
await source.AcknowledgeAsync([new AlarmAcknowledgeRequest(
@@ -165,7 +165,7 @@ public sealed class ScriptedAlarmSourceTests
// Supplied principal -> honored.
up.Push("Temp", 150);
await Task.Delay(200);
await Task.Delay(200, TestContext.Current.CancellationToken);
await source.AcknowledgeAsync([new AlarmAcknowledgeRequest(
"Plant/Line1", "Plant/Line1::HighTemp", "ack as bob", "bob")],
TestContext.Current.CancellationToken);
@@ -173,9 +173,9 @@ public sealed class ScriptedAlarmSourceTests
// No principal -> default audit identity.
up.Push("Temp", 50);
await Task.Delay(200);
await Task.Delay(200, TestContext.Current.CancellationToken);
up.Push("Temp", 150);
await Task.Delay(200);
await Task.Delay(200, TestContext.Current.CancellationToken);
await source.AcknowledgeAsync([new AlarmAcknowledgeRequest(
"Plant/Line1", "Plant/Line1::HighTemp", "ack anon", null)],
TestContext.Current.CancellationToken);
@@ -36,7 +36,7 @@ public sealed class ScriptCancellationTokenTests
{
using var eval = ScriptEvaluator<FakeScriptContext, int>.Compile("return 1;");
var ctx = new FakeScriptContext();
(await eval.RunAsync(ctx)).ShouldBe(1);
(await eval.RunAsync(ctx, TestContext.Current.CancellationToken)).ShouldBe(1);
ctx.CancellationToken.ShouldBe(CancellationToken.None, "the token is scoped to the run, not left on the context");
}
@@ -26,7 +26,7 @@ public sealed class DriverResiliencePipelineBuilderTests
attempts++;
if (attempts < 3) throw new InvalidOperationException("transient");
await Task.Yield();
});
}, TestContext.Current.CancellationToken);
attempts.ShouldBe(3);
}
@@ -141,7 +141,7 @@ public sealed class DriverResiliencePipelineBuilderTests
{
liveAttempts++;
await Task.Yield();
});
}, TestContext.Current.CancellationToken);
liveAttempts.ShouldBe(1, "healthy sibling host must not be affected by dead peer");
}
@@ -200,7 +200,7 @@ public sealed class DriverResiliencePipelineBuilderTests
{
await Task.Yield();
ran = true;
});
}, TestContext.Current.CancellationToken);
ran.ShouldBeTrue("the breaker must stay closed after refusals");
}
@@ -341,7 +341,7 @@ public sealed class DriverResiliencePipelineBuilderTests
// Elapse the break duration (15 s) so the breaker half-opens, then let a probe succeed → OnClosed.
clock.Advance(TimeSpan.FromSeconds(16));
await pipeline.ExecuteAsync(async _ => await Task.Yield());
await pipeline.ExecuteAsync(async _ => await Task.Yield(), TestContext.Current.CancellationToken);
var snap = tracker.TryGet("drv-trk", "host-c")!;
snap.LastBreakerClosedUtc.ShouldNotBeNull("OnClosed must stamp the close time on recovery");
@@ -404,7 +404,7 @@ public sealed class DriverResiliencePipelineBuilderTests
await Task.Yield();
throw new InvalidOperationException("dead");
}));
await live.ExecuteAsync(async _ => await Task.Yield());
await live.ExecuteAsync(async _ => await Task.Yield(), TestContext.Current.CancellationToken);
tracker.TryGet("drv-trk", "dead")!.ConsecutiveFailures.ShouldBeGreaterThan(0);
tracker.TryGet("drv-trk", "live").ShouldBeNull();
@@ -428,7 +428,7 @@ public sealed class DriverResiliencePipelineBuilderTests
attempts++;
if (attempts < 3) throw new InvalidOperationException("transient");
await Task.Yield();
});
}, TestContext.Current.CancellationToken);
attempts.ShouldBe(3);
logger.Entries.ShouldContain(e =>