Debian Codegraph @

Lib/test/test_repl.py

raw
1 """Test the interactive interpreter."""
2
3 import os
4 import select
5 import subprocess
6 import sys
7 import unittest
8 from functools import partial
9 from textwrap import dedent
10 from test import support
11 from test.support import (
12 cpython_only,
13 has_subprocess_support,
14 os_helper,
15 SuppressCrashReport,
16 SHORT_TIMEOUT,
17 )
18 from test.support.script_helper import kill_python
19 from test.support.import_helper import import_module
20
21 try:
22 import pty
23 except ImportError:
24 pty = None
25
26
27 if not has_subprocess_support:
28 raise unittest.SkipTest("test module requires subprocess")
29
30
31 def spawn_repl(*args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, custom=False, isolated=True, **kw):
32 """Run the Python REPL with the given arguments.
33
34 kw is extra keyword args to pass to subprocess.Popen. Returns a Popen
35 object.
36 """
37
38 # To run the REPL without using a terminal, spawn python with the command
39 # line option '-i' and the process name set to '<stdin>'.
40 # The directory of argv[0] must match the directory of the Python
41 # executable for the Popen() call to python to succeed as the directory
42 # path may be used by Py_GetPath() to build the default module search
43 # path.
44 stdin_fname = os.path.join(os.path.dirname(sys.executable), "<stdin>")
45 cmd_line = [stdin_fname]
46 # Isolated mode implies -EPs and ignores PYTHON* variables.
47 if isolated:
48 cmd_line.append('-I')
49 # Don't re-run the built-in REPL from interactive mode
50 # if we're testing a custom REPL (such as the asyncio REPL).
51 if not custom:
52 cmd_line.append('-i')
53 cmd_line.extend(args)
54
55 # Set TERM=vt100, for the rationale see the comments in spawn_python() of
56 # test.support.script_helper.
57 env = kw.setdefault('env', dict(os.environ))
58 env['TERM'] = 'vt100'
59 return subprocess.Popen(cmd_line,
60 executable=sys.executable,
61 text=True,
62 stdin=subprocess.PIPE,
63 stdout=stdout, stderr=stderr,
64 **kw)
65
66
67 spawn_asyncio_repl = partial(spawn_repl, "-m", "asyncio", custom=True)
68
69
70 def run_on_interactive_mode(source):
71 """Spawn a new Python interpreter, pass the given
72 input source code from the stdin and return the
73 result back. If the interpreter exits non-zero, it
74 raises a ValueError."""
75
76 process = spawn_repl()
77 process.stdin.write(source)
78 output = kill_python(process)
79
80 if process.returncode != 0:
81 raise ValueError("Process didn't exit properly.")
82 return output
83
84
85 @support.force_not_colorized_test_class
86 class TestInteractiveInterpreter(unittest.TestCase):
87
88 @cpython_only
89 # Python built with Py_TRACE_REFS fail with a fatal error in
90 # _PyRefchain_Trace() on memory allocation error.
91 @unittest.skipIf(support.Py_TRACE_REFS, 'cannot test Py_TRACE_REFS build')
92 def test_no_memory(self):
93 import_module("_testcapi")
94 # Issue #30696: Fix the interactive interpreter looping endlessly when
95 # no memory. Check also that the fix does not break the interactive
96 # loop when an exception is raised.
97 user_input = """
98 import sys, _testcapi
99 1/0
100 print('After the exception.')
101 _testcapi.set_nomemory(0)
102 sys.exit(0)
103 """
104 user_input = dedent(user_input)
105 p = spawn_repl()
106 with SuppressCrashReport():
107 p.stdin.write(user_input)
108 output = kill_python(p)
109 self.assertIn('After the exception.', output)
110 # Exit code 120: Py_FinalizeEx() failed to flush stdout and stderr.
111 self.assertIn(p.returncode, (1, 120))
112
113 @cpython_only
114 def test_multiline_string_parsing(self):
115 # bpo-39209: Multiline string tokens need to be handled in the tokenizer
116 # in two places: the interactive path and the non-interactive path.
117 user_input = '''\
118 x = """<?xml version="1.0" encoding="iso-8859-1"?>
119 <test>
120 <Users>
121 <fun25>
122 <limits>
123 <total>0KiB</total>
124 <kbps>0</kbps>
125 <rps>1.3</rps>
126 <connections>0</connections>
127 </limits>
128 <usages>
129 <total>16738211KiB</total>
130 <kbps>237.15</kbps>
131 <rps>1.3</rps>
132 <connections>0</connections>
133 </usages>
134 <time_to_refresh>never</time_to_refresh>
135 <limit_exceeded_URL>none</limit_exceeded_URL>
136 </fun25>
137 </Users>
138 </test>"""
139 '''
140 user_input = dedent(user_input)
141 p = spawn_repl()
142 p.stdin.write(user_input)
143 output = kill_python(p)
144 self.assertEqual(p.returncode, 0)
145
146 def test_close_stdin(self):
147 user_input = dedent('''
148 import os
149 print("before close")
150 os.close(0)
151 ''')
152 prepare_repl = dedent('''
153 from test.support import suppress_msvcrt_asserts
154 suppress_msvcrt_asserts()
155 ''')
156 process = spawn_repl('-c', prepare_repl)
157 output = process.communicate(user_input)[0]
158 self.assertEqual(process.returncode, 0)
159 self.assertIn('before close', output)
160
161 def test_interactive_traceback_reporting(self):
162 user_input = "1 / 0 / 3 / 4"
163 p = spawn_repl()
164 p.stdin.write(user_input)
165 output = kill_python(p)
166 self.assertEqual(p.returncode, 0)
167
168 traceback_lines = output.splitlines()[-6:-1]
169 expected_lines = [
170 "Traceback (most recent call last):",
171 " File \"<stdin>\", line 1, in <module>",
172 " 1 / 0 / 3 / 4",
173 " ~~^~~",
174 "ZeroDivisionError: division by zero",
175 ]
176 self.assertEqual(traceback_lines, expected_lines)
177
178 def test_interactive_traceback_reporting_multiple_input(self):
179 user_input1 = dedent("""
180 def foo(x):
181 1 / x
182
183 """)
184 p = spawn_repl()
185 p.stdin.write(user_input1)
186 user_input2 = "foo(0)"
187 p.stdin.write(user_input2)
188 output = kill_python(p)
189 self.assertEqual(p.returncode, 0)
190
191 traceback_lines = output.splitlines()[-8:-1]
192 expected_lines = [
193 ' File "<stdin>", line 1, in <module>',
194 ' foo(0)',
195 ' ~~~^^^',
196 ' File "<stdin>", line 2, in foo',
197 ' 1 / x',
198 ' ~~^~~',
199 'ZeroDivisionError: division by zero'
200 ]
201 self.assertEqual(traceback_lines, expected_lines)
202
203 def test_pythonstartup_error_reporting(self):
204 # errors based on https://github.com/python/cpython/issues/137576
205
206 def make_repl(env):
207 return subprocess.Popen(
208 [os.path.join(os.path.dirname(sys.executable), '<stdin>'), "-i"],
209 executable=sys.executable,
210 text=True,
211 stdin=subprocess.PIPE,
212 stdout=subprocess.PIPE,
213 stderr=subprocess.STDOUT,
214 env=env,
215 )
216
217 # case 1: error in user input, but PYTHONSTARTUP is fine
218 with os_helper.temp_dir() as tmpdir:
219 script = os.path.join(tmpdir, "pythonstartup.py")
220 with open(script, "w") as f:
221 f.write("print('from pythonstartup')\n")
222
223 env = os.environ.copy()
224 env['PYTHONSTARTUP'] = script
225 env["PYTHON_HISTORY"] = os.path.join(tmpdir, ".pythonhist")
226 p = make_repl(env)
227 p.stdin.write("1/0")
228 output = kill_python(p)
229 expected = dedent("""
230 Traceback (most recent call last):
231 File "<stdin>", line 1, in <module>
232 1/0
233 ~^~
234 ZeroDivisionError: division by zero
235 """)
236 self.assertIn("from pythonstartup", output)
237 self.assertIn(expected, output)
238
239 # case 2: error in PYTHONSTARTUP triggered by user input
240 with os_helper.temp_dir() as tmpdir:
241 script = os.path.join(tmpdir, "pythonstartup.py")
242 with open(script, "w") as f:
243 f.write("def foo():\n 1/0\n")
244
245 env = os.environ.copy()
246 env['PYTHONSTARTUP'] = script
247 env["PYTHON_HISTORY"] = os.path.join(tmpdir, ".pythonhist")
248 p = make_repl(env)
249 p.stdin.write('foo()')
250 output = kill_python(p)
251 expected = dedent("""
252 Traceback (most recent call last):
253 File "<stdin>", line 1, in <module>
254 foo()
255 ~~~^^
256 File "%s", line 2, in foo
257 1/0
258 ~^~
259 ZeroDivisionError: division by zero
260 """) % script
261 self.assertIn(expected, output)
262
263
264
265 def test_runsource_show_syntax_error_location(self):
266 user_input = dedent("""def f(x, x): ...
267 """)
268 p = spawn_repl()
269 p.stdin.write(user_input)
270 output = kill_python(p)
271 expected_lines = [
272 ' def f(x, x): ...',
273 ' ^',
274 "SyntaxError: duplicate argument 'x' in function definition"
275 ]
276 self.assertEqual(output.splitlines()[4:-1], expected_lines)
277
278 def test_interactive_source_is_in_linecache(self):
279 user_input = dedent("""
280 def foo(x):
281 return x + 1
282
283 def bar(x):
284 return foo(x) + 2
285 """)
286 p = spawn_repl()
287 p.stdin.write(user_input)
288 user_input2 = dedent("""
289 import linecache
290 print(linecache._interactive_cache[linecache._make_key(foo.__code__)])
291 """)
292 p.stdin.write(user_input2)
293 output = kill_python(p)
294 self.assertEqual(p.returncode, 0)
295 expected = "(30, None, [\'def foo(x):\\n\', \' return x + 1\\n\', \'\\n\'], \'<stdin>\')"
296 self.assertIn(expected, output, expected)
297
298 def test_asyncio_repl_reaches_python_startup_script(self):
299 with os_helper.temp_dir() as tmpdir:
300 script = os.path.join(tmpdir, "pythonstartup.py")
301 with open(script, "w") as f:
302 f.write("print('pythonstartup done!')\n")
303 env = os.environ.copy()
304 env["PYTHON_HISTORY"] = os.path.join(tmpdir, ".asyncio_history")
305 env["PYTHONSTARTUP"] = script
306 p = spawn_asyncio_repl(isolated=False, env=env)
307 output = kill_python(p)
308 self.assertEqual(p.returncode, 0)
309 self.assertIn("pythonstartup done!", output)
310
311 def test_asyncio_repl_respects_isolated_mode(self):
312 with os_helper.temp_dir() as tmpdir:
313 script = os.path.join(tmpdir, "pythonstartup.py")
314 with open(script, "w") as f:
315 f.write("print('should not print')\n")
316 env = os.environ.copy()
317 env["PYTHON_HISTORY"] = os.path.join(tmpdir, ".asyncio_history")
318 env["PYTHONSTARTUP"] = script
319 p = spawn_asyncio_repl(isolated=True, env=env)
320 output = kill_python(p)
321 self.assertEqual(p.returncode, 0)
322 self.assertNotIn("should not print", output)
323
324 @unittest.skipUnless(pty, "requires pty")
325 def test_asyncio_repl_is_ok(self):
326 m, s = pty.openpty()
327 cmd = [sys.executable, "-I", "-m", "asyncio"]
328 env = os.environ.copy()
329 proc = subprocess.Popen(
330 cmd,
331 stdin=s,
332 stdout=s,
333 stderr=s,
334 text=True,
335 close_fds=True,
336 env=env,
337 )
338 os.close(s)
339 os.write(m, b"await asyncio.sleep(0)\n")
340 os.write(m, b"exit()\n")
341 output = []
342 while select.select([m], [], [], SHORT_TIMEOUT)[0]:
343 try:
344 data = os.read(m, 1024).decode("utf-8")
345 if not data:
346 break
347 except OSError:
348 break
349 output.append(data)
350 os.close(m)
351 try:
352 exit_code = proc.wait(timeout=SHORT_TIMEOUT)
353 except subprocess.TimeoutExpired:
354 proc.kill()
355 exit_code = proc.wait()
356
357 self.assertEqual(exit_code, 0, "".join(output))
358
359
360 @support.force_not_colorized_test_class
361 class TestInteractiveModeSyntaxErrors(unittest.TestCase):
362
363 def test_interactive_syntax_error_correct_line(self):
364 output = run_on_interactive_mode(dedent("""\
365 def f():
366 print(0)
367 return yield 42
368 """))
369
370 traceback_lines = output.splitlines()[-4:-1]
371 expected_lines = [
372 ' return yield 42',
373 ' ^^^^^',
374 'SyntaxError: invalid syntax'
375 ]
376 self.assertEqual(traceback_lines, expected_lines)
377
378
379 class TestAsyncioREPL(unittest.TestCase):
380 def test_multiple_statements_fail_early(self):
381 user_input = "1 / 0; print(f'afterwards: {1+1}')"
382 p = spawn_asyncio_repl()
383 p.stdin.write(user_input)
384 output = kill_python(p)
385 self.assertIn("ZeroDivisionError", output)
386 self.assertNotIn("afterwards: 2", output)
387
388 def test_toplevel_contextvars_sync(self):
389 user_input = dedent("""\
390 from contextvars import ContextVar
391 var = ContextVar("var", default="failed")
392 var.set("ok")
393 """)
394 p = spawn_asyncio_repl()
395 p.stdin.write(user_input)
396 user_input2 = dedent("""
397 print(f"toplevel contextvar test: {var.get()}")
398 """)
399 p.stdin.write(user_input2)
400 output = kill_python(p)
401 self.assertEqual(p.returncode, 0)
402 expected = "toplevel contextvar test: ok"
403 self.assertIn(expected, output, expected)
404
405 def test_toplevel_contextvars_async(self):
406 user_input = dedent("""\
407 from contextvars import ContextVar
408 var = ContextVar('var', default='failed')
409 """)
410 p = spawn_asyncio_repl()
411 p.stdin.write(user_input)
412 user_input2 = "async def set_var(): var.set('ok')\n"
413 p.stdin.write(user_input2)
414 user_input3 = "await set_var()\n"
415 p.stdin.write(user_input3)
416 user_input4 = "print(f'toplevel contextvar test: {var.get()}')\n"
417 p.stdin.write(user_input4)
418 output = kill_python(p)
419 self.assertEqual(p.returncode, 0)
420 expected = "toplevel contextvar test: ok"
421 self.assertIn(expected, output, expected)
422
423 def test_quiet_mode(self):
424 p = spawn_repl("-q", "-m", "asyncio", custom=True)
425 output = kill_python(p)
426 self.assertEqual(p.returncode, 0)
427 self.assertEqual(output[:3], ">>>")
428
429
430 if __name__ == "__main__":
431 unittest.main()