Debian Codegraph @

testing/test_termination.py

raw symbols SCIP
1 import os
2 import pathlib
3 import shutil
4 import signal
5 import subprocess
6 import sys
7 from typing import Callable
8
9 import pytest
10 from test_gateway import TESTTIMEOUT
11
12 import execnet
13 from execnet.gateway import Gateway
14 from execnet.gateway_base import ExecModel
15 from execnet.gateway_base import WorkerPool
16
17 execnetdir = pathlib.Path(execnet.__file__).parent.parent
18
19 skip_win_pypy = pytest.mark.xfail(
20 condition=hasattr(sys, "pypy_version_info") and sys.platform.startswith("win"),
21 reason="failing on Windows on PyPy (#63)",
22 )
23
24
25 def test_exit_blocked_worker_execution_gateway(
26 anypython: str, makegateway: Callable[[str], Gateway], pool: WorkerPool
27 ) -> None:
28 gateway = makegateway("popen//python=%s" % anypython)
29 gateway.remote_exec(
30 """
31 import time
32 time.sleep(10.0)
33 """
34 )
35
36 def doit() -> int:
37 gateway.exit()
38 return 17
39
40 reply = pool.spawn(doit)
41 x = reply.get(timeout=5.0)
42 assert x == 17
43
44
45 def test_endmarker_delivery_on_remote_killterm(
46 makegateway: Callable[[str], Gateway], execmodel: ExecModel
47 ) -> None:
48 if execmodel.backend not in ("thread", "main_thread_only"):
49 pytest.xfail("test and execnet not compatible to greenlets yet")
50 gw = makegateway("popen")
51 q = execmodel.queue.Queue()
52 channel = gw.remote_exec(
53 source="""
54 import os, time
55 channel.send(os.getpid())
56 time.sleep(100)
57 """
58 )
59 pid = channel.receive()
60 assert isinstance(pid, int)
61 os.kill(pid, signal.SIGTERM)
62 channel.setcallback(q.put, endmarker=999)
63 val = q.get(TESTTIMEOUT)
64 assert val == 999
65 err = channel._getremoteerror()
66 assert isinstance(err, EOFError)
67
68
69 @skip_win_pypy
70 def test_termination_on_remote_channel_receive(
71 monkeypatch: pytest.MonkeyPatch, makegateway: Callable[[str], Gateway]
72 ) -> None:
73 if not shutil.which("ps"):
74 pytest.skip("need 'ps' command to externally check process status")
75 monkeypatch.setenv("EXECNET_DEBUG", "2")
76 gw = makegateway("popen")
77 pid = gw.remote_exec("import os ; channel.send(os.getpid())").receive()
78 gw.remote_exec("channel.receive()")
79 gw._group.terminate()
80 command = ["ps", "-p", str(pid)]
81 output = subprocess.run(command, capture_output=True, text=True, check=False)
82 assert str(pid) not in output.stdout, output
83
84
85 def test_close_initiating_remote_no_error(
86 pytester: pytest.Pytester, anypython: str
87 ) -> None:
88 p = pytester.makepyfile(
89 """
90 import sys
91 sys.path.insert(0, sys.argv[1])
92 import execnet
93 gw = execnet.makegateway("popen")
94 print ("remote_exec1")
95 ch1 = gw.remote_exec("channel.receive()")
96 print ("remote_exec1")
97 ch2 = gw.remote_exec("channel.receive()")
98 print ("termination")
99 execnet.default_group.terminate()
100 """
101 )
102 popen = subprocess.Popen(
103 [anypython, str(p), str(execnetdir)], stdout=None, stderr=subprocess.PIPE
104 )
105 _out, err = popen.communicate()
106 print(err)
107 errstr = err.decode("utf8")
108 lines = [x for x in errstr.splitlines() if "*sys-package" not in x]
109 assert not lines
110
111
112 def test_terminate_implicit_does_trykill(
113 pytester: pytest.Pytester,
114 anypython: str,
115 capfd: pytest.CaptureFixture[str],
116 pool: WorkerPool,
117 ) -> None:
118 if pool.execmodel.backend not in ("thread", "main_thread_only"):
119 pytest.xfail("only os threading model supported")
120 if sys.version_info >= (3, 12):
121 pytest.xfail(
122 "since python3.12 this test triggers RuntimeError: can't create new thread at interpreter shutdown"
123 )
124 p = pytester.makepyfile(
125 """
126 import sys
127 sys.path.insert(0, %r)
128 import execnet
129 group = execnet.Group()
130 gw = group.makegateway("popen")
131 ch = gw.remote_exec("import time ; channel.send(1) ; time.sleep(100)")
132 ch.receive() # remote execution started
133 sys.stdout.write("1\\n")
134 sys.stdout.flush()
135 sys.stdout.close()
136 class FlushNoOp(object):
137 def flush(self):
138 pass
139 # replace stdout since some python implementations
140 # flush and print errors (for example 3.2)
141 # see Issue #5319 (from the release notes of 3.2 Alpha 2)
142 sys.stdout = FlushNoOp()
143
144 # use process at-exit group.terminate call
145 """
146 % str(execnetdir)
147 )
148 popen = subprocess.Popen([str(anypython), str(p)], stdout=subprocess.PIPE)
149 # sync with start-up
150 assert popen.stdout is not None
151 popen.stdout.readline()
152 reply = pool.spawn(popen.communicate)
153 reply.get(timeout=50)
154 _out, err = capfd.readouterr()
155 lines = [x for x in err.splitlines() if "*sys-package" not in x]
156 assert not lines or "Killed" in err