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