Skip to content

Commit 49cf4a6

Browse files
committed
Update tests
1 parent 9d4fe71 commit 49cf4a6

2 files changed

Lines changed: 72 additions & 150 deletions

File tree

‎Lib/test/test_pyrepl/test_interact.py‎

Lines changed: 2 additions & 150 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,11 @@
33
import sys
44
import warnings
55
import unittest
6-
from unittest.mock import ANY, MagicMock, patch
6+
from unittest.mock import ANY, patch
77
from textwrap import dedent
88

9-
from test.support import force_colorized, force_not_colorized
9+
from test.support import force_not_colorized
1010

11-
from _pyrepl import simple_interact
1211
from _pyrepl.console import InteractiveColoredConsole
1312
from _pyrepl.simple_interact import (
1413
_more_lines,
@@ -359,150 +358,3 @@ def f():
359358
count = sum("'return' in a 'finally' block" in str(w.message)
360359
for w in caught)
361360
self.assertEqual(count, 1)
362-
363-
364-
class TestInputSubmittedHook(unittest.TestCase):
365-
def _run_interactive(self, statements, hook):
366-
console = InteractiveColoredConsole()
367-
statement_iter = iter(statements)
368-
369-
def fake_multiline_input(more_lines, ps1, ps2):
370-
try:
371-
return next(statement_iter)
372-
except StopIteration:
373-
raise EOFError
374-
375-
output = io.StringIO()
376-
with (
377-
patch.object(simple_interact, "input_submitted_hook", hook),
378-
patch.object(
379-
simple_interact,
380-
"multiline_input",
381-
side_effect=fake_multiline_input,
382-
),
383-
patch.object(simple_interact, "_get_reader"),
384-
patch.object(simple_interact, "append_history_file"),
385-
patch("_pyrepl.readline._setup"),
386-
contextlib.redirect_stdout(output),
387-
contextlib.redirect_stderr(output),
388-
):
389-
simple_interact.run_multiline_interactive_console(console)
390-
391-
return output.getvalue(), console.locals
392-
393-
def test_hook_called_before_statement_execution(self):
394-
statement = "if True:\n print('statement executed')\n"
395-
escape_sequence = "\x1b]633;C\x07"
396-
hook = MagicMock(
397-
side_effect=lambda statement: print(escape_sequence, end="")
398-
)
399-
output, _ = self._run_interactive([statement], hook)
400-
401-
hook.assert_called_once_with(statement)
402-
self.assertEqual(output, f"{escape_sequence}statement executed\n")
403-
404-
def test_hook_receives_input_without_final_auto_indent(self):
405-
statement = "if True:\n x = 1\n "
406-
hook = MagicMock()
407-
408-
_, namespace = self._run_interactive([statement], hook)
409-
410-
hook.assert_called_once_with("if True:\n x = 1\n")
411-
self.assertEqual(namespace["x"], 1)
412-
413-
@force_not_colorized
414-
def test_hook_exception_is_displayed(self):
415-
hook = MagicMock(side_effect=RuntimeError("hook error"))
416-
417-
output, namespace = self._run_interactive(["x = 1"], hook)
418-
419-
self.assertIn(
420-
"Error in input_submitted_hook:\n"
421-
"Traceback (most recent call last):\n",
422-
output,
423-
)
424-
self.assertIn("input_submitted_hook(", output)
425-
self.assertIn("RuntimeError: hook error", output)
426-
self.assertEqual(namespace["x"], 1)
427-
428-
@force_colorized
429-
def test_hook_exception_is_colorized(self):
430-
def hook(statement):
431-
raise RuntimeError("hook error")
432-
433-
output, namespace = self._run_interactive(["x = 1"], hook)
434-
435-
self.assertIn("Error in input_submitted_hook:\n", output)
436-
self.assertRegex(output, r"\x1b\[[0-9;]+m")
437-
self.assertIn("hook error", output)
438-
self.assertEqual(namespace["x"], 1)
439-
440-
@force_not_colorized
441-
def test_hook_exception_preserves_last_exception(self):
442-
try:
443-
raise ValueError("previous user error")
444-
except ValueError as exc:
445-
previous_exception = exc
446-
447-
last_attributes = {
448-
"last_exc": previous_exception,
449-
"last_type": type(previous_exception),
450-
"last_value": previous_exception,
451-
"last_traceback": previous_exception.__traceback__,
452-
}
453-
for initialized in (True, False):
454-
with self.subTest(initialized=initialized), contextlib.ExitStack() as stack:
455-
for name, value in last_attributes.items():
456-
stack.enter_context(patch.object(sys, name, value, create=True))
457-
if not initialized:
458-
delattr(sys, name)
459-
460-
hook = MagicMock(side_effect=RuntimeError("hook error"))
461-
output, namespace = self._run_interactive(["x = 1"], hook)
462-
463-
self.assertIn("RuntimeError: hook error", output)
464-
self.assertEqual(namespace["x"], 1)
465-
for name, value in last_attributes.items():
466-
if initialized:
467-
self.assertIs(getattr(sys, name), value)
468-
else:
469-
self.assertFalse(hasattr(sys, name))
470-
471-
def test_hook_keyboard_interrupt_cancels_submission(self):
472-
hook = MagicMock(side_effect=[KeyboardInterrupt, None])
473-
474-
output, namespace = self._run_interactive(["x = 1", "y = 2"], hook)
475-
476-
self.assertIn("\nKeyboardInterrupt\n", output)
477-
self.assertNotIn("Error in input_submitted_hook:", output)
478-
self.assertNotIn("x", namespace)
479-
self.assertEqual(namespace["y"], 2)
480-
self.assertEqual(hook.call_count, 2)
481-
482-
def test_hook_system_exit_exits_repl(self):
483-
hook = MagicMock(side_effect=SystemExit(42))
484-
statement = "raise SystemExit(99)"
485-
486-
with self.assertRaises(SystemExit) as caught:
487-
self._run_interactive([statement, "x = 1"], hook)
488-
489-
self.assertEqual(caught.exception.code, 42)
490-
hook.assert_called_once_with(statement)
491-
492-
def test_hook_not_called_for_repl_commands(self):
493-
hook = MagicMock()
494-
self._run_interactive(["clear"], hook)
495-
496-
hook.assert_not_called()
497-
498-
@force_not_colorized
499-
def test_hook_called_before_execution_exception(self):
500-
statement = "1 / 0"
501-
marker = "hook ran first"
502-
hook = MagicMock(side_effect=lambda statement: print(marker))
503-
output, _ = self._run_interactive([statement], hook)
504-
505-
hook.assert_called_once_with(statement)
506-
marker_index = output.index(marker)
507-
traceback_index = output.index("ZeroDivisionError")
508-
self.assertLess(marker_index, traceback_index)

‎Lib/test/test_pyrepl/test_pyrepl.py‎

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2112,6 +2112,41 @@ def setUp(self):
21122112
self.addCleanup(patcher.stop)
21132113
patcher.start()
21142114

2115+
def test_input_submitted_hook(self):
2116+
env = os.environ.copy()
2117+
env["PYTHON_COLORS"] = "0"
2118+
marker = "\x1b]633;C\x07"
2119+
output, exit_code = self.run_repl(
2120+
[
2121+
"from _pyrepl import simple_interact as si",
2122+
f"def hook(source): print({marker!r} + repr(source), flush=True)",
2123+
"",
2124+
"si.input_submitted_hook = hook",
2125+
"print('single executed')",
2126+
"if True:",
2127+
"print('block executed')",
2128+
"",
2129+
"a b c",
2130+
"clear",
2131+
"exit",
2132+
],
2133+
env=env,
2134+
skip=True,
2135+
)
2136+
output = output.replace("\r\n", "\n")
2137+
self.assertEqual(exit_code, 0)
2138+
self.assertEqual(output.count(marker), 3)
2139+
for submitted_input, result in (
2140+
("print('single executed')", "single executed\n"),
2141+
("if True:\n print('block executed')\n", "block executed\n"),
2142+
("a b c", "SyntaxError: invalid syntax"),
2143+
):
2144+
with self.subTest(submitted_input=submitted_input):
2145+
hook_output = f"{marker}{submitted_input!r}"
2146+
self.assertIn(hook_output, output)
2147+
self.assertIn(result, output)
2148+
self.assertLess(output.index(hook_output), output.index(result))
2149+
21152150
def test_input_submitted_hook_exception(self):
21162151
env = make_clean_env()
21172152
env["NO_COLOR"] = "1"
@@ -2137,6 +2172,41 @@ def test_input_submitted_hook_exception(self):
21372172
self.assertEqual(output.count("RuntimeError: hook failed"), 2)
21382173
self.assertIn("\nexecuted: 1\n", output)
21392174

2175+
def test_input_submitted_hook_exception_preserves_sys_last(self):
2176+
env = os.environ.copy()
2177+
env["PYTHON_COLORS"] = "0"
2178+
output, exit_code = self.run_repl(
2179+
[
2180+
"import sys",
2181+
"from _pyrepl import simple_interact as si",
2182+
"names = ('last_exc', 'last_type', 'last_value', 'last_traceback')",
2183+
"print('initially unset:', all(not hasattr(sys, name) for name in names))",
2184+
"def hook(statement):",
2185+
"if statement in ('x = 1', 'y = 2'):",
2186+
"raise RuntimeError('hook failed')",
2187+
"",
2188+
"si.input_submitted_hook = hook",
2189+
"x = 1",
2190+
"print('still unset:', all(not hasattr(sys, name) for name in names))",
2191+
"si.input_submitted_hook = None",
2192+
"1 / 0",
2193+
"previous = tuple(getattr(sys, name) for name in names)",
2194+
"si.input_submitted_hook = hook",
2195+
"y = 2",
2196+
"print('last preserved:', isinstance(previous[0], ZeroDivisionError), "
2197+
"all(getattr(sys, name) is value for name, value in zip(names, previous)))",
2198+
"exit",
2199+
],
2200+
env=env,
2201+
skip=True,
2202+
)
2203+
output = output.replace("\r\n", "\n")
2204+
self.assertEqual(exit_code, 0)
2205+
self.assertEqual(output.count("Error in input_submitted_hook:\n"), 2)
2206+
self.assertIn("initially unset: True\n", output)
2207+
self.assertIn("still unset: True\n", output)
2208+
self.assertIn("last preserved: True True\n", output)
2209+
21402210
@force_not_colorized
21412211
def test_exposed_globals_in_repl(self):
21422212
pre = "['__builtins__'"

0 commit comments

Comments
 (0)