|
5 | 5 | import subprocess |
6 | 6 | import sys |
7 | 7 | import unittest |
| 8 | +from contextlib import contextmanager |
8 | 9 | from functools import partial |
9 | 10 | from textwrap import dedent |
10 | 11 | from test import support |
@@ -67,6 +68,19 @@ def spawn_repl(*args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, custom=F |
67 | 68 | spawn_asyncio_repl = partial(spawn_repl, "-m", "asyncio", custom=True) |
68 | 69 |
|
69 | 70 |
|
| 71 | +@contextmanager |
| 72 | +def temp_pythonstartup(*, source: str, histfile: str = ".pythonhist"): |
| 73 | + """Create environment variables for a PYTHONSTARTUP script in a temporary directory.""" |
| 74 | + with os_helper.temp_dir() as tmpdir: |
| 75 | + filename = os.path.join(tmpdir, "pythonstartup.py") |
| 76 | + with open(filename, "w") as f: |
| 77 | + f.write(source) |
| 78 | + yield { |
| 79 | + "PYTHONSTARTUP": filename, |
| 80 | + "PYTHON_HISTORY": os.path.join(tmpdir, histfile) |
| 81 | + } |
| 82 | + |
| 83 | + |
70 | 84 | def run_on_interactive_mode(source): |
71 | 85 | """Spawn a new Python interpreter, pass the given |
72 | 86 | input source code from the stdin and return the |
@@ -276,8 +290,6 @@ def make_repl(env): |
276 | 290 | """) % script |
277 | 291 | self.assertIn(expected, output) |
278 | 292 |
|
279 | | - |
280 | | - |
281 | 293 | def test_runsource_show_syntax_error_location(self): |
282 | 294 | user_input = dedent("""def f(x, x): ... |
283 | 295 | """) |
@@ -449,6 +461,33 @@ def test_quiet_mode(self): |
449 | 461 | self.assertEqual(p.returncode, 0) |
450 | 462 | self.assertEqual(output[:3], ">>>") |
451 | 463 |
|
| 464 | + @support.force_not_colorized |
| 465 | + @support.subTests( |
| 466 | + ("startup_code", "expected_error"), |
| 467 | + [ |
| 468 | + ("some invalid syntax\n", "SyntaxError: invalid syntax"), |
| 469 | + ("1/0\n", "ZeroDivisionError: division by zero"), |
| 470 | + ], |
| 471 | + ) |
| 472 | + def test_pythonstartup_failure(self, startup_code, expected_error): |
| 473 | + startup_env = self.enterContext( |
| 474 | + temp_pythonstartup(source=startup_code, histfile=".asyncio_history")) |
| 475 | + |
| 476 | + p = spawn_repl( |
| 477 | + "-qm", "asyncio", |
| 478 | + env=os.environ | startup_env, |
| 479 | + isolated=False, |
| 480 | + custom=True) |
| 481 | + p.stdin.write("print('user code', 'executed')\n") |
| 482 | + output = kill_python(p) |
| 483 | + self.assertEqual(p.returncode, 0) |
| 484 | + |
| 485 | + tb_hint = f'File "{startup_env["PYTHONSTARTUP"]}", line 1' |
| 486 | + self.assertIn(tb_hint, output) |
| 487 | + self.assertIn(expected_error, output) |
| 488 | + |
| 489 | + self.assertIn("user code executed", output) |
| 490 | + |
452 | 491 |
|
453 | 492 | if __name__ == "__main__": |
454 | 493 | unittest.main() |
0 commit comments