Debian Codegraph @

tests/test_kernel.py

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