Skip to content

Commit 83328d2

Browse files
committed
made InterruptTest more robust
should resolve this failure: https://github.com/pythonnet/pythonnet/pull/1392/checks?check_run_id=1944113649 related to #1337
1 parent d0d7616 commit 83328d2

File tree

1 file changed

+13
-12
lines changed

1 file changed

+13
-12
lines changed

src/embed_tests/TestInterrupt.cs

+13-12
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
21
using System;
2+
using System.Diagnostics;
33
using System.Threading;
44
using System.Threading.Tasks;
55

@@ -30,34 +30,35 @@ public void Dispose()
3030
[Test]
3131
public void InterruptTest()
3232
{
33-
int runSimpleStringReturnValue = int.MinValue;
34-
ulong pythonThreadID = ulong.MinValue;
35-
Task.Factory.StartNew(() =>
33+
long pythonThreadID = 0;
34+
var asyncCall = Task.Factory.StartNew(() =>
3635
{
3736
using (Py.GIL())
3837
{
39-
pythonThreadID = PythonEngine.GetPythonThreadID();
40-
runSimpleStringReturnValue = PythonEngine.RunSimpleString(@"
38+
Interlocked.Exchange(ref pythonThreadID, (long)PythonEngine.GetPythonThreadID());
39+
return PythonEngine.RunSimpleString(@"
4140
import time
4241
4342
while True:
4443
time.sleep(0.2)");
4544
}
4645
});
4746

48-
Thread.Sleep(200);
49-
50-
Assert.AreNotEqual(ulong.MinValue, pythonThreadID);
47+
var timeout = Stopwatch.StartNew();
48+
while (Interlocked.Read(ref pythonThreadID) == 0)
49+
{
50+
Assert.Less(timeout.Elapsed, TimeSpan.FromSeconds(5), "thread ID was not assigned in time");
51+
}
5152

5253
using (Py.GIL())
5354
{
54-
int interruptReturnValue = PythonEngine.Interrupt(pythonThreadID);
55+
int interruptReturnValue = PythonEngine.Interrupt((ulong)Interlocked.Read(ref pythonThreadID));
5556
Assert.AreEqual(1, interruptReturnValue);
5657
}
5758

58-
Thread.Sleep(300);
59+
Assert.IsTrue(asyncCall.Wait(TimeSpan.FromSeconds(5)), "Async thread was not interrupted in time");
5960

60-
Assert.AreEqual(-1, runSimpleStringReturnValue);
61+
Assert.AreEqual(-1, asyncCall.Result);
6162
}
6263
}
6364
}

0 commit comments

Comments
 (0)