Skip to content

Commit a952374

Browse files
committed
Refactor test and simplify CAN_USE_PYREPL after pythongh-121659
1 parent 964de70 commit a952374

File tree

6 files changed

+52
-74
lines changed

6 files changed

+52
-74
lines changed

Lib/_pyrepl/main.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323

2424
def interactive_console(mainmodule=None, quiet=False, pythonstartup=False):
2525
if not CAN_USE_PYREPL:
26-
if not os.environ.get('PYTHON_BASIC_REPL', None) and FAIL_REASON:
26+
if not os.getenv('PYTHON_BASIC_REPL') and FAIL_REASON:
2727
from .trace import trace
2828
trace(FAIL_REASON)
2929
print(FAIL_REASON, file=sys.stderr)

Lib/_pyrepl/readline.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@
5858
TYPE_CHECKING = False
5959

6060
if TYPE_CHECKING:
61-
from typing import Any
61+
from typing import Any, Mapping
6262

6363

6464
MoreLinesCallable = Callable[[str], bool]
@@ -559,7 +559,7 @@ def stub(*args: object, **kwds: object) -> None:
559559
# ____________________________________________________________
560560

561561

562-
def _setup(namespace: dict[str, Any]) -> None:
562+
def _setup(namespace: Mapping[str, Any]) -> None:
563563
global raw_input
564564
if raw_input is not None:
565565
return # don't run _setup twice

Lib/_pyrepl/simple_interact.py

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -27,12 +27,9 @@
2727

2828
import _sitebuiltins
2929
import linecache
30-
import builtins
3130
import sys
3231
import code
33-
from types import ModuleType
3432

35-
from .console import InteractiveColoredConsole
3633
from .readline import _get_reader, multiline_input
3734

3835
TYPE_CHECKING = False
@@ -82,15 +79,12 @@ def _clear_screen():
8279

8380

8481
def run_multiline_interactive_console(
85-
*,
8682
console: code.InteractiveConsole,
83+
*,
8784
future_flags: int = 0,
8885
) -> None:
8986
from .readline import _setup
90-
91-
namespace = console.locals if isinstance(console.locals, dict) else dict(console.locals)
92-
_setup(namespace)
93-
87+
_setup(console.locals)
9488
if future_flags:
9589
console.compile.compiler.flags |= future_flags
9690

Lib/asyncio/__main__.py

Lines changed: 8 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -97,28 +97,14 @@ def run(self):
9797
exec(startup_code, console.locals)
9898

9999
ps1 = getattr(sys, "ps1", ">>> ")
100-
if can_colorize():
100+
if can_colorize() and CAN_USE_PYREPL:
101101
ps1 = f"{ANSIColors.BOLD_MAGENTA}{ps1}{ANSIColors.RESET}"
102102
console.write(f"{ps1}import asyncio\n")
103103

104-
try:
105-
import errno
106-
if os.getenv("PYTHON_BASIC_REPL"):
107-
raise RuntimeError("user environment requested basic REPL")
108-
if not os.isatty(sys.stdin.fileno()):
109-
return_code = errno.ENOTTY
110-
raise OSError(return_code, "tty required", "stdin")
111-
112-
# This import will fail on operating systems with no termios.
104+
if CAN_USE_PYREPL:
113105
from _pyrepl.simple_interact import (
114-
check,
115106
run_multiline_interactive_console,
116107
)
117-
if err := check():
118-
raise RuntimeError(err)
119-
except Exception as e:
120-
console.interact(banner="", exitmsg="")
121-
else:
122108
try:
123109
run_multiline_interactive_console(console)
124110
except SystemExit:
@@ -129,6 +115,8 @@ def run(self):
129115
console.showtraceback()
130116
console.write("Internal error, ")
131117
return_code = 1
118+
else:
119+
console.interact(banner="", exitmsg="")
132120
finally:
133121
warnings.filterwarnings(
134122
'ignore',
@@ -139,7 +127,10 @@ def run(self):
139127

140128

141129
if __name__ == '__main__':
142-
CAN_USE_PYREPL = True
130+
if os.getenv('PYTHON_BASIC_REPL'):
131+
CAN_USE_PYREPL = False
132+
else:
133+
from _pyrepl.main import CAN_USE_PYREPL
143134

144135
return_code = 0
145136
loop = asyncio.new_event_loop()

Lib/site.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -517,10 +517,7 @@ def register_readline():
517517
pass
518518

519519
if readline.get_current_history_length() == 0:
520-
try:
521-
from _pyrepl.main import CAN_USE_PYREPL
522-
except ImportError:
523-
CAN_USE_PYREPL = False
520+
from _pyrepl.main import CAN_USE_PYREPL
524521
# If no history was loaded, default to .python_history,
525522
# or PYTHON_HISTORY.
526523
# The guard is necessary to avoid doubling history size at

Lib/test/test_repl.py

Lines changed: 38 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -3,25 +3,27 @@
33
from io import BytesIO
44
import os
55
from re import sub
6-
import subprocess
76
import tempfile
7+
import select
8+
import subprocess
89
import sys
910
import unittest
1011
from textwrap import dedent
1112
from test import support
1213
from test.support import (
1314
cpython_only,
1415
has_subprocess_support,
15-
is_android,
16-
is_apple_mobile,
17-
is_emscripten,
18-
is_wasi,
1916
SuppressCrashReport,
20-
reap_children,
17+
SHORT_TIMEOUT,
2118
)
2219
from test.support.script_helper import assert_python_failure, kill_python, assert_python_ok
2320
from test.support.import_helper import import_module
2421

22+
try:
23+
import pty
24+
except ImportError:
25+
pty = None
26+
2527

2628
if not has_subprocess_support:
2729
raise unittest.SkipTest("test module requires subprocess")
@@ -207,9 +209,6 @@ def bar(x):
207209
expected = "(30, None, [\'def foo(x):\\n\', \' return x + 1\\n\', \'\\n\'], \'<stdin>\')"
208210
self.assertIn(expected, output, expected)
209211

210-
def test_asyncio_repl_no_tty_fails(self):
211-
assert assert_python_failure("-m", "asyncio")
212-
213212
def test_asyncio_repl_reaches_python_startup_script(self):
214213
with tempfile.TemporaryDirectory() as tmpdir:
215214
script = os.path.join(tmpdir, "script.py")
@@ -223,42 +222,39 @@ def test_asyncio_repl_reaches_python_startup_script(self):
223222
env={"PYTHONSTARTUP": script}
224223
)
225224

225+
@unittest.skipUnless(pty, "requires pty")
226226
def test_asyncio_repl_is_ok(self):
227-
# The REPL expects a tty to go into the interactive mode, so let's
228-
# simulate one. This test is limited to Linux since
229-
# it uses the pty module.
227+
m, s = pty.openpty()
228+
cmd = [sys.executable, "-m", "asyncio"]
229+
proc = subprocess.Popen(
230+
cmd,
231+
stdin=s,
232+
stdout=s,
233+
stderr=s,
234+
text=True,
235+
close_fds=True,
236+
env=os.environ,
237+
)
238+
os.close(s)
239+
os.write(m, b"await asyncio.sleep(0)\n")
240+
os.write(m, b"exit()\n")
241+
output = []
242+
while select.select([m], [], [], SHORT_TIMEOUT)[0]:
243+
try:
244+
data = os.read(m, 1024).decode("utf-8")
245+
if not data:
246+
break
247+
except OSError:
248+
break
249+
output.append(data)
250+
os.close(m)
230251
try:
231-
import_module('termios')
232-
if is_android or is_apple_mobile or is_emscripten or is_wasi:
233-
raise unittest.SkipTest("pty is not available on this platform")
234-
235-
import pty
252+
exit_code = proc.wait(timeout=SHORT_TIMEOUT)
253+
except subprocess.TimeoutExpired:
254+
proc.kill()
255+
exit_code = proc.wait()
236256

237-
m, s = pty.openpty()
238-
try:
239-
with open(s, "rb") as proc_file, open(m, "w") as input_file:
240-
proc = subprocess.Popen(
241-
[
242-
sys.executable,
243-
"-m",
244-
"asyncio",
245-
],
246-
stdin=proc_file,
247-
stdout=proc_file,
248-
stderr=proc_file,
249-
)
250-
input_file.write("exit()\n")
251-
proc.wait()
252-
finally:
253-
for fd in [m, s]:
254-
try:
255-
os.close(fd)
256-
except OSError:
257-
pass
258-
259-
self.assertEqual(proc.returncode, 0)
260-
finally:
261-
reap_children()
257+
self.assertEqual(exit_code, 0)
262258

263259
class TestInteractiveModeSyntaxErrors(unittest.TestCase):
264260

0 commit comments

Comments
 (0)