Debian Codegraph @

testing/test_gateway.py

raw symbols ◀ ▶ SCIP
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 """
2 mostly functional tests of gateways.
3 """
4
5 from __future__ import annotations
6
7 import os
8 import pathlib
9 import shutil
10 import signal
11 import sys
12 from textwrap import dedent
13 from typing import Callable
14
15 import pytest
16
17 import execnet
18 from execnet import gateway_base
19 from execnet import gateway_io
20 from execnet.gateway import Gateway
21
22 TESTTIMEOUT = 10.0 # seconds
23 needs_osdup = pytest.mark.skipif("not hasattr(os, 'dup')")
24
25
26 flakytest = pytest.mark.xfail(
27 reason="on some systems this test fails due to timing problems"
28 )
29 skip_win_pypy = pytest.mark.xfail(
30 condition=hasattr(sys, "pypy_version_info") and sys.platform.startswith("win"),
31 reason="failing on Windows on PyPy (#63)",
32 )
33
34
35 class TestBasicGateway:
36 def test_correct_setup(self, gw: Gateway) -> None:
37 assert gw.hasreceiver()
38 assert gw in gw._group
39 assert gw.id in gw._group
40 assert gw.spec
41
42 def test_repr_doesnt_crash(self, gw: Gateway) -> None:
43 assert isinstance(repr(gw), str)
44
45 def test_attribute__name__(self, gw: Gateway) -> None:
46 channel = gw.remote_exec("channel.send(__name__)")
47 name = channel.receive()
48 assert name == "__channelexec__"
49
50 def test_gateway_status_simple(self, gw: Gateway) -> None:
51 status = gw.remote_status()
52 assert status.numexecuting == 0
53
54 def test_exc_info_is_clear_after_gateway_startup(self, gw: Gateway) -> None:
55 ch = gw.remote_exec(
56 """
57 import traceback, sys
58 excinfo = sys.exc_info()
59 if excinfo != (None, None, None):
60 r = traceback.format_exception(*excinfo)
61 else:
62 r = 0
63 channel.send(r)
64 """
65 )
66 res = ch.receive()
67 if res != 0:
68 pytest.fail("remote raised\n%s" % res)
69
70 def test_gateway_status_no_real_channel(self, gw: Gateway) -> None:
71 numchan = gw._channelfactory.channels()
72 gw.remote_status()
73 numchan2 = gw._channelfactory.channels()
74 # note that on CPython this can not really
75 # fail because refcounting leads to immediate
76 # closure of temporary channels
77 assert numchan2 == numchan
78
79 @flakytest
80 def test_gateway_status_busy(self, gw: Gateway) -> None:
81 numchannels = gw.remote_status().numchannels
82 ch1 = gw.remote_exec("channel.send(1); channel.receive()")
83 ch2 = gw.remote_exec("channel.receive()")
84 ch1.receive()
85 status = gw.remote_status()
86 assert status.numexecuting == 2 # number of active execution threads
87 assert status.numchannels == numchannels + 2
88 ch1.send(None)
89 ch2.send(None)
90 ch1.waitclose()
91 ch2.waitclose()
92 for i in range(10):
93 status = gw.remote_status()
94 if status.numexecuting == 0:
95 break
96 else:
97 pytest.fail("did not get correct remote status")
98 # race condition
99 assert status.numchannels <= numchannels
100
101 def test_remote_exec_module(self, tmp_path: pathlib.Path, gw: Gateway) -> None:
102 p = tmp_path / "remotetest.py"
103 p.write_text("channel.send(1)")
104 mod = type(os)("remotetest")
105 mod.__file__ = str(p)
106 channel = gw.remote_exec(mod)
107 name = channel.receive()
108 assert name == 1
109 p.write_text("channel.send(2)")
110 channel = gw.remote_exec(mod)
111 name = channel.receive()
112 assert name == 2
113
114 def test_remote_exec_module_is_removed(
115 self, gw: Gateway, tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch
116 ) -> None:
117 remotetest = tmp_path / "remote.py"
118 remotetest.write_text(
119 dedent(
120 """
121 def remote():
122 return True
123
124 if __name__ == '__channelexec__':
125 for item in channel: # noqa
126 channel.send(eval(item)) # noqa
127
128 """
129 )
130 )
131
132 monkeypatch.syspath_prepend(tmp_path)
133 import remote # type: ignore[import-not-found]
134
135 ch = gw.remote_exec(remote)
136 # simulate sending the code to a remote location that does not have
137 # access to the source
138 shutil.rmtree(tmp_path)
139 ch.send("remote()")
140 try:
141 result = ch.receive()
142 finally:
143 ch.close()
144
145 assert result is True
146
147 def test_remote_exec_module_with_traceback(
148 self,
149 gw: Gateway,
150 tmp_path: pathlib.Path,
151 monkeypatch: pytest.MonkeyPatch,
152 ) -> None:
153 remotetestpy = tmp_path / "remotetest.py"
154 remotetestpy.write_text(
155 dedent(
156 """
157 def run_me(channel=None):
158 raise ValueError('me')
159
160 if __name__ == '__channelexec__':
161 run_me()
162 """
163 )
164 )
165
166 monkeypatch.syspath_prepend(tmp_path)
167 import remotetest # type: ignore[import-not-found]
168
169 ch = gw.remote_exec(remotetest)
170 try:
171 ch.receive()
172 except execnet.gateway_base.RemoteError as e:
173 assert 'remotetest.py", line 3, in run_me' in str(e)
174 assert "ValueError: me" in str(e)
175 finally:
176 ch.close()
177
178 ch = gw.remote_exec(remotetest.run_me)
179 try:
180 ch.receive()
181 except execnet.gateway_base.RemoteError as e:
182 assert 'remotetest.py", line 3, in run_me' in str(e)
183 assert "ValueError: me" in str(e)
184 finally:
185 ch.close()
186
187 def test_correct_setup_no_py(self, gw: Gateway) -> None:
188 channel = gw.remote_exec(
189 """
190 import sys
191 channel.send(list(sys.modules))
192 """
193 )
194 remotemodules = channel.receive()
195 assert isinstance(remotemodules, list)
196 assert "py" not in remotemodules, "py should not be imported on remote side"
197
198 def test_remote_exec_waitclose(self, gw: Gateway) -> None:
199 channel = gw.remote_exec("pass")
200 channel.waitclose(TESTTIMEOUT)
201
202 def test_remote_exec_waitclose_2(self, gw: Gateway) -> None:
203 channel = gw.remote_exec("def gccycle(): pass")
204 channel.waitclose(TESTTIMEOUT)
205
206 def test_remote_exec_waitclose_noarg(self, gw: Gateway) -> None:
207 channel = gw.remote_exec("pass")
208 channel.waitclose()
209
210 def test_remote_exec_error_after_close(self, gw: Gateway) -> None:
211 channel = gw.remote_exec("pass")
212 channel.waitclose(TESTTIMEOUT)
213 pytest.raises(IOError, channel.send, 0)
214
215 def test_remote_exec_no_explicit_close(self, gw: Gateway) -> None:
216 channel = gw.remote_exec("channel.close()")
217 with pytest.raises(channel.RemoteError) as excinfo:
218 channel.waitclose(TESTTIMEOUT)
219 assert "explicit" in excinfo.value.formatted
220
221 def test_remote_exec_channel_anonymous(self, gw: Gateway) -> None:
222 channel = gw.remote_exec(
223 """
224 obj = channel.receive()
225 channel.send(obj)
226 """
227 )
228 channel.send(42)
229 result = channel.receive()
230 assert result == 42
231
232 @needs_osdup
233 def test_confusion_from_os_write_stdout(self, gw: Gateway) -> None:
234 channel = gw.remote_exec(
235 """
236 import os
237 os.write(1, 'confusion!'.encode('ascii'))
238 channel.send(channel.receive() * 6)
239 channel.send(channel.receive() * 6)
240 """
241 )
242 channel.send(3)
243 res = channel.receive()
244 assert res == 18
245 channel.send(7)
246 res = channel.receive()
247 assert res == 42
248
249 @needs_osdup
250 def test_confusion_from_os_write_stderr(self, gw: Gateway) -> None:
251 channel = gw.remote_exec(
252 """
253 import os
254 os.write(2, 'test'.encode('ascii'))
255 channel.send(channel.receive() * 6)
256 channel.send(channel.receive() * 6)
257 """
258 )
259 channel.send(3)
260 res = channel.receive()
261 assert res == 18
262 channel.send(7)
263 res = channel.receive()
264 assert res == 42
265
266 @flakytest
267 def test__rinfo(self, gw: Gateway) -> None:
268 rinfo = gw._rinfo()
269 assert rinfo.executable
270 assert rinfo.cwd
271 assert rinfo.version_info
272 assert repr(rinfo)
273 old = gw.remote_exec(
274 """
275 import os.path
276 cwd = os.getcwd()
277 channel.send(os.path.basename(cwd))
278 os.chdir('..')
279 """
280 ).receive()
281 try:
282 rinfo2 = gw._rinfo()
283 assert rinfo2.cwd == rinfo.cwd
284 rinfo3 = gw._rinfo(update=True)
285 assert rinfo3.cwd != rinfo2.cwd
286 finally:
287 gw._cache_rinfo = rinfo
288 gw.remote_exec("import os ; os.chdir(%r)" % old).waitclose()
289
290
291 class TestPopenGateway:
292 gwtype = "popen"
293
294 def test_chdir_separation(
295 self, tmp_path: pathlib.Path, makegateway: Callable[[str], Gateway]
296 ) -> None:
297 with pytest.MonkeyPatch.context() as mp:
298 mp.chdir(tmp_path)
299 gw = makegateway("popen")
300 c = gw.remote_exec("import os ; channel.send(os.getcwd())")
301 x = c.receive()
302 assert isinstance(x, str)
303 assert x.lower() == str(tmp_path).lower()
304
305 def test_remoteerror_readable_traceback(self, gw: Gateway) -> None:
306 with pytest.raises(gateway_base.RemoteError) as e:
307 gw.remote_exec("x y").waitclose()
308 assert "gateway_base" in e.value.formatted
309
310 def test_many_popen(self, makegateway: Callable[[str], Gateway]) -> None:
311 num = 4
312 l = []
313 for i in range(num):
314 l.append(makegateway("popen"))
315 channels = []
316 for gw in l:
317 channel = gw.remote_exec("""channel.send(42)""")
318 channels.append(channel)
319 while channels:
320 channel = channels.pop()
321 ret = channel.receive()
322 assert ret == 42
323
324 def test_rinfo_popen(self, gw: Gateway) -> None:
325 rinfo = gw._rinfo()
326 assert rinfo.executable == sys.executable
327 assert rinfo.cwd == os.getcwd()
328 assert rinfo.version_info == sys.version_info
329
330 @flakytest
331 def test_waitclose_on_remote_killed(
332 self, makegateway: Callable[[str], Gateway]
333 ) -> None:
334 gw = makegateway("popen")
335 channel = gw.remote_exec(
336 """
337 import os
338 import time
339 channel.send(os.getpid())
340 time.sleep(100)
341 """
342 )
343 remotepid = channel.receive()
344 assert isinstance(remotepid, int)
345 os.kill(remotepid, signal.SIGTERM)
346 with pytest.raises(EOFError):
347 channel.waitclose(TESTTIMEOUT)
348 with pytest.raises(IOError):
349 channel.send(None)
350 with pytest.raises(EOFError):
351 channel.receive()
352
353 def test_receive_on_remote_sysexit(self, gw: Gateway) -> None:
354 channel = gw.remote_exec(
355 """
356 raise SystemExit()
357 """
358 )
359 pytest.raises(channel.RemoteError, channel.receive)
360
361 def test_dont_write_bytecode(self, makegateway: Callable[[str], Gateway]) -> None:
362 check_sys_dont_write_bytecode = """
363 import sys
364 channel.send(sys.dont_write_bytecode)
365 """
366
367 gw = makegateway("popen")
368 channel = gw.remote_exec(check_sys_dont_write_bytecode)
369 ret = channel.receive()
370 assert not ret
371 gw = makegateway("popen//dont_write_bytecode")
372 channel = gw.remote_exec(check_sys_dont_write_bytecode)
373 ret = channel.receive()
374 assert ret
375
376
377 @pytest.mark.skipif("config.option.broken_isp")
378 def test_socket_gw_host_not_found(makegateway: Callable[[str], Gateway]) -> None:
379 with pytest.raises(execnet.HostNotFound):
380 makegateway("socket=qwepoipqwe:9000")
381
382
383 class TestSshPopenGateway:
384 gwtype = "ssh"
385
386 def test_sshconfig_config_parsing(
387 self, monkeypatch: pytest.MonkeyPatch, makegateway: Callable[[str], Gateway]
388 ) -> None:
389 l = []
390 monkeypatch.setattr(
391 gateway_io, "Popen2IOMaster", lambda *args, **kwargs: l.append(args[0])
392 )
393 with pytest.raises(AttributeError):
394 makegateway("ssh=xyz//ssh_config=qwe")
395
396 assert len(l) == 1
397 popen_args = l[0]
398 i = popen_args.index("-F")
399 assert popen_args[i + 1] == "qwe"
400
401 def test_sshaddress(self, gw: Gateway, specssh: execnet.XSpec) -> None:
402 assert gw.remoteaddress == specssh.ssh
403
404 def test_host_not_found(
405 self, gw: Gateway, makegateway: Callable[[str], Gateway]
406 ) -> None:
407 with pytest.raises(execnet.HostNotFound):
408 makegateway("ssh=nowhere.codespeak.net")
409
410
411 class TestThreads:
412 def test_threads(self, makegateway: Callable[[str], Gateway]) -> None:
413 gw = makegateway("popen")
414 gw.remote_init_threads(3)
415 c1 = gw.remote_exec("channel.send(channel.receive())")
416 c2 = gw.remote_exec("channel.send(channel.receive())")
417 c2.send(1)
418 res = c2.receive()
419 assert res == 1
420 c1.send(42)
421 res = c1.receive()
422 assert res == 42
423
424 def test_threads_race_sending(self, makegateway: Callable[[str], Gateway]) -> None:
425 # multiple threads sending data in parallel
426 gw = makegateway("popen")
427 num = 5
428 gw.remote_init_threads(num)
429 print("remote_init_threads(%d)" % num)
430 channels = []
431 for x in range(num):
432 ch = gw.remote_exec(
433 """
434 for x in range(10):
435 channel.send(''*1000)
436 channel.receive()
437 """
438 )
439 channels.append(ch)
440 for ch in channels:
441 for x in range(10):
442 ch.receive(TESTTIMEOUT)
443 ch.send(1)
444 for ch in channels:
445 ch.waitclose(TESTTIMEOUT)
446
447 @flakytest
448 def test_status_with_threads(self, makegateway: Callable[[str], Gateway]) -> None:
449 gw = makegateway("popen")
450 c1 = gw.remote_exec("channel.send(1) ; channel.receive()")
451 c2 = gw.remote_exec("channel.send(2) ; channel.receive()")
452 c1.receive()
453 c2.receive()
454 rstatus = gw.remote_status()
455 assert rstatus.numexecuting == 2
456 c1.send(1)
457 c2.send(1)
458 c1.waitclose()
459 c2.waitclose()
460 # there is a slight chance that an execution thread
461 # is still active although it's accompanying channel
462 # is already closed.
463 for i in range(10):
464 rstatus = gw.remote_status()
465 if rstatus.numexecuting == 0:
466 return
467 assert 0, "numexecuting didn't drop to zero"
468
469
470 class TestTracing:
471 def test_popen_filetracing(
472 self,
473 tmp_path: pathlib.Path,
474 monkeypatch: pytest.MonkeyPatch,
475 makegateway: Callable[[str], Gateway],
476 ) -> None:
477 monkeypatch.setenv("TMP", str(tmp_path))
478 monkeypatch.setenv("TEMP", str(tmp_path)) # windows
479 monkeypatch.setenv("EXECNET_DEBUG", "1")
480 gw = makegateway("popen")
481 # hack out the debuffilename
482 fn = gw.remote_exec(
483 "import execnet;channel.send(execnet.gateway_base.fn)"
484 ).receive()
485 assert isinstance(fn, str)
486 workerfile = pathlib.Path(fn)
487 assert workerfile.exists()
488 worker_line = "creating workergateway"
489 with workerfile.open() as f:
490 for line in f:
491 if worker_line in line:
492 break
493 else:
494 pytest.fail(f"did not find {worker_line!r} in tracefile")
495 gw.exit()
496
497 @skip_win_pypy
498 @flakytest
499 def test_popen_stderr_tracing(
500 self,
501 capfd: pytest.CaptureFixture[str],
502 monkeypatch: pytest.MonkeyPatch,
503 makegateway: Callable[[str], Gateway],
504 ) -> None:
505 monkeypatch.setenv("EXECNET_DEBUG", "2")
506 gw = makegateway("popen")
507 pid = gw.remote_exec("import os ; channel.send(os.getpid())").receive()
508 _out, err = capfd.readouterr()
509 worker_line = "[%s] creating workergateway" % pid
510 assert worker_line in err
511 gw.exit()
512
513 def test_no_tracing_by_default(self):
514 assert gateway_base.trace == gateway_base.notrace, (
515 "trace does not to default to empty tracing"
516 )
517
518
519 @pytest.mark.parametrize(
520 "spec, expected_args",
521 [
522 ("popen//python=python", ["python"]),
523 ("popen//python=sudo -u test python", ["sudo", "-u", "test", "python"]),
524 pytest.param(
525 r"popen//python=/hans\ alt/bin/python",
526 ["/hans alt/bin/python"],
527 marks=pytest.mark.skipif(
528 sys.platform.startswith("win"), reason="invalid spec on Windows"
529 ),
530 ),
531 ('popen//python="/u/test me/python" -e', ["/u/test me/python", "-e"]),
532 ],
533 )
534 def test_popen_args(spec: str, expected_args: list[str]) -> None:
535 expected_args = [*expected_args, "-u", "-c", gateway_io.popen_bootstrapline]
536 args = gateway_io.popen_args(execnet.XSpec(spec))
537 assert args == expected_args
538
539
540 @pytest.mark.parametrize(
541 "interleave_getstatus",
542 [
543 pytest.param(True, id="interleave-remote-status"),
544 pytest.param(
545 False,
546 id="no-interleave-remote-status",
547 marks=pytest.mark.xfail(
548 reason="https://github.com/pytest-dev/execnet/issues/123",
549 ),
550 ),
551 ],
552 )
553 def test_regression_gevent_hangs(
554 group: execnet.Group, interleave_getstatus: bool
555 ) -> None:
556 pytest.importorskip("gevent")
557 gw = group.makegateway("popen//execmodel=gevent")
558
559 print(gw.remote_status())
560
561 def sendback(channel) -> None:
562 channel.send(1234)
563
564 ch = gw.remote_exec(sendback)
565 if interleave_getstatus:
566 print(gw.remote_status())
567 assert ch.receive(timeout=0.5) == 1234
568
569
570 def test_assert_main_thread_only(
571 execmodel: gateway_base.ExecModel, makegateway: Callable[[str], Gateway]
572 ) -> None:
573 if execmodel.backend != "main_thread_only":
574 pytest.skip("can only run with main_thread_only")
575
576 gw = makegateway(f"execmodel={execmodel.backend}//popen")
577
578 try:
579 # Submit multiple remote_exec requests in quick succession and
580 # assert that all tasks execute in the main thread. It is
581 # necessary to call receive on each channel before the next
582 # remote_exec call, since the channel will raise an error if
583 # concurrent remote_exec requests are submitted as in
584 # test_main_thread_only_concurrent_remote_exec_deadlock.
585 for i in range(10):
586 ch = gw.remote_exec(
587 """
588 import time, threading
589 time.sleep(0.02)
590 channel.send(threading.current_thread() is threading.main_thread())
591 """
592 )
593
594 try:
595 res = ch.receive()
596 finally:
597 ch.close()
598 # This doesn't actually block because we closed
599 # the channel already, but it does check for remote
600 # errors and raise them.
601 ch.waitclose()
602 if res is not True:
603 pytest.fail("remote raised\n%s" % res)
604 finally:
605 gw.exit()
606 gw.join()
607
608
609 def test_main_thread_only_concurrent_remote_exec_deadlock(
610 execmodel: gateway_base.ExecModel, makegateway: Callable[[str], Gateway]
611 ) -> None:
612 if execmodel.backend != "main_thread_only":
613 pytest.skip("can only run with main_thread_only")
614
615 gw = makegateway(f"execmodel={execmodel.backend}//popen")
616 channels = []
617 try:
618 # Submit multiple remote_exec requests in quick succession and
619 # assert that MAIN_THREAD_ONLY_DEADLOCK_TEXT is raised if
620 # concurrent remote_exec requests are submitted for the
621 # main_thread_only execmodel (as compensation for the lack of
622 # back pressure in remote_exec calls which do not attempt to
623 # block until the remote main thread is idle).
624 for i in range(2):
625 channels.append(
626 gw.remote_exec(
627 """
628 import threading
629 channel.send(threading.current_thread() is threading.main_thread())
630 # Wait forever, ensuring that the deadlock case triggers.
631 channel.gateway.execmodel.Event().wait()
632 """
633 )
634 )
635
636 expected_results = (
637 True,
638 execnet.gateway_base.MAIN_THREAD_ONLY_DEADLOCK_TEXT,
639 )
640 for expected, ch in zip(expected_results, channels):
641 try:
642 res = ch.receive()
643 except execnet.RemoteError as e:
644 res = e.formatted
645 assert res == expected
646 finally:
647 for ch in channels:
648 ch.close()
649 gw.exit()
650 gw.join()