Debian Codegraph @

tests/utils.py

raw
1 """utilities for testing IPython kernels"""
2
3 # Copyright (c) IPython Development Team.
4 # Distributed under the terms of the Modified BSD License.
5 from __future__ import annotations
6
7 import atexit
8 import os
9 import sys
10 from contextlib import contextmanager
11 from queue import Empty
12 from subprocess import STDOUT
13 from tempfile import TemporaryDirectory
14 from time import time
15
16 from jupyter_client import manager
17 from jupyter_client.blocking.client import BlockingKernelClient
18
19 STARTUP_TIMEOUT = 60
20 TIMEOUT = 100
21
22 KM: manager.KernelManager = None # type:ignore
23 KC: BlockingKernelClient = None # type:ignore
24
25
26 def start_new_kernel(**kwargs):
27 """start a new kernel, and return its Manager and Client
28
29 Integrates with our output capturing for tests.
30 """
31 kwargs["stderr"] = STDOUT
32 return manager.start_new_kernel(startup_timeout=STARTUP_TIMEOUT, **kwargs)
33
34
35 def flush_channels(kc=None):
36 """flush any messages waiting on the queue"""
37 from .test_message_spec import validate_message
38
39 if kc is None:
40 kc = KC
41 for get_msg in (kc.get_shell_msg, kc.get_iopub_msg):
42 while True:
43 try:
44 msg = get_msg(timeout=0.1)
45 except Empty:
46 break
47 else:
48 validate_message(msg)
49
50
51 def get_reply(kc, msg_id, timeout=TIMEOUT, channel="shell"):
52 t0 = time()
53 while True:
54 get_msg = getattr(kc, f"get_{channel}_msg")
55 reply = get_msg(timeout=timeout)
56 if reply["parent_header"]["msg_id"] == msg_id:
57 break
58 # Allow debugging ignored replies
59 print(f"Ignoring reply not to {msg_id}: {reply}")
60 t1 = time()
61 timeout -= t1 - t0
62 t0 = t1
63 return reply
64
65
66 def get_replies(kc, msg_ids: list[str], timeout=TIMEOUT, channel="shell"):
67 # Get replies which may arrive in any order as they may be running on different subshells.
68 # Replies are returned in the same order as the msg_ids, not in the order of arrival.
69 count = 0
70 replies = [None] * len(msg_ids)
71 while count < len(msg_ids):
72 get_msg = getattr(kc, f"get_{channel}_msg")
73 reply = get_msg(timeout=timeout)
74 try:
75 msg_id = reply["parent_header"]["msg_id"]
76 replies[msg_ids.index(msg_id)] = reply
77 count += 1
78 except ValueError:
79 # Allow debugging ignored replies
80 print(f"Ignoring reply not to any of {msg_ids}: {reply}")
81 return replies
82
83
84 def execute(code="", kc=None, **kwargs):
85 """wrapper for doing common steps for validating an execution request"""
86 from .test_message_spec import validate_message
87
88 if kc is None:
89 kc = KC
90 msg_id = kc.execute(code=code, **kwargs)
91 reply = get_reply(kc, msg_id, TIMEOUT)
92 validate_message(reply, "execute_reply", msg_id)
93 busy = kc.get_iopub_msg(timeout=TIMEOUT)
94 validate_message(busy, "status", msg_id)
95 assert busy["content"]["execution_state"] == "busy"
96
97 if not kwargs.get("silent"):
98 execute_input = kc.get_iopub_msg(timeout=TIMEOUT)
99 validate_message(execute_input, "execute_input", msg_id)
100 assert execute_input["content"]["code"] == code
101
102 # show tracebacks if present for debugging
103 if reply["content"].get("traceback"):
104 print("\n".join(reply["content"]["traceback"]), file=sys.stderr)
105
106 return msg_id, reply["content"]
107
108
109 def start_global_kernel():
110 """start the global kernel (if it isn't running) and return its client"""
111 global KM, KC
112 if KM is None:
113 KM, KC = start_new_kernel()
114 atexit.register(stop_global_kernel)
115 else:
116 flush_channels(KC)
117 return KC
118
119
120 @contextmanager
121 def kernel():
122 """Context manager for the global kernel instance
123
124 Should be used for most kernel tests
125
126 Returns
127 -------
128 kernel_client: connected KernelClient instance
129 """
130 yield start_global_kernel()
131
132
133 def uses_kernel(test_f):
134 """Decorator for tests that use the global kernel"""
135
136 def wrapped_test():
137 with kernel() as kc:
138 test_f(kc)
139
140 wrapped_test.__doc__ = test_f.__doc__
141 wrapped_test.__name__ = test_f.__name__
142 return wrapped_test
143
144
145 def stop_global_kernel():
146 """Stop the global shared kernel instance, if it exists"""
147 global KM, KC
148 KC.stop_channels()
149 KC = None # type:ignore
150 if KM is None:
151 return
152 KM.shutdown_kernel(now=True)
153 KM = None # type:ignore
154
155
156 def new_kernel(argv=None):
157 """Context manager for a new kernel in a subprocess
158
159 Should only be used for tests where the kernel must not be reused.
160
161 Returns
162 -------
163 kernel_client: connected KernelClient instance
164 """
165 kwargs = {"stderr": STDOUT}
166 if argv is not None:
167 kwargs["extra_arguments"] = argv
168 return manager.run_kernel(**kwargs)
169
170
171 def assemble_output(get_msg, timeout=1, parent_msg_id: str | None = None, raise_error=True):
172 """assemble stdout/err from an execution"""
173 stdout = ""
174 stderr = ""
175 while True:
176 msg = get_msg(timeout=timeout)
177 msg_type = msg["msg_type"]
178 content = msg["content"]
179
180 if parent_msg_id is not None and msg["parent_header"]["msg_id"] != parent_msg_id:
181 # Ignore message for wrong parent message
182 continue
183
184 if msg_type == "status" and content["execution_state"] == "idle":
185 # idle message signals end of output
186 break
187 elif msg["msg_type"] == "stream":
188 if content["name"] == "stdout":
189 stdout += content["text"]
190 elif content["name"] == "stderr":
191 stderr += content["text"]
192 else:
193 raise KeyError("bad stream: %r" % content["name"])
194 elif raise_error and msg["msg_type"] == "error":
195 tb = "\n".join(msg["content"]["traceback"])
196 msg = f"Execution failed with:\n{tb}"
197 if stderr:
198 msg = f"{msg}\nstderr:\n{stderr}"
199 raise RuntimeError(msg)
200 else:
201 # other output, ignored
202 pass
203 return stdout, stderr
204
205
206 def wait_for_idle(kc, parent_msg_id: str | None = None):
207 while True:
208 msg = kc.get_iopub_msg(timeout=1)
209 msg_type = msg["msg_type"]
210 content = msg["content"]
211 if (
212 msg_type == "status"
213 and content["execution_state"] == "idle"
214 and (parent_msg_id is None or msg["parent_header"]["msg_id"] == parent_msg_id)
215 ):
216 break
217
218
219 class TemporaryWorkingDirectory(TemporaryDirectory):
220 """
221 Creates a temporary directory and sets the cwd to that directory.
222 Automatically reverts to previous cwd upon cleanup.
223 Usage example:
224
225 with TemporaryWorkingDirectory() as tmpdir:
226 ...
227 """
228
229 def __enter__(self):
230 self.old_wd = os.getcwd()
231 os.chdir(self.name)
232 return super().__enter__()
233
234 def __exit__(self, exc, value, tb):
235 os.chdir(self.old_wd)
236 return super().__exit__(exc, value, tb)