From 6c1678778703127732a6fb0b1313097111da85dc Mon Sep 17 00:00:00 2001 From: Victor Milovanov Date: Sat, 20 Feb 2021 18:46:38 -0800 Subject: [PATCH] made InterruptTest more robust should resolve this failure: https://github.com/pythonnet/pythonnet/pull/1392/checks?check_run_id=1944113649 related to https://github.com/pythonnet/pythonnet/pull/1337 --- src/embed_tests/TestInterrupt.cs | 25 +++++++++++++------------ 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/src/embed_tests/TestInterrupt.cs b/src/embed_tests/TestInterrupt.cs index e075d1194..a40407782 100644 --- a/src/embed_tests/TestInterrupt.cs +++ b/src/embed_tests/TestInterrupt.cs @@ -1,5 +1,5 @@ - using System; +using System.Diagnostics; using System.Threading; using System.Threading.Tasks; @@ -30,14 +30,13 @@ public void Dispose() [Test] public void InterruptTest() { - int runSimpleStringReturnValue = int.MinValue; - ulong pythonThreadID = ulong.MinValue; - Task.Factory.StartNew(() => + long pythonThreadID = 0; + var asyncCall = Task.Factory.StartNew(() => { using (Py.GIL()) { - pythonThreadID = PythonEngine.GetPythonThreadID(); - runSimpleStringReturnValue = PythonEngine.RunSimpleString(@" + Interlocked.Exchange(ref pythonThreadID, (long)PythonEngine.GetPythonThreadID()); + return PythonEngine.RunSimpleString(@" import time while True: @@ -45,19 +44,21 @@ import time } }); - Thread.Sleep(200); - - Assert.AreNotEqual(ulong.MinValue, pythonThreadID); + var timeout = Stopwatch.StartNew(); + while (Interlocked.Read(ref pythonThreadID) == 0) + { + Assert.Less(timeout.Elapsed, TimeSpan.FromSeconds(5), "thread ID was not assigned in time"); + } using (Py.GIL()) { - int interruptReturnValue = PythonEngine.Interrupt(pythonThreadID); + int interruptReturnValue = PythonEngine.Interrupt((ulong)Interlocked.Read(ref pythonThreadID)); Assert.AreEqual(1, interruptReturnValue); } - Thread.Sleep(300); + Assert.IsTrue(asyncCall.Wait(TimeSpan.FromSeconds(5)), "Async thread was not interrupted in time"); - Assert.AreEqual(-1, runSimpleStringReturnValue); + Assert.AreEqual(-1, asyncCall.Result); } } }