Debian Codegraph @

tests/test_kernel.py

raw ◀ ▶
Source reconstructed at patch state 0 of 2 — not the installed (fully patched) source.
2 Debian patches touch this file
1 """test the IPython Kernel"""
2
3 # Copyright (c) IPython Development Team.
4 # Distributed under the terms of the Modified BSD License.
5
6 import ast
7 import os.path
8 import platform
9 import signal
10 import subprocess
11 import sys
12 import time
13 from datetime import datetime, timedelta
14 from subprocess import Popen
15 from tempfile import TemporaryDirectory
16
17 import IPython
18 import psutil
19 import pytest
20 from IPython.paths import locate_profile
21
22 from .utils import (
23 TIMEOUT,
24 assemble_output,
25 execute,
26 flush_channels,
27 get_reply,
28 kernel,
29 new_kernel,
30 wait_for_idle,
31 )
32
33
34 def _check_master(kc, expected=True, stream="stdout"):
35 execute(kc=kc, code="import sys")
36 flush_channels(kc)
37 _msg_id, _content = execute(kc=kc, code="print(sys.%s._is_master_process())" % stream)
38 stdout, _stderr = assemble_output(kc.get_iopub_msg)
39 assert stdout.strip() == repr(expected)
40
41
42 def _check_status(content):
43 """If status=error, show the traceback"""
44 if content["status"] == "error":
45 raise AssertionError("".join(["\n"] + content["traceback"]))
46
47
48 # printing tests
49
50
51 def test_simple_print():
52 """simple print statement in kernel"""
53 with kernel() as kc:
54 _msg_id, _content = execute(kc=kc, code="print('hi')")
55 stdout, stderr = assemble_output(kc.get_iopub_msg)
56 assert stdout == "hi\n"
57 assert stderr == ""
58 _check_master(kc, expected=True)
59
60
61 def collect_outputs(get_iopub_msg, parent_msg_id, timeout=5):
62 """Collect outputs until we get an idle message
63
64 Returns list of complete output messages.
65 """
66 while True:
67 msg = get_iopub_msg(timeout=timeout)
68 msg_type = msg["msg_type"]
69 content = msg["content"]
70
71 if (
72 msg["parent_header"]["msg_id"] == parent_msg_id
73 and msg_type == "status"
74 and content["execution_state"] == "idle"
75 ):
76 # idle message signals end of output
77 break
78 elif msg["msg_type"] in {"stream", "display_data"}:
79 yield msg
80 elif msg["msg_type"] == "error":
81 tb = "\n".join(msg["content"]["traceback"])
82 raise RuntimeError(f"Error during execution: {tb}")
83 else:
84 # other output, ignored
85 print(msg["msg_type"])
86
87
88 @pytest.mark.parametrize("explicit_parent", [True, False])
89 def test_print_to_correct_cell_from_thread(explicit_parent: bool):
90 """should print to the current cell unless
91
92 get_ipython().set_parent sets the thread-local value,
93 which supersedes the default.
94
95 """
96 code = f"""\
97 from threading import Event, Thread
98 from time import sleep
99 from IPython.display import display
100
101 explicit_parent = {explicit_parent}
102 parent = get_ipython().get_parent()
103
104 cell_start_event = Event()
105 cell_end_event = Event()
106
107 def thread_target():
108 if explicit_parent:
109 get_ipython().set_parent(parent)
110
111 print("before", flush=True)
112 display(1)
113 cell_start_event.wait(timeout=10)
114 cell_start_event.clear()
115
116 print("during", flush=True)
117 display(2)
118 cell_end_event.set()
119 cell_start_event.wait(timeout=10)
120 cell_start_event.clear()
121 print("after", flush=True)
122 display(3)
123
124 thread = Thread(target=thread_target)
125 thread.start()
126 """
127 outputs = {}
128
129 def add_output(msg):
130 parent_id = msg["parent_header"]["msg_id"]
131 if parent_id not in outputs:
132 outputs[parent_id] = {
133 "stdout": "",
134 "stderr": "",
135 "display_data": [],
136 }
137 cell_outputs = outputs[parent_id]
138 msg_type = msg["header"]["msg_type"]
139 content = msg["content"]
140 if msg_type == "stream":
141 cell_outputs[content["name"]] += content["text"]
142 else:
143 cell_outputs[msg_type].append(msg["content"]["data"]["text/plain"])
144
145 with kernel() as kc:
146 thread_msg_id = kc.execute(code)
147 for msg in collect_outputs(kc.get_iopub_msg, thread_msg_id):
148 add_output(msg)
149
150 next_cell_msg_id = kc.execute("cell_start_event.set()\ncell_end_event.wait(timeout=10)")
151 for msg in collect_outputs(kc.get_iopub_msg, next_cell_msg_id):
152 add_output(msg)
153
154 last_cell_msg_id = kc.execute("cell_start_event.set()\nthread.join()")
155 for msg in collect_outputs(kc.get_iopub_msg, last_cell_msg_id):
156 add_output(msg)
157 print(outputs)
158 if explicit_parent:
159 # assert next_cell_msg_id not in outputs
160 # assert last_cell_msg_id not in outputs
161 thread_cell_output = outputs[thread_msg_id]
162 assert thread_cell_output["stdout"] == "before\nduring\nafter\n"
163 assert thread_cell_output["display_data"] == ["1", "2", "3"]
164 else:
165 thread_cell_output = outputs[thread_msg_id]
166 assert thread_cell_output["stdout"] == "before\n"
167 assert thread_cell_output["display_data"] == ["1"]
168 next_cell_output = outputs[next_cell_msg_id]
169 assert next_cell_output["stdout"] == "during\n"
170 assert next_cell_output["display_data"] == ["2"]
171 last_cell_output = outputs[last_cell_msg_id]
172 assert last_cell_output["stdout"] == "after\n"
173 assert last_cell_output["display_data"] == ["3"]
174
175
176 def test_print_to_correct_cell_from_child_thread():
177 """should print to the cell that spawned the thread, not a subsequently run cell"""
178 iterations = 5
179 interval = 0.25
180 code = f"""\
181 from threading import Thread
182 from time import sleep
183
184 parent = get_ipython().get_parent()
185
186 def child_target():
187 get_ipython().set_parent(parent)
188 for i in range({iterations}):
189 print(i, end='', flush=True)
190 sleep({interval})
191
192 def parent_target():
193 sleep({interval})
194 thread = Thread(target=child_target)
195 thread.start()
196 thread.join()
197
198 Thread(target=parent_target).start()
199 """
200 with kernel() as kc:
201 thread_msg_id = kc.execute(code)
202 _ = kc.execute("pass")
203
204 received = 0
205 while received < iterations:
206 msg = kc.get_iopub_msg(timeout=interval * 2)
207 if msg["msg_type"] != "stream":
208 continue
209 content = msg["content"]
210 assert content["name"] == "stdout"
211 assert content["text"] == str(received)
212 # this is crucial as the parent header decides to which cell the output goes
213 assert msg["parent_header"]["msg_id"] == thread_msg_id
214 received += 1
215
216
217 def test_print_to_correct_cell_from_asyncio():
218 """should print to the cell that scheduled the task, not a subsequently run cell"""
219 iterations = 5
220 interval = 0.25
221 code = f"""\
222 import asyncio
223
224 async def async_task():
225 for i in range({iterations}):
226 print(i, end='', flush=True)
227 await asyncio.sleep({interval})
228
229 loop = asyncio.get_event_loop()
230 loop.create_task(async_task());
231 """
232 with kernel() as kc:
233 thread_msg_id = kc.execute(code)
234 _ = kc.execute("pass")
235
236 received = 0
237 while received < iterations:
238 msg = kc.get_iopub_msg(timeout=interval * 2)
239 if msg["msg_type"] != "stream":
240 continue
241 content = msg["content"]
242 assert content["name"] == "stdout"
243 assert content["text"] == str(received)
244 # this is crucial as the parent header decides to which cell the output goes
245 assert msg["parent_header"]["msg_id"] == thread_msg_id
246 received += 1
247
248
249 @pytest.mark.skip(reason="Currently don't capture during test as pytest does its own capturing")
250 def test_capture_fd():
251 """simple print statement in kernel"""
252 with kernel() as kc:
253 iopub = kc.iopub_channel
254 _msg_id, _content = execute(kc=kc, code="import os; os.system('echo capsys')")
255 stdout, stderr = assemble_output(iopub)
256 assert stdout == "capsys\n"
257 assert stderr == ""
258 _check_master(kc, expected=True)
259
260
261 @pytest.mark.skip(reason="Currently don't capture during test as pytest does its own capturing")
262 def test_subprocess_peek_at_stream_fileno():
263 with kernel() as kc:
264 iopub = kc.iopub_channel
265 _msg_id, _content = execute(
266 kc=kc,
267 code="import subprocess, sys; subprocess.run(['python', '-c', 'import os; os.system(\"echo CAP1\"); print(\"CAP2\")'], stderr=sys.stderr)",
268 )
269 stdout, stderr = assemble_output(iopub)
270 assert stdout == "CAP1\nCAP2\n"
271 assert stderr == ""
272 _check_master(kc, expected=True)
273
274
275 def test_sys_path():
276 """test that sys.path doesn't get messed up by default"""
277 with kernel() as kc:
278 _msg_id, _content = execute(kc=kc, code="import sys; print(repr(sys.path))")
279 stdout, stderr = assemble_output(kc.get_iopub_msg)
280 # for error-output on failure
281 sys.stderr.write(stderr)
282
283 sys_path = ast.literal_eval(stdout.strip())
284 assert "" in sys_path
285
286
287 def test_sys_path_profile_dir():
288 """test that sys.path doesn't get messed up when `--profile-dir` is specified"""
289
290 with new_kernel(["--profile-dir", locate_profile("default")]) as kc:
291 _msg_id, _content = execute(kc=kc, code="import sys; print(repr(sys.path))")
292 stdout, stderr = assemble_output(kc.get_iopub_msg)
293 # for error-output on failure
294 sys.stderr.write(stderr)
295
296 sys_path = ast.literal_eval(stdout.strip())
297 assert "" in sys_path
298
299
300 # the subprocess print tests fail in pytest,
301 # but manual tests in notebooks work fine...
302
303
304 @pytest.mark.flaky(max_runs=3)
305 @pytest.mark.skipif(
306 sys.platform in {"win32", "darwin"} or sys.version_info >= (3, 14),
307 reason="test doesn't reliably reproduce subprocess output capture",
308 )
309 def test_subprocess_print():
310 """printing from forked mp.Process"""
311 with new_kernel() as kc:
312 _check_master(kc, expected=True)
313 flush_channels(kc)
314 np = 5
315 code = "\n".join(
316 [
317 "import time",
318 "import multiprocessing as mp",
319 "pool = [mp.Process(target=print, args=('hello', i,)) for i in range(%i)]" % np,
320 "for p in pool: p.start()",
321 "for p in pool: p.join()",
322 "time.sleep(0.5),",
323 ]
324 )
325
326 _msg_id, _content = execute(kc=kc, code=code)
327 stdout, stderr = assemble_output(kc.get_iopub_msg)
328 assert stdout.count("hello") == np, stdout
329 for n in range(np):
330 assert stdout.count(str(n)) == 1, stdout
331 assert stderr == ""
332 _check_master(kc, expected=True)
333 _check_master(kc, expected=True, stream="stderr")
334
335
336 @pytest.mark.flaky(max_runs=3)
337 def test_subprocess_noprint():
338 """mp.Process without print doesn't trigger iostream mp_mode"""
339 with kernel() as kc:
340 np = 5
341 code = "\n".join(
342 [
343 "import multiprocessing as mp",
344 "pool = [mp.Process(target=range, args=(i,)) for i in range(%i)]" % np,
345 "for p in pool: p.start()",
346 "for p in pool: p.join()",
347 ]
348 )
349
350 _msg_id, _content = execute(kc=kc, code=code)
351 stdout, stderr = assemble_output(kc.get_iopub_msg)
352 assert stdout == ""
353 assert stderr == ""
354
355 _check_master(kc, expected=True)
356 _check_master(kc, expected=True, stream="stderr")
357
358
359 @pytest.mark.flaky(max_runs=3)
360 @pytest.mark.skipif(
361 sys.platform in {"win32", "darwin"} or sys.version_info >= (3, 14),
362 reason="test doesn't reliably reproduce subprocess output capture",
363 )
364 def test_subprocess_error():
365 """error in mp.Process doesn't crash"""
366 with new_kernel() as kc:
367 code = "\n".join(
368 [
369 "import multiprocessing as mp",
370 "p = mp.Process(target=int, args=('hi',))",
371 "p.start()",
372 "p.join()",
373 ]
374 )
375
376 _msg_id, _content = execute(kc=kc, code=code)
377 stdout, stderr = assemble_output(kc.get_iopub_msg)
378 assert stdout == ""
379 assert "ValueError" in stderr
380
381 _check_master(kc, expected=True)
382 _check_master(kc, expected=True, stream="stderr")
383
384
385 # raw_input tests
386
387
388 def test_raw_input():
389 """test input"""
390 with kernel() as kc:
391 input_f = "input"
392 theprompt = "prompt> "
393 code = f'print({input_f}("{theprompt}"))'
394 kc.execute(code, allow_stdin=True)
395 msg = kc.get_stdin_msg(timeout=TIMEOUT)
396 assert msg["header"]["msg_type"] == "input_request"
397 content = msg["content"]
398 assert content["prompt"] == theprompt
399 text = "some text"
400 kc.input(text)
401 reply = kc.get_shell_msg(timeout=TIMEOUT)
402 assert reply["content"]["status"] == "ok"
403 stdout, _stderr = assemble_output(kc.get_iopub_msg)
404 assert stdout == text + "\n"
405
406
407 def test_save_history():
408 # Saving history from the kernel with %hist -f was failing because of
409 # unicode problems on Python 2.
410 with kernel() as kc, TemporaryDirectory() as td:
411 file = os.path.join(td, "hist.out")
412 execute("a=1", kc=kc)
413 wait_for_idle(kc)
414 execute('b="abcþ"', kc=kc)
415 wait_for_idle(kc)
416 _, reply = execute("%hist -f " + file, kc=kc)
417 assert reply["status"] == "ok"
418 with open(file, encoding="utf-8") as f:
419 content = f.read()
420 assert "a=1" in content
421 assert 'b="abcþ"' in content
422
423
424 def test_smoke_faulthandler():
425 pytest.importorskip("faulthandler", reason="this test needs faulthandler")
426 with kernel() as kc:
427 # Note: faulthandler.register is not available on windows.
428 code = "\n".join(
429 [
430 "import sys",
431 "import faulthandler",
432 "import signal",
433 "faulthandler.enable()",
434 'if not sys.platform.startswith("win32"):',
435 " faulthandler.register(signal.SIGTERM)",
436 ]
437 )
438 _, reply = execute(code, kc=kc)
439 assert reply["status"] == "ok", reply.get("traceback", "")
440
441
442 def test_help_output():
443 """ipython kernel --help-all works"""
444 cmd = [sys.executable, "-m", "IPython", "kernel", "--help-all"]
445 proc = subprocess.run(cmd, timeout=30, capture_output=True, check=True)
446 assert proc.returncode == 0, proc.stderr
447 assert b"Traceback" not in proc.stderr
448 assert b"Options" in proc.stdout
449 assert b"Class" in proc.stdout
450
451
452 def test_is_complete():
453 with kernel() as kc:
454 # There are more test cases for this in core - here we just check
455 # that the kernel exposes the interface correctly.
456 kc.is_complete("2+2")
457 reply = kc.get_shell_msg(timeout=TIMEOUT)
458 assert reply["content"]["status"] == "complete"
459
460 # SyntaxError
461 kc.is_complete("raise = 2")
462 reply = kc.get_shell_msg(timeout=TIMEOUT)
463 assert reply["content"]["status"] == "invalid"
464
465 kc.is_complete("a = [1,\n2,")
466 reply = kc.get_shell_msg(timeout=TIMEOUT)
467 assert reply["content"]["status"] == "incomplete"
468 assert reply["content"]["indent"] == ""
469
470 # Cell magic ends on two blank lines for console UIs
471 kc.is_complete("%%timeit\na\n\n")
472 reply = kc.get_shell_msg(timeout=TIMEOUT)
473 assert reply["content"]["status"] == "complete"
474
475
476 @pytest.mark.skipif(sys.platform != "win32", reason="only run on Windows")
477 def test_complete():
478 with kernel() as kc:
479 execute("a = 1", kc=kc)
480 wait_for_idle(kc)
481 cell = "import IPython\nb = a."
482 kc.complete(cell)
483 reply = kc.get_shell_msg(timeout=TIMEOUT)
484
485 c = reply["content"]
486 assert c["status"] == "ok"
487 start = cell.find("a.")
488 end = start + 2
489 assert c["cursor_end"] == cell.find("a.") + 2
490 assert c["cursor_start"] <= end
491
492 # there are many right answers for cursor_start,
493 # so verify application of the completion
494 # rather than the value of cursor_start
495
496 matches = c["matches"]
497 assert matches
498 for m in matches:
499 completed = cell[: c["cursor_start"]] + m
500 assert completed.startswith(cell)
501
502
503 def test_matplotlib_inline_on_import():
504 pytest.importorskip("matplotlib", reason="this test requires matplotlib")
505 with kernel() as kc:
506 cell = "\n".join(
507 ["import matplotlib, matplotlib.pyplot as plt", "backend = matplotlib.get_backend()"]
508 )
509 _, reply = execute(cell, user_expressions={"backend": "backend"}, kc=kc)
510 _check_status(reply)
511 backend_bundle = reply["user_expressions"]["backend"]
512 _check_status(backend_bundle)
513 assert "backend_inline" in backend_bundle["data"]["text/plain"]
514
515
516 def test_message_order():
517 N = 100 # number of messages to test
518 with kernel() as kc:
519 _, reply = execute("a = 1", kc=kc)
520 _check_status(reply)
521 offset = reply["execution_count"] + 1
522 cell = "a += 1\na"
523 msg_ids = []
524 # submit N executions as fast as we can
525 for _ in range(N):
526 msg_ids.append(kc.execute(cell))
527 # check message-handling order
528 for i, msg_id in enumerate(msg_ids, offset):
529 reply = kc.get_shell_msg(timeout=TIMEOUT)
530 _check_status(reply["content"])
531 assert reply["content"]["execution_count"] == i
532 assert reply["parent_header"]["msg_id"] == msg_id
533
534
535 @pytest.mark.skipif(
536 sys.platform.startswith("linux") or sys.platform.startswith("darwin"),
537 reason="test only on windows",
538 )
539 def test_unc_paths():
540 with kernel() as kc, TemporaryDirectory() as td:
541 drive_file_path = os.path.join(td, "unc.txt")
542 with open(drive_file_path, "w+") as f:
543 f.write("# UNC test")
544 unc_root = "\\\\localhost\\C$"
545 file_path = os.path.splitdrive(os.path.dirname(drive_file_path))[1]
546 unc_file_path = os.path.join(unc_root, file_path[1:])
547
548 kc.execute(f"cd {unc_file_path:s}")
549 reply = kc.get_shell_msg(timeout=TIMEOUT)
550 assert reply["content"]["status"] == "ok"
551 out, _err = assemble_output(kc.get_iopub_msg)
552 assert unc_file_path in out
553
554 flush_channels(kc)
555 kc.execute(code="ls")
556 reply = kc.get_shell_msg(timeout=TIMEOUT)
557 assert reply["content"]["status"] == "ok"
558 out, _err = assemble_output(kc.get_iopub_msg)
559 assert "unc.txt" in out
560
561 kc.execute(code="cd")
562 reply = kc.get_shell_msg(timeout=TIMEOUT)
563 assert reply["content"]["status"] == "ok"
564
565
566 @pytest.mark.skipif(
567 platform.python_implementation() == "PyPy",
568 reason="does not work on PyPy",
569 )
570 def test_shutdown():
571 """Kernel exits after polite shutdown_request"""
572 with new_kernel() as kc:
573 km = kc.parent
574 execute("a = 1", kc=kc)
575 wait_for_idle(kc)
576 kc.shutdown()
577 for _ in range(300): # 30s timeout
578 if km.is_alive():
579 time.sleep(0.1)
580 else:
581 break
582 assert not km.is_alive()
583
584
585 def test_interrupt_during_input():
586 """
587 The kernel exits after being interrupted while waiting in input().
588
589 input() appears to have issues other functions don't, and it needs to be
590 interruptible in order for pdb to be interruptible.
591 """
592 with new_kernel() as kc:
593 km = kc.parent
594 msg_id = kc.execute("input()")
595 time.sleep(1) # Make sure it's actually waiting for input.
596 km.interrupt_kernel()
597 from .test_message_spec import validate_message
598
599 # If we failed to interrupt interrupt, this will timeout:
600 reply = get_reply(kc, msg_id, TIMEOUT)
601 validate_message(reply, "execute_reply", msg_id)
602
603
604 @pytest.mark.skipif(os.name == "nt", reason="Message based interrupt not supported on Windows")
605 def test_interrupt_with_message():
606 with new_kernel() as kc:
607 km = kc.parent
608 km.kernel_spec.interrupt_mode = "message"
609 msg_id = kc.execute("input()")
610 time.sleep(1) # Make sure it's actually waiting for input.
611 km.interrupt_kernel()
612 from .test_message_spec import validate_message
613
614 # If we failed to interrupt interrupt, this will timeout:
615 reply = get_reply(kc, msg_id, TIMEOUT)
616 validate_message(reply, "execute_reply", msg_id)
617
618
619 @pytest.mark.skipif(
620 "__pypy__" in sys.builtin_module_names,
621 reason="fails on pypy",
622 )
623 def test_interrupt_during_pdb_set_trace():
624 """
625 The kernel exits after being interrupted while waiting in pdb.set_trace().
626
627 Merely testing input() isn't enough, pdb has its own issues that need
628 to be handled in addition.
629
630 This test will fail with versions of IPython < 7.14.0.
631 """
632 with new_kernel() as kc:
633 km = kc.parent
634 msg_id = kc.execute("import pdb; pdb.set_trace()")
635 msg_id2 = kc.execute("3 + 4")
636 time.sleep(1) # Make sure it's actually waiting for input.
637 km.interrupt_kernel()
638 from .test_message_spec import validate_message
639
640 # If we failed to interrupt interrupt, this will timeout:
641 reply = get_reply(kc, msg_id, TIMEOUT)
642 validate_message(reply, "execute_reply", msg_id)
643 # If we failed to interrupt interrupt, this will timeout:
644 reply = get_reply(kc, msg_id2, TIMEOUT)
645 validate_message(reply, "execute_reply", msg_id2)
646
647
648 def test_control_thread_priority():
649 N = 5
650 with new_kernel() as kc:
651 msg_id = kc.execute("pass")
652 get_reply(kc, msg_id)
653
654 sleep_msg_id = kc.execute("import asyncio; await asyncio.sleep(2)")
655
656 # submit N shell messages
657 shell_msg_ids = []
658 for i in range(N):
659 shell_msg_ids.append(kc.execute(f"i = {i}"))
660
661 # ensure all shell messages have arrived at the kernel before any control messages
662 time.sleep(0.5)
663 # at this point, shell messages should be waiting in msg_queue,
664 # rather than zmq while the kernel is still in the middle of processing
665 # the first execution
666
667 # now send N control messages
668 control_msg_ids = []
669 for _ in range(N):
670 msg = kc.session.msg("kernel_info_request", {})
671 kc.control_channel.send(msg)
672 control_msg_ids.append(msg["header"]["msg_id"])
673
674 # finally, collect the replies on both channels for comparison
675 get_reply(kc, sleep_msg_id)
676 shell_replies = []
677 for msg_id in shell_msg_ids:
678 shell_replies.append(get_reply(kc, msg_id))
679
680 control_replies = []
681 for msg_id in control_msg_ids:
682 control_replies.append(get_reply(kc, msg_id, channel="control"))
683
684 # verify that all control messages were handled before all shell messages
685 shell_dates = [msg["header"]["date"] for msg in shell_replies]
686 control_dates = [msg["header"]["date"] for msg in control_replies]
687 # comparing first to last ought to be enough, since queues preserve order
688 # use <= in case of very-fast handling and/or low resolution timers
689 assert control_dates[-1] <= shell_dates[0]
690
691
692 def test_sequential_control_messages():
693 with new_kernel() as kc:
694 msg_id = kc.execute("import time")
695 get_reply(kc, msg_id)
696
697 # Send multiple messages on the control channel.
698 # Using execute messages to vary duration.
699 sleeps = [0.6, 0.3, 0.1]
700
701 # Prepare messages
702 msgs = [
703 kc.session.msg("execute_request", {"code": f"time.sleep({sleep})"}) for sleep in sleeps
704 ]
705 msg_ids = [msg["header"]["msg_id"] for msg in msgs]
706
707 # Submit messages
708 for msg in msgs:
709 kc.control_channel.send(msg)
710
711 # Get replies
712 replies = [get_reply(kc, msg_id, channel="control") for msg_id in msg_ids]
713
714 def ensure_datetime(arg):
715 # Support arg which is a datetime or str.
716 if isinstance(arg, str):
717 if sys.version_info[:2] < (3, 11) and arg.endswith("Z"):
718 # Python < 3.11 doesn't support "Z" suffix in datetime.fromisoformat,
719 # so use alternative timezone format.
720 # https://github.com/python/cpython/issues/80010
721 arg = arg[:-1] + "+00:00"
722 return datetime.fromisoformat(arg)
723 return arg
724
725 # Check messages are processed in order, one at a time, and of a sensible duration.
726 previous_end = None
727 for reply, sleep in zip(replies, sleeps, strict=False):
728 start = ensure_datetime(reply["metadata"]["started"])
729 end = ensure_datetime(reply["header"]["date"])
730
731 if previous_end is not None:
732 assert start >= previous_end
733 previous_end = end
734
735 assert end >= start + timedelta(seconds=sleep)
736
737
738 def _child():
739 print("in child", os.getpid())
740
741 def _print_and_exit(sig, frame):
742 print(f"Received signal {sig}")
743 # take some time so retries are triggered
744 time.sleep(0.5)
745 sys.exit(-sig)
746
747 signal.signal(signal.SIGTERM, _print_and_exit)
748 time.sleep(30)
749
750
751 def _start_children():
752 ip = IPython.get_ipython() # type:ignore[attr-defined]
753 ns = ip.user_ns
754
755 cmd = [sys.executable, "-c", f"from {__name__} import _child; _child()"]
756 child_pg = Popen(cmd, start_new_session=False)
757 child_newpg = Popen(cmd, start_new_session=True)
758 ns["pid"] = os.getpid()
759 ns["child_pg"] = child_pg.pid
760 ns["child_newpg"] = child_newpg.pid
761 # give them time to start up and register signal handlers
762 time.sleep(1)
763
764
765 @pytest.mark.skipif(
766 platform.python_implementation() == "PyPy",
767 reason="does not work on PyPy",
768 )
769 @pytest.mark.skipif(
770 sys.platform.lower() == "linux",
771 reason="Stalls on linux",
772 )
773 def test_shutdown_subprocesses():
774 """Kernel exits after polite shutdown_request"""
775 with new_kernel() as kc:
776 km = kc.parent
777 _msg_id, reply = execute(
778 f"from {__name__} import _start_children\n_start_children()",
779 kc=kc,
780 user_expressions={
781 "pid": "pid",
782 "child_pg": "child_pg",
783 "child_newpg": "child_newpg",
784 },
785 )
786 print(reply)
787 expressions = reply["user_expressions"]
788 kernel_process = psutil.Process(int(expressions["pid"]["data"]["text/plain"]))
789 child_pg = psutil.Process(int(expressions["child_pg"]["data"]["text/plain"]))
790 child_newpg = psutil.Process(int(expressions["child_newpg"]["data"]["text/plain"]))
791 wait_for_idle(kc)
792
793 kc.shutdown()
794 for _ in range(300): # 30s timeout
795 if km.is_alive():
796 time.sleep(0.1)
797 else:
798 break
799 assert not km.is_alive()
800 assert not kernel_process.is_running()
801 # child in the process group shut down
802 assert not child_pg.is_running()
803 # child outside the process group was not shut down (unix only)
804 if os.name != "nt":
805 assert child_newpg.is_running()
806 try:
807 child_newpg.terminate()
808 except psutil.NoSuchProcess:
809 pass
810
811
812 def test_parent_header_and_ident():
813 # Kernel._parent_ident is private but kept for backward compatibility,
814 # see https://github.com/jupyterlab/jupyterlab/issues/17785
815 with kernel() as kc:
816 # get_parent('shell')
817 msg_id, _ = execute(
818 kc=kc,
819 code="k=get_ipython().kernel; p=k.get_parent('shell'); print(p['header']['msg_id'], p['header']['session'])",
820 )
821 stdout, _ = assemble_output(kc.get_iopub_msg, parent_msg_id=msg_id)
822 check_msg_id, session = stdout.split()
823 assert check_msg_id == msg_id
824 assert check_msg_id.startswith(msg_id)
825
826 # _parent_ident['shell']
827 msg_id, _ = execute(kc=kc, code="print(k._parent_ident['shell'])")
828 stdout, _ = assemble_output(kc.get_iopub_msg, parent_msg_id=msg_id)
829 assert stdout == f"[b'{session}']\n"
830
831 # Send a control message
832 msg = kc.session.msg("kernel_info_request")
833 kc.control_channel.send(msg)
834 control_msg_id = msg["header"]["msg_id"]
835 assemble_output(kc.get_iopub_msg, parent_msg_id=control_msg_id)
836
837 # get_parent('control')
838 msg_id, _ = execute(
839 kc=kc,
840 code="p=k.get_parent('control'); print(p['header']['msg_id'], p['header']['session'])",
841 )
842 stdout, _ = assemble_output(kc.get_iopub_msg, parent_msg_id=msg_id)
843 check_msg_id, session = stdout.split()
844 assert check_msg_id == control_msg_id
845 assert check_msg_id.startswith(control_msg_id)
846
847 # _parent_ident['control']
848 msg_id, _ = execute(kc=kc, code="print(k._parent_ident['control'])")
849 stdout, _ = assemble_output(kc.get_iopub_msg, parent_msg_id=msg_id)
850 assert stdout == f"[b'{session}']\n"
851
852
853 def test_context_vars():
854 with new_kernel() as kc:
855 msg_id, _ = execute(
856 kc=kc,
857 code="from contextvars import ContextVar, copy_context\nctxvar = ContextVar('var', default='default')",
858 )
859 stdout, _ = assemble_output(kc.get_iopub_msg, parent_msg_id=msg_id)
860
861 msg_id, _ = execute(
862 kc=kc,
863 code="print(ctxvar.get())",
864 )
865 stdout, _ = assemble_output(kc.get_iopub_msg, parent_msg_id=msg_id)
866 assert stdout.strip() == "default"
867
868 msg_id, _ = execute(
869 kc=kc,
870 code="ctxvar.set('set'); print(ctxvar.get())",
871 )
872 stdout, _ = assemble_output(kc.get_iopub_msg, parent_msg_id=msg_id)
873 assert stdout.strip() == "set"
874
875 msg_id, _ = execute(
876 kc=kc,
877 code="print(ctxvar.get())",
878 )
879 stdout, _ = assemble_output(kc.get_iopub_msg, parent_msg_id=msg_id)
880 assert stdout.strip() == "set"