Debian Codegraph @

tests/inprocess/test_kernel.py

raw
1 # Copyright (c) IPython Development Team.
2 # Distributed under the terms of the Modified BSD License.
3
4 import sys
5 from contextlib import contextmanager
6 from io import StringIO
7
8 import pytest
9 from IPython.utils.io import capture_output # type:ignore[attr-defined]
10 from jupyter_client.session import Session
11
12 from ipykernel.inprocess.blocking import BlockingInProcessKernelClient
13 from ipykernel.inprocess.ipkernel import InProcessKernel
14 from ipykernel.inprocess.manager import InProcessKernelManager
15
16 from ..utils import assemble_output
17
18 orig_msg = Session.msg
19
20
21 def _inject_cell_id(_self, *args, **kwargs):
22 """
23 This patch jupyter_client.session:Session.msg to add a cell_id to the return message metadata
24 """
25 assert isinstance(_self, Session)
26 res = orig_msg(_self, *args, **kwargs)
27 assert "cellId" not in res["metadata"]
28 res["metadata"]["cellId"] = "test_cell_id"
29 return res
30
31
32 @contextmanager
33 def patch_cell_id():
34 try:
35 Session.msg = _inject_cell_id # type:ignore
36 yield
37 finally:
38 Session.msg = orig_msg # type:ignore
39
40
41 @pytest.fixture()
42 def kc():
43 km = InProcessKernelManager()
44 km.start_kernel()
45 kc = km.client()
46 kc.start_channels()
47 kc.wait_for_ready()
48 return kc
49
50
51 def test_with_cell_id(kc):
52 with patch_cell_id():
53 kc.execute("1+1")
54
55
56 def test_pylab(kc):
57 """Does %pylab work in the in-process kernel?"""
58 _ = pytest.importorskip("matplotlib", reason="This test requires matplotlib")
59 kc.execute("%pylab")
60 out, _err = assemble_output(kc.get_iopub_msg)
61 assert "matplotlib" in out
62
63
64 def test_raw_input(kc):
65 """Does the in-process kernel handle raw_input correctly?"""
66 io = StringIO("foobar\n")
67 sys_stdin = sys.stdin
68 sys.stdin = io
69 try:
70 kc.execute("x = input()")
71 finally:
72 sys.stdin = sys_stdin
73 assert kc.kernel.shell.user_ns.get("x") == "foobar"
74
75
76 @pytest.mark.skipif("__pypy__" in sys.builtin_module_names, reason="fails on pypy")
77 def test_stdout(kc):
78 """Does the in-process kernel correctly capture IO?"""
79 kernel = InProcessKernel()
80
81 with capture_output() as io:
82 kernel.shell.run_cell('print("foo")')
83 assert io.stdout == "foo\n"
84
85 kc = BlockingInProcessKernelClient(kernel=kernel, session=kernel.session)
86 kernel.frontends.append(kc)
87 kc.execute('print("bar")')
88 out, _err = assemble_output(kc.get_iopub_msg)
89 assert out == "bar\n"
90
91
92 @pytest.mark.skip(reason="Currently don't capture during test as pytest does its own capturing")
93 def test_capfd(kc):
94 """Does correctly capture fd"""
95 kernel = InProcessKernel()
96
97 with capture_output() as io:
98 kernel.shell.run_cell('print("foo")')
99 assert io.stdout == "foo\n"
100
101 kc = BlockingInProcessKernelClient(kernel=kernel, session=kernel.session)
102 kernel.frontends.append(kc)
103 kc.execute("import os")
104 kc.execute('os.system("echo capfd")')
105 out, _err = assemble_output(kc.iopub_channel)
106 assert out == "capfd\n"
107
108
109 def test_getpass_stream(kc):
110 """Tests that kernel getpass accept the stream parameter"""
111 kernel = InProcessKernel()
112 kernel._allow_stdin = True
113 kernel._input_request = lambda *args, **kwargs: None # type:ignore
114
115 kernel.getpass(stream="non empty")
116
117
118 async def test_do_execute(kc):
119 kernel = InProcessKernel()
120 await kernel.do_execute("a=1", True)
121 assert kernel.shell.user_ns["a"] == 1