Debian Codegraph @

tests/test_client.py

raw
1 """Tests for the KernelClient"""
2
3 # Copyright (c) Jupyter Development Team.
4 # Distributed under the terms of the Modified BSD License.
5 import os
6 from threading import Event
7 from unittest import TestCase
8
9 import pytest
10 from IPython.utils.capture import capture_output
11 from traitlets import DottedObjectName, Type
12
13 from jupyter_client.client import validate_string_dict
14 from jupyter_client.kernelspec import KernelSpecManager, NoSuchKernel
15 from jupyter_client.manager import KernelManager, start_new_async_kernel, start_new_kernel
16 from jupyter_client.threaded import ThreadedKernelClient, ThreadedZMQSocketChannel
17
18 TIMEOUT = 60
19
20 pjoin = os.path.join
21
22
23 class TestKernelClient(TestCase):
24 def setUp(self):
25 try:
26 KernelSpecManager().get_kernel_spec("echo")
27 except NoSuchKernel:
28 pytest.skip()
29 self.km, self.kc = start_new_kernel(kernel_name="echo")
30
31 def tearDown(self):
32 self.km.shutdown_kernel()
33 self.kc.stop_channels()
34 return super().tearDown()
35
36 def test_execute_interactive(self):
37 kc = self.kc
38
39 with capture_output() as io:
40 reply = kc.execute_interactive("print('hello')", timeout=TIMEOUT)
41 assert "hello" in io.stdout
42 assert reply["content"]["status"] == "ok"
43
44 def _check_reply(self, reply_type, reply):
45 self.assertIsInstance(reply, dict)
46 self.assertEqual(reply["header"]["msg_type"], reply_type + "_reply")
47 self.assertEqual(reply["parent_header"]["msg_type"], reply_type + "_request")
48
49 def test_history(self):
50 kc = self.kc
51 msg_id = kc.history(session=0)
52 self.assertIsInstance(msg_id, str)
53 # Drain the first reply to avoid race condition
54 kc._recv_reply(msg_id, timeout=TIMEOUT)
55 # Now test the reply=True convenience path
56 reply = kc.history(session=0, reply=True, timeout=TIMEOUT)
57 self._check_reply("history", reply)
58
59 def test_inspect(self):
60 kc = self.kc
61 msg_id = kc.inspect("who cares")
62 self.assertIsInstance(msg_id, str)
63 # Drain the first reply to avoid race condition
64 kc._recv_reply(msg_id, timeout=TIMEOUT)
65 # Now test the reply=True convenience path
66 reply = kc.inspect("code", reply=True, timeout=TIMEOUT)
67 self._check_reply("inspect", reply)
68
69 def test_complete(self):
70 kc = self.kc
71 msg_id = kc.complete("who cares")
72 self.assertIsInstance(msg_id, str)
73 # Drain the first reply to avoid race condition
74 kc._recv_reply(msg_id, timeout=TIMEOUT)
75 # Now test the reply=True convenience path
76 reply = kc.complete("code", reply=True, timeout=TIMEOUT)
77 self._check_reply("complete", reply)
78
79 def test_kernel_info(self):
80 kc = self.kc
81 msg_id = kc.kernel_info()
82 self.assertIsInstance(msg_id, str)
83 # Drain the first reply to avoid race condition
84 kc._recv_reply(msg_id, timeout=TIMEOUT)
85 # Now test the reply=True convenience path
86 reply = kc.kernel_info(reply=True, timeout=TIMEOUT)
87 self._check_reply("kernel_info", reply)
88
89 def test_comm_info(self):
90 kc = self.kc
91 msg_id = kc.comm_info()
92 self.assertIsInstance(msg_id, str)
93 # Drain the first reply to avoid race condition
94 kc._recv_reply(msg_id, timeout=TIMEOUT)
95 # Now test the reply=True convenience path
96 reply = kc.comm_info(reply=True, timeout=TIMEOUT)
97 self._check_reply("comm_info", reply)
98
99 def test_shutdown(self):
100 kc = self.kc
101 reply = kc.shutdown(reply=True, timeout=TIMEOUT)
102 self._check_reply("shutdown", reply)
103
104 def test_shutdown_id(self):
105 kc = self.kc
106 msg_id = kc.shutdown()
107 self.assertIsInstance(msg_id, str)
108
109
110 @pytest.fixture
111 def kc(jp_asyncio_loop):
112 try:
113 KernelSpecManager().get_kernel_spec("echo")
114 except NoSuchKernel:
115 pytest.skip()
116
117 async def start():
118 return await start_new_async_kernel(kernel_name="echo")
119
120 km, kc = jp_asyncio_loop.run_until_complete(start())
121 yield kc
122
123 async def stop():
124 await km.shutdown_kernel()
125
126 jp_asyncio_loop.run_until_complete(stop())
127 kc.stop_channels()
128
129
130 class TestAsyncKernelClient:
131 async def test_execute_interactive(self, kc):
132 reply = await kc.execute_interactive("hello", timeout=TIMEOUT)
133 assert reply["content"]["status"] == "ok"
134
135 def _check_reply(self, reply_type, reply):
136 assert isinstance(reply, dict)
137 assert reply["header"]["msg_type"] == reply_type + "_reply"
138 assert reply["parent_header"]["msg_type"] == reply_type + "_request"
139
140 async def test_input_request(self, kc):
141 def handle_stdin(msg):
142 kc.input("test")
143
144 reply = await kc.execute_interactive(
145 "a = input()",
146 stdin_hook=handle_stdin,
147 timeout=TIMEOUT,
148 )
149 assert reply["content"]["status"] == "ok"
150
151 async def test_output_hook(self, kc):
152 called = False
153
154 def output_hook(msg):
155 nonlocal called
156 if msg["header"]["msg_type"] == "stream":
157 called = True
158
159 reply = await kc.execute_interactive(
160 "print('hello')", timeout=TIMEOUT, output_hook=output_hook
161 )
162 assert reply["content"]["status"] == "ok"
163 assert called
164
165 async def test_history(self, kc):
166 msg_id = kc.history(session=0)
167 assert isinstance(msg_id, str)
168 # Drain the first reply to avoid race condition
169 await kc._async_recv_reply(msg_id, timeout=TIMEOUT)
170 # Now test the reply=True convenience path
171 reply = await kc.history(session=0, reply=True, timeout=TIMEOUT)
172 self._check_reply("history", reply)
173
174 async def test_inspect(self, kc):
175 msg_id = kc.inspect("who cares")
176 assert isinstance(msg_id, str)
177 # Drain the first reply to avoid race condition
178 await kc._async_recv_reply(msg_id, timeout=TIMEOUT)
179 # Now test the reply=True convenience path
180 reply = await kc.inspect("code", reply=True, timeout=TIMEOUT)
181 self._check_reply("inspect", reply)
182
183 async def test_complete(self, kc):
184 msg_id = kc.complete("who cares")
185 assert isinstance(msg_id, str)
186 # Drain the first reply to avoid race condition
187 await kc._async_recv_reply(msg_id, timeout=TIMEOUT)
188 # Now test the reply=True convenience path
189 reply = await kc.complete("code", reply=True, timeout=TIMEOUT)
190 self._check_reply("complete", reply)
191
192 async def test_is_complete(self, kc):
193 msg_id = kc.is_complete("who cares")
194 assert isinstance(msg_id, str)
195 # Drain the first reply to avoid race condition
196 await kc._async_recv_reply(msg_id, timeout=TIMEOUT)
197 # Now test the reply=True convenience path
198 reply = await kc.is_complete("code", reply=True, timeout=TIMEOUT)
199 self._check_reply("is_complete", reply)
200
201 async def test_kernel_info(self, kc):
202 msg_id = kc.kernel_info()
203 assert isinstance(msg_id, str)
204 # Drain the first reply to avoid race condition
205 await kc._async_recv_reply(msg_id, timeout=TIMEOUT)
206 # Now test the reply=True convenience path
207 reply = await kc.kernel_info(reply=True, timeout=TIMEOUT)
208 self._check_reply("kernel_info", reply)
209
210 async def test_comm_info(self, kc):
211 msg_id = kc.comm_info()
212 assert isinstance(msg_id, str)
213 # Drain the first reply to avoid race condition
214 await kc._async_recv_reply(msg_id, timeout=TIMEOUT)
215 # Now test the reply=True convenience path
216 reply = await kc.comm_info(reply=True, timeout=TIMEOUT)
217 self._check_reply("comm_info", reply)
218
219 async def test_shutdown(self, kc):
220 reply = await kc.shutdown(reply=True, timeout=TIMEOUT)
221 self._check_reply("shutdown", reply)
222
223 async def test_shutdown_id(self, kc):
224 msg_id = kc.shutdown()
225 assert isinstance(msg_id, str)
226
227
228 class ThreadedKernelManager(KernelManager):
229 client_class = DottedObjectName("tests.test_client.CustomThreadedKernelClient")
230
231
232 class CustomThreadedZMQSocketChannel(ThreadedZMQSocketChannel):
233 last_msg = None
234
235 def __init__(self, *args, **kwargs):
236 self.msg_recv = Event()
237 super().__init__(*args, **kwargs)
238
239 def call_handlers(self, msg):
240 self.last_msg = msg
241 self.msg_recv.set()
242
243
244 class CustomThreadedKernelClient(ThreadedKernelClient):
245 iopub_channel_class = Type(CustomThreadedZMQSocketChannel) # type:ignore[arg-type]
246 shell_channel_class = Type(CustomThreadedZMQSocketChannel) # type:ignore[arg-type]
247 stdin_channel_class = Type(CustomThreadedZMQSocketChannel) # type:ignore[arg-type]
248 control_channel_class = Type(CustomThreadedZMQSocketChannel) # type:ignore[arg-type]
249
250
251 class TestThreadedKernelClient(TestKernelClient):
252 def setUp(self):
253 try:
254 KernelSpecManager().get_kernel_spec("echo")
255 except NoSuchKernel:
256 pytest.skip()
257 self.km = km = ThreadedKernelManager(kernel_name="echo")
258 km.start_kernel()
259 self.kc = kc = km.client()
260 kc.start_channels()
261
262 def tearDown(self):
263 self.km.shutdown_kernel()
264 self.kc.stop_channels()
265
266 def _check_reply(self, reply_type, reply):
267 self.assertIsInstance(reply, dict)
268 self.assertEqual(reply["header"]["msg_type"], reply_type + "_reply")
269 self.assertEqual(reply["parent_header"]["msg_type"], reply_type + "_request")
270
271 def test_execute_interactive(self):
272 pytest.skip("Not supported")
273
274 def test_history(self):
275 kc = self.kc
276 msg_id = kc.history(session=0)
277 self.assertIsInstance(msg_id, str)
278 kc.history(session=0)
279 kc.shell_channel.msg_recv.wait()
280 reply = kc.shell_channel.last_msg
281 self._check_reply("history", reply)
282
283 def test_inspect(self):
284 kc = self.kc
285 msg_id = kc.inspect("who cares")
286 self.assertIsInstance(msg_id, str)
287 kc.inspect("code")
288 kc.shell_channel.msg_recv.wait()
289 reply = kc.shell_channel.last_msg
290 self._check_reply("inspect", reply)
291
292 def test_complete(self):
293 kc = self.kc
294 msg_id = kc.complete("who cares")
295 self.assertIsInstance(msg_id, str)
296 kc.complete("code")
297 kc.shell_channel.msg_recv.wait()
298 reply = kc.shell_channel.last_msg
299 self._check_reply("complete", reply)
300
301 def test_kernel_info(self):
302 kc = self.kc
303 msg_id = kc.kernel_info()
304 self.assertIsInstance(msg_id, str)
305 kc.kernel_info()
306 kc.shell_channel.msg_recv.wait()
307 reply = kc.shell_channel.last_msg
308 self._check_reply("kernel_info", reply)
309
310 def test_comm_info(self):
311 kc = self.kc
312 msg_id = kc.comm_info()
313 self.assertIsInstance(msg_id, str)
314 kc.shell_channel.msg_recv.wait()
315 reply = kc.shell_channel.last_msg
316 self._check_reply("comm_info", reply)
317
318 def test_shutdown(self):
319 kc = self.kc
320 kc.shutdown()
321 kc.control_channel.msg_recv.wait()
322 reply = kc.control_channel.last_msg
323 self._check_reply("shutdown", reply)
324
325 def test_shutdown_id(self):
326 kc = self.kc
327 msg_id = kc.shutdown()
328 self.assertIsInstance(msg_id, str)
329
330
331 def test_validate_string_dict():
332 with pytest.raises(ValueError):
333 validate_string_dict(dict(a=1)) # type:ignore
334 with pytest.raises(ValueError):
335 validate_string_dict({1: "a"}) # type:ignore