Debian Codegraph @

src/trio/_tests/test_repl.py

raw
1 from __future__ import annotations
2
3 import os
4 import pathlib
5 import signal
6 import subprocess
7 import sys
8 from functools import partial
9 from typing import Protocol
10
11 import pytest
12
13 import trio._repl
14
15
16 class RawInput(Protocol):
17 def __call__(self, prompt: str = "") -> str: ...
18
19
20 def build_raw_input(cmds: list[str]) -> RawInput:
21 """
22 Pass in a list of strings.
23 Returns a callable that returns each string, each time its called
24 When there are not more strings to return, raise EOFError
25 """
26 cmds_iter = iter(cmds)
27 prompts = []
28
29 def _raw_helper(prompt: str = "") -> str:
30 prompts.append(prompt)
31 try:
32 return next(cmds_iter)
33 except StopIteration:
34 raise EOFError from None
35
36 return _raw_helper
37
38
39 def test_build_raw_input() -> None:
40 """Quick test of our helper function."""
41 raw_input = build_raw_input(["cmd1"])
42 assert raw_input() == "cmd1"
43 with pytest.raises(EOFError):
44 raw_input()
45
46
47 async def test_basic_interaction(
48 capsys: pytest.CaptureFixture[str],
49 monkeypatch: pytest.MonkeyPatch,
50 ) -> None:
51 """
52 Run some basic commands through the interpreter while capturing stdout.
53 Ensure that the interpreted prints the expected results.
54 """
55 console = trio._repl.TrioInteractiveConsole()
56 raw_input = build_raw_input(
57 [
58 # evaluate simple expression and recall the value
59 "x = 1",
60 "print(f'{x=}')",
61 # Literal gets printed
62 "'hello'",
63 # define and call sync function
64 "def func():",
65 " print(x + 1)",
66 "",
67 "func()",
68 # define and call async function
69 "async def afunc():",
70 " return 4",
71 "",
72 "await afunc()",
73 # import works
74 "import sys",
75 "sys.stdout.write('hello stdout\\n')",
76 ],
77 )
78 monkeypatch.setattr(console, "raw_input", raw_input)
79 await trio._repl.run_repl(console)
80 out, _err = capsys.readouterr()
81 assert out.splitlines() == ["x=1", "'hello'", "2", "4", "hello stdout", "13"]
82
83
84 async def test_system_exits_quit_interpreter(monkeypatch: pytest.MonkeyPatch) -> None:
85 console = trio._repl.TrioInteractiveConsole()
86 raw_input = build_raw_input(
87 [
88 "raise SystemExit",
89 ],
90 )
91 monkeypatch.setattr(console, "raw_input", raw_input)
92 with pytest.raises(SystemExit):
93 await trio._repl.run_repl(console)
94
95
96 async def test_KI_interrupts(
97 capsys: pytest.CaptureFixture[str],
98 monkeypatch: pytest.MonkeyPatch,
99 ) -> None:
100 console = trio._repl.TrioInteractiveConsole()
101 raw_input = build_raw_input(
102 [
103 "import signal, trio, trio.lowlevel",
104 "async def f():",
105 " trio.lowlevel.spawn_system_task("
106 " trio.to_thread.run_sync,"
107 " signal.raise_signal, signal.SIGINT,"
108 " )", # just awaiting this kills the test runner?!
109 " await trio.sleep_forever()",
110 " print('should not see this')",
111 "",
112 "await f()",
113 "print('AFTER KeyboardInterrupt')",
114 ],
115 )
116 monkeypatch.setattr(console, "raw_input", raw_input)
117 await trio._repl.run_repl(console)
118 out, err = capsys.readouterr()
119 assert "KeyboardInterrupt" in err
120 assert "should" not in out
121 assert "AFTER KeyboardInterrupt" in out
122
123
124 async def test_system_exits_in_exc_group(
125 capsys: pytest.CaptureFixture[str],
126 monkeypatch: pytest.MonkeyPatch,
127 ) -> None:
128 console = trio._repl.TrioInteractiveConsole()
129 raw_input = build_raw_input(
130 [
131 "import sys",
132 "if sys.version_info < (3, 11):",
133 " from exceptiongroup import BaseExceptionGroup",
134 "",
135 "raise BaseExceptionGroup('', [RuntimeError(), SystemExit()])",
136 "print('AFTER BaseExceptionGroup')",
137 ],
138 )
139 monkeypatch.setattr(console, "raw_input", raw_input)
140 await trio._repl.run_repl(console)
141 out, _err = capsys.readouterr()
142 # assert that raise SystemExit in an exception group
143 # doesn't quit
144 assert "AFTER BaseExceptionGroup" in out
145
146
147 async def test_system_exits_in_nested_exc_group(
148 capsys: pytest.CaptureFixture[str],
149 monkeypatch: pytest.MonkeyPatch,
150 ) -> None:
151 console = trio._repl.TrioInteractiveConsole()
152 raw_input = build_raw_input(
153 [
154 "import sys",
155 "if sys.version_info < (3, 11):",
156 " from exceptiongroup import BaseExceptionGroup",
157 "",
158 "raise BaseExceptionGroup(",
159 " '', [BaseExceptionGroup('', [RuntimeError(), SystemExit()])])",
160 "print('AFTER BaseExceptionGroup')",
161 ],
162 )
163 monkeypatch.setattr(console, "raw_input", raw_input)
164 await trio._repl.run_repl(console)
165 out, _err = capsys.readouterr()
166 # assert that raise SystemExit in an exception group
167 # doesn't quit
168 assert "AFTER BaseExceptionGroup" in out
169
170
171 async def test_base_exception_captured(
172 capsys: pytest.CaptureFixture[str],
173 monkeypatch: pytest.MonkeyPatch,
174 ) -> None:
175 console = trio._repl.TrioInteractiveConsole()
176 raw_input = build_raw_input(
177 [
178 # The statement after raise should still get executed
179 "raise BaseException",
180 "print('AFTER BaseException')",
181 ],
182 )
183 monkeypatch.setattr(console, "raw_input", raw_input)
184 await trio._repl.run_repl(console)
185 out, err = capsys.readouterr()
186 assert "_threads.py" not in err
187 assert "_repl.py" not in err
188 assert "AFTER BaseException" in out
189
190
191 async def test_exc_group_captured(
192 capsys: pytest.CaptureFixture[str],
193 monkeypatch: pytest.MonkeyPatch,
194 ) -> None:
195 console = trio._repl.TrioInteractiveConsole()
196 raw_input = build_raw_input(
197 [
198 # The statement after raise should still get executed
199 "raise ExceptionGroup('', [KeyError()])",
200 "print('AFTER ExceptionGroup')",
201 ],
202 )
203 monkeypatch.setattr(console, "raw_input", raw_input)
204 await trio._repl.run_repl(console)
205 out, _err = capsys.readouterr()
206 assert "AFTER ExceptionGroup" in out
207
208
209 async def test_base_exception_capture_from_coroutine(
210 capsys: pytest.CaptureFixture[str],
211 monkeypatch: pytest.MonkeyPatch,
212 ) -> None:
213 console = trio._repl.TrioInteractiveConsole()
214 raw_input = build_raw_input(
215 [
216 "async def async_func_raises_base_exception():",
217 " raise BaseException",
218 "",
219 # This will raise, but the statement after should still
220 # be executed
221 "await async_func_raises_base_exception()",
222 "print('AFTER BaseException')",
223 ],
224 )
225 monkeypatch.setattr(console, "raw_input", raw_input)
226 await trio._repl.run_repl(console)
227 out, err = capsys.readouterr()
228 assert "_threads.py" not in err
229 assert "_repl.py" not in err
230 assert "AFTER BaseException" in out
231
232
233 def test_main_entrypoint() -> None:
234 """
235 Basic smoke test when running via the package __main__ entrypoint.
236 """
237 repl = subprocess.run([sys.executable, "-m", "trio"], input=b"exit()")
238 assert repl.returncode == 0
239
240
241 def should_try_newline_injection() -> bool:
242 if sys.platform != "linux":
243 return False
244
245 sysctl = pathlib.Path("/proc/sys/dev/tty/legacy_tiocsti")
246 if not sysctl.exists(): # pragma: no cover
247 return True
248
249 else:
250 return sysctl.read_text() == "1"
251
252
253 @pytest.mark.skipif(
254 not should_try_newline_injection(),
255 reason="the ioctl we use is disabled in CI",
256 )
257 def test_ki_newline_injection() -> None: # TODO: test this line
258 # TODO: we want to remove this functionality, eg by using vendored
259 # pyrepls.
260 assert sys.platform != "win32"
261
262 import pty
263
264 # NOTE: this cannot be subprocess.Popen because pty.fork
265 # does some magic to set the controlling terminal.
266 # (which I don't know how to replicate... so I copied this
267 # structure from pty.spawn...)
268 pid, pty_fd = pty.fork() # type: ignore[attr-defined,unused-ignore]
269 if pid == 0:
270 os.execlp(sys.executable, *[sys.executable, "-u", "-m", "trio"])
271
272 # setup:
273 buffer = b""
274 while not buffer.endswith(b"import trio\r\n>>> "):
275 buffer += os.read(pty_fd, 4096)
276
277 # sanity check:
278 print(buffer.decode())
279 buffer = b""
280 os.write(pty_fd, b'print("hello!")\n')
281 while not buffer.endswith(b">>> "):
282 buffer += os.read(pty_fd, 4096)
283
284 assert buffer.count(b"hello!") == 2
285
286 # press ctrl+c
287 print(buffer.decode())
288 buffer = b""
289 os.kill(pid, signal.SIGINT)
290 while not buffer.endswith(b">>> "):
291 buffer += os.read(pty_fd, 4096)
292
293 assert b"KeyboardInterrupt" in buffer
294
295 # press ctrl+c later
296 print(buffer.decode())
297 buffer = b""
298 os.write(pty_fd, b'print("hello!")')
299 os.kill(pid, signal.SIGINT)
300 while not buffer.endswith(b">>> "):
301 buffer += os.read(pty_fd, 4096)
302
303 assert b"KeyboardInterrupt" in buffer
304 print(buffer.decode())
305 os.close(pty_fd)
306 os.waitpid(pid, 0)[1]
307
308
309 async def test_ki_in_repl() -> None:
310 async with trio.open_nursery() as nursery:
311 proc = await nursery.start(
312 partial(
313 trio.run_process,
314 [sys.executable, "-u", "-m", "trio"],
315 stdout=subprocess.PIPE,
316 stderr=subprocess.STDOUT,
317 stdin=subprocess.PIPE,
318 creationflags=subprocess.CREATE_NEW_PROCESS_GROUP if sys.platform == "win32" else 0, # type: ignore[attr-defined,unused-ignore]
319 )
320 )
321
322 async with proc.stdout:
323 # setup
324 buffer = b""
325 async for part in proc.stdout: # pragma: no branch
326 buffer += part
327 # TODO: consider making run_process stdout have some universal newlines thing
328 if buffer.replace(b"\r\n", b"\n").endswith(b"import trio\n>>> "):
329 break
330
331 # ensure things work
332 print(buffer.decode())
333 buffer = b""
334 await proc.stdin.send_all(b'print("hello!")\n')
335 async for part in proc.stdout: # pragma: no branch
336 buffer += part
337 if buffer.endswith(b">>> "):
338 break
339
340 assert b"hello!" in buffer
341 print(buffer.decode())
342
343 # this seems to be necessary on Windows for reasons
344 # (the parents of process groups ignore ctrl+c by default...)
345 if sys.platform == "win32":
346 buffer = b""
347 await proc.stdin.send_all(
348 b"import ctypes; ctypes.windll.kernel32.SetConsoleCtrlHandler(None, False)\n"
349 )
350 async for part in proc.stdout: # pragma: no branch
351 buffer += part
352 if buffer.endswith(b">>> "):
353 break
354
355 print(buffer.decode())
356
357 # try to decrease flakiness...
358 buffer = b""
359 await proc.stdin.send_all(
360 b"import coverage; trio.lowlevel.enable_ki_protection(coverage.pytracer.PyTracer._trace)\n"
361 )
362 async for part in proc.stdout: # pragma: no branch
363 buffer += part
364 if buffer.endswith(b">>> "):
365 break
366
367 print(buffer.decode())
368
369 # ensure that ctrl+c on a prompt works
370 # NOTE: for some reason, signal.SIGINT doesn't work for this test.
371 # Using CTRL_C_EVENT is also why we need subprocess.CREATE_NEW_PROCESS_GROUP
372 signal_sent = signal.CTRL_C_EVENT if sys.platform == "win32" else signal.SIGINT # type: ignore[attr-defined,unused-ignore]
373 os.kill(proc.pid, signal_sent)
374 if sys.platform == "win32":
375 # we rely on EOFError which... doesn't happen with pipes.
376 # I'm not sure how to fix it...
377 await proc.stdin.send_all(b"\n")
378 else:
379 # we test injection separately
380 await proc.stdin.send_all(b"\n")
381
382 buffer = b""
383 async for part in proc.stdout: # pragma: no branch
384 buffer += part
385 if buffer.endswith(b">>> "):
386 break
387
388 assert b"KeyboardInterrupt" in buffer
389
390 # ensure ctrl+c while a command runs works
391 print(buffer.decode())
392 await proc.stdin.send_all(b'print("READY"); await trio.sleep_forever()\n')
393 killed = False
394 buffer = b""
395 async for part in proc.stdout: # pragma: no branch
396 buffer += part
397 if buffer.replace(b"\r\n", b"\n").endswith(b"READY\n") and not killed:
398 os.kill(proc.pid, signal_sent)
399 killed = True
400 if buffer.endswith(b">>> "):
401 break
402
403 assert b"trio" in buffer
404 assert b"KeyboardInterrupt" in buffer
405
406 # make sure it works for sync commands too
407 # (though this would be hard to break)
408 print(buffer.decode())
409 await proc.stdin.send_all(
410 b'import time; print("READY"); time.sleep(99999)\n'
411 )
412 killed = False
413 buffer = b""
414 async for part in proc.stdout: # pragma: no branch
415 buffer += part
416 if buffer.replace(b"\r\n", b"\n").endswith(b"READY\n") and not killed:
417 os.kill(proc.pid, signal_sent)
418 killed = True
419 if buffer.endswith(b">>> "):
420 break
421
422 assert b"Traceback" in buffer
423 assert b"KeyboardInterrupt" in buffer
424
425 print(buffer.decode())
426
427 # kill the process
428 nursery.cancel_scope.cancel()