diff --git a/tests/Titano.Data.Tests/Sessions/SessionTests.cs b/tests/Titano.Data.Tests/Sessions/SessionTests.cs index 72b7706b..fc9ca0f6 100644 --- a/tests/Titano.Data.Tests/Sessions/SessionTests.cs +++ b/tests/Titano.Data.Tests/Sessions/SessionTests.cs @@ -240,10 +240,21 @@ public abstract class SessionTests(TestContext context) : DatabaseTest(context) "WITH RECURSIVE r(n) AS (SELECT 1 UNION ALL SELECT n + 1 FROM r WHERE n < 2000000000) SELECT count(*) FROM r", "SELECT pg_sleep(10)"); using var cts = CancellationTokenSource.CreateLinkedTokenSource(Ct); - cts.CancelAfter(300); var watch = Stopwatch.StartNew(); + var cancelledAt = TimeSpan.Zero; + // A dedicated thread, not CancelAfter: a timer on a busy thread pool can fire late and skew the measurement. + var canceller = new Thread(() => + { + Thread.Sleep(300); + cancelledAt = watch.Elapsed; + cts.Cancel(); + }) + { IsBackground = true }; + canceller.Start(); await Assert.ThrowsAsync(() => session.ExecuteAsync(sql, [], cts.Token)); - Assert.Less(watch.Elapsed.TotalSeconds, 2.0, "cancellation latency"); + var stoppedAt = watch.Elapsed; + canceller.Join(); + Assert.Less((stoppedAt - cancelledAt).TotalSeconds, 1.0, "cancellation latency"); Assert.Equal(1, await session.ScalarAsync("SELECT 1", [], Ct)); } }