Debian Codegraph @

tests/test_async.py

raw
1 """Test async/await integration"""
2
3 import pytest
4
5 from .test_message_spec import validate_message
6 from .utils import TIMEOUT, execute, flush_channels, start_new_kernel
7
8 KC = KM = None
9
10
11 @pytest.fixture(autouse=True)
12 def _setup_env():
13 """start the global kernel (if it isn't running) and return its client"""
14 global KM, KC
15 KM, KC = start_new_kernel()
16 flush_channels(KC)
17 yield
18 assert KC is not None
19 assert KM is not None
20 KC.stop_channels()
21 KM.shutdown_kernel(now=True)
22
23
24 def test_async_await():
25 flush_channels(KC)
26 _msg_id, content = execute("import asyncio; await asyncio.sleep(0.1)", KC)
27 assert content["status"] == "ok", content
28
29
30 @pytest.mark.parametrize("asynclib", ["asyncio", "trio"])
31 def test_async_interrupt(asynclib, request):
32 assert KC is not None
33 assert KM is not None
34 try:
35 __import__(asynclib)
36 except ImportError:
37 pytest.skip("Requires %s" % asynclib)
38 request.addfinalizer(lambda: execute("%autoawait asyncio", KC))
39
40 flush_channels(KC)
41 msg_id, content = execute("%autoawait " + asynclib, KC)
42 assert content["status"] == "ok", content
43
44 flush_channels(KC)
45 msg_id = KC.execute(f"print('begin'); import {asynclib}; await {asynclib}.sleep(5)")
46 busy = KC.get_iopub_msg(timeout=TIMEOUT)
47 validate_message(busy, "status", msg_id)
48 assert busy["content"]["execution_state"] == "busy"
49 echo = KC.get_iopub_msg(timeout=TIMEOUT)
50 validate_message(echo, "execute_input")
51 stream = KC.get_iopub_msg(timeout=TIMEOUT)
52 # wait for the stream output to be sure kernel is in the async block
53 validate_message(stream, "stream")
54 assert stream["content"]["text"] == "begin\n"
55
56 KM.interrupt_kernel()
57 reply = KC.get_shell_msg()["content"]
58 assert reply["status"] == "error", reply
59 assert reply["ename"] in {"CancelledError", "KeyboardInterrupt"}
60
61 flush_channels(KC)