Debian Codegraph @

tests/test_message_spec.py

raw
1 """Test suite for our zeromq-based message specification."""
2
3 # Copyright (c) IPython Development Team.
4 # Distributed under the terms of the Modified BSD License.
5
6 import re
7 import sys
8 from queue import Empty
9
10 import pytest
11 from jupyter_client._version import version_info
12 from jupyter_client.blocking.client import BlockingKernelClient
13 from packaging.version import Version as V
14 from traitlets import Bool, Dict, Enum, HasTraits, Integer, List, TraitError, Unicode, observe
15
16 from .utils import TIMEOUT, execute, flush_channels, get_reply, start_global_kernel
17
18 # -----------------------------------------------------------------------------
19 # Globals
20 # -----------------------------------------------------------------------------
21 KC: BlockingKernelClient = None # type:ignore
22
23
24 @pytest.fixture(autouse=True)
25 def _setup_env():
26 global KC
27 KC = start_global_kernel()
28
29
30 # -----------------------------------------------------------------------------
31 # Message Spec References
32 # -----------------------------------------------------------------------------
33
34
35 class Reference(HasTraits):
36 """
37 Base class for message spec specification testing.
38
39 This class is the core of the message specification test. The
40 idea is that child classes implement trait attributes for each
41 message keys, so that message keys can be tested against these
42 traits using :meth:`check` method.
43
44 """
45
46 def check(self, d):
47 """validate a dict against our traits"""
48 for key in self.trait_names():
49 assert key in d
50 # FIXME: always allow None, probably not a good idea
51 if d[key] is None:
52 continue
53 try:
54 setattr(self, key, d[key])
55 except TraitError as e:
56 raise AssertionError(str(e)) from None
57
58
59 class Version(Unicode):
60 def __init__(self, *args, **kwargs):
61 self.min = kwargs.pop("min", None)
62 self.max = kwargs.pop("max", None)
63 kwargs["default_value"] = self.min
64 super().__init__(*args, **kwargs)
65
66 def validate(self, obj, value):
67 if self.min and V(value) < V(self.min):
68 msg = f"bad version: {value} < {self.min}"
69 raise TraitError(msg)
70 if self.max and (V(value) > V(self.max)):
71 msg = f"bad version: {value} > {self.max}"
72 raise TraitError(msg)
73
74
75 class RMessage(Reference):
76 msg_id = Unicode()
77 msg_type = Unicode()
78 header = Dict()
79 parent_header = Dict()
80 content = Dict()
81
82 def check(self, d):
83 super().check(d)
84 RHeader().check(self.header)
85 if self.parent_header:
86 RHeader().check(self.parent_header)
87
88
89 class RHeader(Reference):
90 msg_id = Unicode()
91 msg_type = Unicode()
92 session = Unicode()
93 username = Unicode()
94 version = Version(min="5.0")
95
96
97 mime_pat = re.compile(r"^[\w\-\+\.]+/[\w\-\+\.]+$")
98
99
100 class MimeBundle(Reference):
101 metadata = Dict()
102 data = Dict()
103
104 @observe("data")
105 def _on_data_changed(self, change):
106 for k, v in change["new"].items():
107 assert mime_pat.match(k)
108 assert isinstance(v, str)
109
110
111 # shell replies
112 class Reply(Reference):
113 status = Enum(("ok", "error"), default_value="ok")
114
115
116 class ExecuteReply(Reply):
117 execution_count = Integer()
118
119 def check(self, d):
120 Reference.check(self, d)
121 if d["status"] == "ok":
122 ExecuteReplyOkay().check(d)
123 elif d["status"] == "error":
124 ExecuteReplyError().check(d)
125 elif d["status"] == "aborted":
126 ExecuteReplyAborted().check(d)
127
128
129 class ExecuteReplyOkay(Reply):
130 status = Enum(("ok",))
131 user_expressions = Dict()
132
133
134 class ExecuteReplyError(Reply):
135 status = Enum(("error",))
136 ename = Unicode()
137 evalue = Unicode()
138 traceback = List(Unicode())
139
140
141 class ExecuteReplyAborted(Reply):
142 status = Enum(("aborted",))
143
144
145 class InspectReply(Reply, MimeBundle):
146 found = Bool()
147
148
149 class ArgSpec(Reference):
150 args = List(Unicode())
151 varargs = Unicode()
152 varkw = Unicode()
153 defaults = List()
154
155
156 class Status(Reference):
157 execution_state = Enum(("busy", "idle", "starting"), default_value="busy")
158
159
160 class CompleteReply(Reply):
161 matches = List(Unicode())
162 cursor_start = Integer()
163 cursor_end = Integer()
164 status = Unicode() # type:ignore
165
166
167 class LanguageInfo(Reference):
168 name = Unicode("python")
169 version = Unicode(sys.version.split()[0])
170
171
172 class KernelInfoReply(Reply):
173 protocol_version = Version(min="5.0")
174 implementation = Unicode("ipython")
175 implementation_version = Version(min="2.1")
176 language_info = Dict()
177 banner = Unicode()
178
179 def check(self, d):
180 Reference.check(self, d)
181 LanguageInfo().check(d["language_info"])
182
183
184 class ConnectReply(Reference):
185 shell_port = Integer()
186 control_port = Integer()
187 stdin_port = Integer()
188 iopub_port = Integer()
189 hb_port = Integer()
190
191
192 class CommInfoReply(Reply):
193 comms = Dict()
194
195
196 class IsCompleteReply(Reference):
197 status = Enum(("complete", "incomplete", "invalid", "unknown"), default_value="complete")
198
199 def check(self, d):
200 Reference.check(self, d)
201 if d["status"] == "incomplete":
202 IsCompleteReplyIncomplete().check(d)
203
204
205 class IsCompleteReplyIncomplete(Reference):
206 indent = Unicode()
207
208
209 # IOPub messages
210
211
212 class ExecuteInput(Reference):
213 code = Unicode()
214 execution_count = Integer()
215
216
217 class Error(ExecuteReplyError):
218 """Errors are the same as ExecuteReply, but without status"""
219
220 status = None # type:ignore # no status field
221
222
223 class Stream(Reference):
224 name = Enum(("stdout", "stderr"), default_value="stdout")
225 text = Unicode()
226
227
228 class DisplayData(MimeBundle):
229 pass
230
231
232 class ExecuteResult(MimeBundle):
233 execution_count = Integer()
234
235
236 class HistoryReply(Reply):
237 history = List(List())
238
239
240 # Subshell control messages
241
242
243 class CreateSubshellReply(Reply):
244 subshell_id = Unicode()
245
246
247 class DeleteSubshellReply(Reply):
248 pass
249
250
251 class ListSubshellReply(Reply):
252 subshell_id = List(Unicode())
253
254
255 references = {
256 "execute_reply": ExecuteReply(),
257 "inspect_reply": InspectReply(),
258 "status": Status(),
259 "complete_reply": CompleteReply(),
260 "kernel_info_reply": KernelInfoReply(),
261 "connect_reply": ConnectReply(),
262 "comm_info_reply": CommInfoReply(),
263 "is_complete_reply": IsCompleteReply(),
264 "execute_input": ExecuteInput(),
265 "execute_result": ExecuteResult(),
266 "history_reply": HistoryReply(),
267 "error": Error(),
268 "stream": Stream(),
269 "display_data": DisplayData(),
270 "header": RHeader(),
271 "create_subshell_reply": CreateSubshellReply(),
272 "delete_subshell_reply": DeleteSubshellReply(),
273 "list_subshell_reply": ListSubshellReply(),
274 }
275
276 # -----------------------------------------------------------------------------
277 # Specifications of `content` part of the reply messages.
278 # -----------------------------------------------------------------------------
279
280
281 def validate_message(msg, msg_type=None, parent=None):
282 """validate a message
283
284 This is a generator, and must be iterated through to actually
285 trigger each test.
286
287 If msg_type and/or parent are given, the msg_type and/or parent msg_id
288 are compared with the given values.
289 """
290 RMessage().check(msg)
291 if msg_type:
292 assert msg["msg_type"] == msg_type
293 if parent:
294 assert msg["parent_header"]["msg_id"] == parent
295 content = msg["content"]
296 ref = references[msg["msg_type"]]
297 ref.check(content)
298
299
300 # -----------------------------------------------------------------------------
301 # Tests
302 # -----------------------------------------------------------------------------
303
304 # Shell channel
305
306
307 def test_execute():
308 flush_channels()
309
310 msg_id = KC.execute(code="x=1")
311 reply = get_reply(KC, msg_id, TIMEOUT)
312 validate_message(reply, "execute_reply", msg_id)
313
314
315 def test_execute_silent():
316 flush_channels()
317 msg_id, reply = execute(code="x=1", silent=True)
318
319 # flush status=idle
320 status = KC.get_iopub_msg(timeout=TIMEOUT)
321 validate_message(status, "status", msg_id)
322 assert status["content"]["execution_state"] == "idle"
323
324 with pytest.raises(Empty):
325 KC.get_iopub_msg(timeout=0.1)
326
327 count = reply["execution_count"]
328
329 msg_id, reply = execute(code="x=2", silent=True)
330
331 # flush status=idle
332 status = KC.get_iopub_msg(timeout=TIMEOUT)
333 validate_message(status, "status", msg_id)
334 assert status["content"]["execution_state"] == "idle"
335
336 with pytest.raises(Empty):
337 KC.get_iopub_msg(timeout=0.1)
338
339 count_2 = reply["execution_count"]
340 assert count_2 == count
341
342
343 def test_execute_error():
344 flush_channels()
345
346 msg_id, reply = execute(code="1/0")
347 assert reply["status"] == "error"
348 assert reply["ename"] == "ZeroDivisionError"
349
350 error = KC.get_iopub_msg(timeout=TIMEOUT)
351 validate_message(error, "error", msg_id)
352
353
354 def test_execute_inc():
355 """execute request should increment execution_count"""
356 flush_channels()
357
358 _, reply = execute(code="x=1")
359 count = reply["execution_count"]
360
361 flush_channels()
362
363 _, reply = execute(code="x=2")
364 count_2 = reply["execution_count"]
365 assert count_2 == count + 1
366
367
368 def test_execute_stop_on_error():
369 """execute request should not abort execution queue with stop_on_error False"""
370 flush_channels()
371
372 fail = "\n".join(
373 [
374 # sleep to ensure subsequent message is waiting in the queue to be aborted
375 # async sleep to ensure coroutines are processing while this happens
376 "import asyncio",
377 "await asyncio.sleep(1)",
378 "raise ValueError()",
379 ]
380 )
381 KC.execute(code=fail)
382 KC.execute(code='print("Hello")')
383 KC.execute(code='print("world")')
384 reply = KC.get_shell_msg(timeout=TIMEOUT)
385 reply = KC.get_shell_msg(timeout=TIMEOUT)
386 assert reply["content"]["status"] == "aborted"
387 # second message, too
388 reply = KC.get_shell_msg(timeout=TIMEOUT)
389 assert reply["content"]["status"] == "aborted"
390
391 flush_channels()
392
393 KC.execute(code=fail, stop_on_error=False)
394 KC.execute(code='print("Hello")')
395 KC.get_shell_msg(timeout=TIMEOUT)
396 reply = KC.get_shell_msg(timeout=TIMEOUT)
397 assert reply["content"]["status"] == "ok"
398
399
400 def test_non_execute_stop_on_error():
401 """test that non-execute_request's are not aborted after an error"""
402 flush_channels()
403
404 fail = "\n".join(
405 [
406 # sleep to ensure subsequent message is waiting in the queue to be aborted
407 "import time",
408 "time.sleep(0.5)",
409 "raise ValueError",
410 ]
411 )
412 KC.execute(code=fail)
413 KC.kernel_info()
414 KC.comm_info()
415 KC.inspect(code="print")
416 reply = KC.get_shell_msg(timeout=TIMEOUT) # execute
417 assert reply["content"]["status"] == "error"
418 reply = KC.get_shell_msg(timeout=TIMEOUT) # kernel_info
419 assert reply["content"]["status"] == "ok"
420 reply = KC.get_shell_msg(timeout=TIMEOUT) # comm_info
421 assert reply["content"]["status"] == "ok"
422 reply = KC.get_shell_msg(timeout=TIMEOUT) # inspect
423 assert reply["content"]["status"] == "ok"
424
425
426 def test_user_expressions():
427 flush_channels()
428
429 _msg_id, reply = execute(code="x=1", user_expressions=dict(foo="x+1"))
430 user_expressions = reply["user_expressions"]
431 assert user_expressions == {
432 "foo": {
433 "status": "ok",
434 "data": {"text/plain": "2"},
435 "metadata": {},
436 }
437 }
438
439
440 def test_user_expressions_fail():
441 flush_channels()
442
443 _msg_id, reply = execute(code="x=0", user_expressions=dict(foo="nosuchname"))
444 user_expressions = reply["user_expressions"]
445 foo = user_expressions["foo"]
446 assert foo["status"] == "error"
447 assert foo["ename"] == "NameError"
448
449
450 def test_oinfo():
451 flush_channels()
452
453 msg_id = KC.inspect("a")
454 reply = get_reply(KC, msg_id, TIMEOUT)
455 validate_message(reply, "inspect_reply", msg_id)
456
457
458 def test_oinfo_found():
459 flush_channels()
460
461 msg_id, reply = execute(code="a=5")
462
463 msg_id = KC.inspect("a")
464 reply = get_reply(KC, msg_id, TIMEOUT)
465 validate_message(reply, "inspect_reply", msg_id)
466 content = reply["content"]
467 assert content["found"]
468 text = content["data"]["text/plain"]
469 assert "Type:" in text
470 assert "Docstring:" in text
471
472
473 def test_oinfo_detail():
474 flush_channels()
475
476 msg_id, reply = execute(code="ip=get_ipython()")
477
478 msg_id = KC.inspect("ip.object_inspect", cursor_pos=10, detail_level=1)
479 reply = get_reply(KC, msg_id, TIMEOUT)
480 validate_message(reply, "inspect_reply", msg_id)
481 content = reply["content"]
482 assert content["found"]
483 text = content["data"]["text/plain"]
484 assert "Signature:" in text
485 assert "Source:" in text
486
487
488 def test_oinfo_not_found():
489 flush_channels()
490
491 msg_id = KC.inspect("does_not_exist")
492 reply = get_reply(KC, msg_id, TIMEOUT)
493 validate_message(reply, "inspect_reply", msg_id)
494 content = reply["content"]
495 assert not content["found"]
496
497
498 def test_complete():
499 flush_channels()
500
501 msg_id, reply = execute(code="alpha = albert = 5")
502
503 msg_id = KC.complete("al", 2)
504 reply = get_reply(KC, msg_id, TIMEOUT)
505 validate_message(reply, "complete_reply", msg_id)
506 matches = reply["content"]["matches"]
507 for name in ("alpha", "albert"):
508 assert name in matches
509
510
511 def test_kernel_info_request():
512 flush_channels()
513
514 msg_id = KC.kernel_info()
515 reply = get_reply(KC, msg_id, TIMEOUT)
516 validate_message(reply, "kernel_info_reply", msg_id)
517 assert "supported_features" in reply["content"]
518 assert "kernel subshells" in reply["content"]["supported_features"]
519
520
521 def test_connect_request():
522 flush_channels()
523 msg = KC.session.msg("connect_request")
524 KC.shell_channel.send(msg)
525 msg_id = msg["header"]["msg_id"]
526 reply = get_reply(KC, msg_id, TIMEOUT)
527 validate_message(reply, "connect_reply", msg_id)
528
529
530 def test_subshell():
531 flush_channels()
532
533 msg = KC.session.msg("create_subshell_request")
534 KC.control_channel.send(msg)
535 msg_id = msg["header"]["msg_id"]
536 reply = get_reply(KC, msg_id, TIMEOUT, channel="control")
537 validate_message(reply, "create_subshell_reply", msg_id)
538 subshell_id = reply["content"]["subshell_id"]
539
540 msg = KC.session.msg("list_subshell_request")
541 KC.control_channel.send(msg)
542 msg_id = msg["header"]["msg_id"]
543 reply = get_reply(KC, msg_id, TIMEOUT, channel="control")
544 validate_message(reply, "list_subshell_reply", msg_id)
545
546 msg = KC.session.msg("delete_subshell_request", {"subshell_id": subshell_id})
547 KC.control_channel.send(msg)
548 msg_id = msg["header"]["msg_id"]
549 reply = get_reply(KC, msg_id, TIMEOUT, channel="control")
550 validate_message(reply, "delete_subshell_reply", msg_id)
551
552
553 @pytest.mark.skipif(
554 version_info < (5, 0),
555 reason="earlier Jupyter Client don't have comm_info",
556 )
557 def test_comm_info_request():
558 flush_channels()
559 msg_id = KC.comm_info()
560 reply = get_reply(KC, msg_id, TIMEOUT)
561 validate_message(reply, "comm_info_reply", msg_id)
562
563
564 def test_single_payload():
565 """
566 We want to test the set_next_input is not triggered several time per cell.
567 This is (was ?) mostly due to the fact that `?` in a loop would trigger
568 several set_next_input.
569
570 I'm tempted to thing that we actually want to _allow_ multiple
571 set_next_input (that's users' choice). But that `?` itself (and ?'s
572 transform) should avoid setting multiple set_next_input).
573 """
574 flush_channels()
575 _msg_id, reply = execute(
576 code="ip = get_ipython()\nfor i in range(3):\n ip.set_next_input('Hello There')\n"
577 )
578 payload = reply["payload"]
579 next_input_pls = [pl for pl in payload if pl["source"] == "set_next_input"]
580 assert len(next_input_pls) == 1
581
582
583 def test_is_complete():
584 flush_channels()
585
586 msg_id = KC.is_complete("a = 1")
587 reply = get_reply(KC, msg_id, TIMEOUT)
588 validate_message(reply, "is_complete_reply", msg_id)
589
590
591 def test_history_range():
592 flush_channels()
593
594 KC.execute(code="x=1", store_history=True)
595 KC.get_shell_msg(timeout=TIMEOUT)
596
597 msg_id = KC.history(hist_access_type="range", raw=True, output=True, start=1, stop=2, session=0)
598 reply = get_reply(KC, msg_id, TIMEOUT)
599 validate_message(reply, "history_reply", msg_id)
600 content = reply["content"]
601 assert len(content["history"]) == 1
602
603
604 def test_history_tail():
605 flush_channels()
606
607 KC.execute(code="x=1", store_history=True)
608 KC.get_shell_msg(timeout=TIMEOUT)
609
610 msg_id = KC.history(hist_access_type="tail", raw=True, output=True, n=1, session=0)
611 reply = get_reply(KC, msg_id, TIMEOUT)
612 validate_message(reply, "history_reply", msg_id)
613 content = reply["content"]
614 assert len(content["history"]) == 1
615
616
617 def test_history_search():
618 flush_channels()
619
620 KC.execute(code="x=1", store_history=True)
621 KC.get_shell_msg(timeout=TIMEOUT)
622
623 msg_id = KC.history(
624 hist_access_type="search", raw=True, output=True, n=1, pattern="*", session=0
625 )
626 reply = get_reply(KC, msg_id, TIMEOUT)
627 validate_message(reply, "history_reply", msg_id)
628 content = reply["content"]
629 assert len(content["history"]) == 1
630
631
632 # IOPub channel
633
634
635 def test_stream():
636 flush_channels()
637
638 msg_id, _reply = execute("print('hi')")
639
640 stdout = KC.get_iopub_msg(timeout=TIMEOUT)
641 validate_message(stdout, "stream", msg_id)
642 content = stdout["content"]
643 assert content["text"] == "hi\n"
644
645
646 def test_display_data():
647 flush_channels()
648
649 msg_id, _reply = execute("from IPython.display import display; display(1)")
650
651 display = KC.get_iopub_msg(timeout=TIMEOUT)
652 validate_message(display, "display_data", parent=msg_id)
653 data = display["content"]["data"]
654 assert data["text/plain"] == "1"