| 1 |
import io |
| 2 |
import itertools |
| 3 |
import os |
| 4 |
import pathlib |
| 5 |
import re |
| 6 |
import rlcompleter |
| 7 |
import select |
| 8 |
import subprocess |
| 9 |
import sys |
| 10 |
import tempfile |
| 11 |
from unittest import TestCase, skipUnless, skipIf |
| 12 |
from unittest.mock import Mock, patch |
| 13 |
from test.support import force_not_colorized, make_clean_env, Py_DEBUG |
| 14 |
from test.support import SHORT_TIMEOUT, STDLIB_DIR |
| 15 |
from test.support.import_helper import import_module |
| 16 |
from test.support.os_helper import EnvironmentVarGuard, unlink |
| 17 |
|
| 18 |
from .support import ( |
| 19 |
FakeConsole, |
| 20 |
ScreenEqualMixin, |
| 21 |
handle_all_events, |
| 22 |
handle_events_narrow_console, |
| 23 |
more_lines, |
| 24 |
multiline_input, |
| 25 |
code_to_events, |
| 26 |
) |
| 27 |
from _pyrepl.console import Event |
| 28 |
from _pyrepl.readline import (ReadlineAlikeReader, ReadlineConfig, |
| 29 |
_ReadlineWrapper) |
| 30 |
from _pyrepl.readline import multiline_input as readline_multiline_input |
| 31 |
|
| 32 |
try: |
| 33 |
import pty |
| 34 |
except ImportError: |
| 35 |
pty = None |
| 36 |
try: |
| 37 |
import readline as readline_module |
| 38 |
except ImportError: |
| 39 |
readline_module = None |
| 40 |
|
| 41 |
|
| 42 |
class ReplTestCase(TestCase): |
| 43 |
def run_repl( |
| 44 |
self, |
| 45 |
repl_input: str | list[str], |
| 46 |
env: dict | None = None, |
| 47 |
*, |
| 48 |
cmdline_args: list[str] | None = None, |
| 49 |
cwd: str | None = None, |
| 50 |
skip: bool = False, |
| 51 |
) -> tuple[str, int]: |
| 52 |
temp_dir = None |
| 53 |
if cwd is None: |
| 54 |
temp_dir = tempfile.TemporaryDirectory(ignore_cleanup_errors=True) |
| 55 |
cwd = temp_dir.name |
| 56 |
try: |
| 57 |
return self._run_repl( |
| 58 |
repl_input, env=env, cmdline_args=cmdline_args, cwd=cwd, skip=skip, |
| 59 |
) |
| 60 |
finally: |
| 61 |
if temp_dir is not None: |
| 62 |
temp_dir.cleanup() |
| 63 |
|
| 64 |
def _run_repl( |
| 65 |
self, |
| 66 |
repl_input: str | list[str], |
| 67 |
*, |
| 68 |
env: dict | None, |
| 69 |
cmdline_args: list[str] | None, |
| 70 |
cwd: str, |
| 71 |
skip: bool, |
| 72 |
) -> tuple[str, int]: |
| 73 |
assert pty |
| 74 |
master_fd, slave_fd = pty.openpty() |
| 75 |
cmd = [sys.executable, "-i", "-u"] |
| 76 |
if env is None: |
| 77 |
cmd.append("-I") |
| 78 |
elif "PYTHON_HISTORY" not in env: |
| 79 |
env["PYTHON_HISTORY"] = os.path.join(cwd, ".regrtest_history") |
| 80 |
if cmdline_args is not None: |
| 81 |
cmd.extend(cmdline_args) |
| 82 |
|
| 83 |
try: |
| 84 |
import termios |
| 85 |
except ModuleNotFoundError: |
| 86 |
pass |
| 87 |
else: |
| 88 |
term_attr = termios.tcgetattr(slave_fd) |
| 89 |
term_attr[6][termios.VREPRINT] = 0 # pass through CTRL-R |
| 90 |
term_attr[6][termios.VINTR] = 0 # pass through CTRL-C |
| 91 |
termios.tcsetattr(slave_fd, termios.TCSANOW, term_attr) |
| 92 |
|
| 93 |
process = subprocess.Popen( |
| 94 |
cmd, |
| 95 |
stdin=slave_fd, |
| 96 |
stdout=slave_fd, |
| 97 |
stderr=slave_fd, |
| 98 |
cwd=cwd, |
| 99 |
text=True, |
| 100 |
close_fds=True, |
| 101 |
env=env if env else os.environ, |
| 102 |
) |
| 103 |
os.close(slave_fd) |
| 104 |
if isinstance(repl_input, list): |
| 105 |
repl_input = "\n".join(repl_input) + "\n" |
| 106 |
os.write(master_fd, repl_input.encode("utf-8")) |
| 107 |
|
| 108 |
output = [] |
| 109 |
while select.select([master_fd], [], [], SHORT_TIMEOUT)[0]: |
| 110 |
try: |
| 111 |
data = os.read(master_fd, 1024).decode("utf-8") |
| 112 |
if not data: |
| 113 |
break |
| 114 |
except OSError: |
| 115 |
break |
| 116 |
output.append(data) |
| 117 |
else: |
| 118 |
os.close(master_fd) |
| 119 |
process.kill() |
| 120 |
self.fail(f"Timeout while waiting for output, got: {''.join(output)}") |
| 121 |
|
| 122 |
os.close(master_fd) |
| 123 |
try: |
| 124 |
exit_code = process.wait(timeout=SHORT_TIMEOUT) |
| 125 |
except subprocess.TimeoutExpired: |
| 126 |
process.kill() |
| 127 |
exit_code = process.wait() |
| 128 |
output = "".join(output) |
| 129 |
if skip and "can't use pyrepl" in output: |
| 130 |
self.skipTest("pyrepl not available") |
| 131 |
return output, exit_code |
| 132 |
|
| 133 |
|
| 134 |
class TestCursorPosition(TestCase): |
| 135 |
def prepare_reader(self, events): |
| 136 |
console = FakeConsole(events) |
| 137 |
config = ReadlineConfig(readline_completer=None) |
| 138 |
reader = ReadlineAlikeReader(console=console, config=config) |
| 139 |
return reader |
| 140 |
|
| 141 |
def test_up_arrow_simple(self): |
| 142 |
# fmt: off |
| 143 |
code = ( |
| 144 |
"def f():\n" |
| 145 |
" ...\n" |
| 146 |
) |
| 147 |
# fmt: on |
| 148 |
events = itertools.chain( |
| 149 |
code_to_events(code), |
| 150 |
[ |
| 151 |
Event(evt="key", data="up", raw=bytearray(b"\x1bOA")), |
| 152 |
], |
| 153 |
) |
| 154 |
|
| 155 |
reader, console = handle_all_events(events) |
| 156 |
self.assertEqual(reader.cxy, (0, 1)) |
| 157 |
console.move_cursor.assert_called_once_with(0, 1) |
| 158 |
|
| 159 |
def test_down_arrow_end_of_input(self): |
| 160 |
# fmt: off |
| 161 |
code = ( |
| 162 |
"def f():\n" |
| 163 |
" ...\n" |
| 164 |
) |
| 165 |
# fmt: on |
| 166 |
events = itertools.chain( |
| 167 |
code_to_events(code), |
| 168 |
[ |
| 169 |
Event(evt="key", data="down", raw=bytearray(b"\x1bOB")), |
| 170 |
], |
| 171 |
) |
| 172 |
|
| 173 |
reader, console = handle_all_events(events) |
| 174 |
self.assertEqual(reader.cxy, (0, 2)) |
| 175 |
console.move_cursor.assert_called_once_with(0, 2) |
| 176 |
|
| 177 |
def test_left_arrow_simple(self): |
| 178 |
events = itertools.chain( |
| 179 |
code_to_events("11+11"), |
| 180 |
[ |
| 181 |
Event(evt="key", data="left", raw=bytearray(b"\x1bOD")), |
| 182 |
], |
| 183 |
) |
| 184 |
|
| 185 |
reader, console = handle_all_events(events) |
| 186 |
self.assertEqual(reader.cxy, (4, 0)) |
| 187 |
console.move_cursor.assert_called_once_with(4, 0) |
| 188 |
|
| 189 |
def test_right_arrow_end_of_line(self): |
| 190 |
events = itertools.chain( |
| 191 |
code_to_events("11+11"), |
| 192 |
[ |
| 193 |
Event(evt="key", data="right", raw=bytearray(b"\x1bOC")), |
| 194 |
], |
| 195 |
) |
| 196 |
|
| 197 |
reader, console = handle_all_events(events) |
| 198 |
self.assertEqual(reader.cxy, (5, 0)) |
| 199 |
console.move_cursor.assert_called_once_with(5, 0) |
| 200 |
|
| 201 |
def test_cursor_position_simple_character(self): |
| 202 |
events = itertools.chain(code_to_events("k")) |
| 203 |
|
| 204 |
reader, _ = handle_all_events(events) |
| 205 |
self.assertEqual(reader.pos, 1) |
| 206 |
|
| 207 |
# 1 for simple character |
| 208 |
self.assertEqual(reader.cxy, (1, 0)) |
| 209 |
|
| 210 |
def test_cursor_position_double_width_character(self): |
| 211 |
events = itertools.chain(code_to_events("樂")) |
| 212 |
|
| 213 |
reader, _ = handle_all_events(events) |
| 214 |
self.assertEqual(reader.pos, 1) |
| 215 |
|
| 216 |
# 2 for wide character |
| 217 |
self.assertEqual(reader.cxy, (2, 0)) |
| 218 |
|
| 219 |
def test_cursor_position_double_width_character_move_left(self): |
| 220 |
events = itertools.chain( |
| 221 |
code_to_events("樂"), |
| 222 |
[ |
| 223 |
Event(evt="key", data="left", raw=bytearray(b"\x1bOD")), |
| 224 |
], |
| 225 |
) |
| 226 |
|
| 227 |
reader, _ = handle_all_events(events) |
| 228 |
self.assertEqual(reader.pos, 0) |
| 229 |
self.assertEqual(reader.cxy, (0, 0)) |
| 230 |
|
| 231 |
def test_cursor_position_double_width_character_move_left_right(self): |
| 232 |
events = itertools.chain( |
| 233 |
code_to_events("樂"), |
| 234 |
[ |
| 235 |
Event(evt="key", data="left", raw=bytearray(b"\x1bOD")), |
| 236 |
Event(evt="key", data="right", raw=bytearray(b"\x1bOC")), |
| 237 |
], |
| 238 |
) |
| 239 |
|
| 240 |
reader, _ = handle_all_events(events) |
| 241 |
self.assertEqual(reader.pos, 1) |
| 242 |
|
| 243 |
# 2 for wide character |
| 244 |
self.assertEqual(reader.cxy, (2, 0)) |
| 245 |
|
| 246 |
def test_cursor_position_double_width_characters_move_up(self): |
| 247 |
for_loop = "for _ in _:" |
| 248 |
|
| 249 |
# fmt: off |
| 250 |
code = ( |
| 251 |
f"{for_loop}\n" |
| 252 |
" ' 可口可乐; 可口可樂'" |
| 253 |
) |
| 254 |
# fmt: on |
| 255 |
|
| 256 |
events = itertools.chain( |
| 257 |
code_to_events(code), |
| 258 |
[ |
| 259 |
Event(evt="key", data="up", raw=bytearray(b"\x1bOA")), |
| 260 |
], |
| 261 |
) |
| 262 |
|
| 263 |
reader, _ = handle_all_events(events) |
| 264 |
|
| 265 |
# cursor at end of first line |
| 266 |
self.assertEqual(reader.pos, len(for_loop)) |
| 267 |
self.assertEqual(reader.cxy, (len(for_loop), 0)) |
| 268 |
|
| 269 |
def test_cursor_position_double_width_characters_move_up_down(self): |
| 270 |
for_loop = "for _ in _:" |
| 271 |
|
| 272 |
# fmt: off |
| 273 |
code = ( |
| 274 |
f"{for_loop}\n" |
| 275 |
" ' 可口可乐; 可口可樂'" |
| 276 |
) |
| 277 |
# fmt: on |
| 278 |
|
| 279 |
events = itertools.chain( |
| 280 |
code_to_events(code), |
| 281 |
[ |
| 282 |
Event(evt="key", data="up", raw=bytearray(b"\x1bOA")), |
| 283 |
Event(evt="key", data="left", raw=bytearray(b"\x1bOD")), |
| 284 |
Event(evt="key", data="down", raw=bytearray(b"\x1bOB")), |
| 285 |
], |
| 286 |
) |
| 287 |
|
| 288 |
reader, _ = handle_all_events(events) |
| 289 |
|
| 290 |
# cursor here (showing 2nd line only): |
| 291 |
# < ' 可口可乐; 可口可樂'> |
| 292 |
# ^ |
| 293 |
self.assertEqual(reader.pos, 19) |
| 294 |
self.assertEqual(reader.cxy, (10, 1)) |
| 295 |
|
| 296 |
def test_cursor_position_multiple_double_width_characters_move_left(self): |
| 297 |
events = itertools.chain( |
| 298 |
code_to_events("' 可口可乐; 可口可樂'"), |
| 299 |
[ |
| 300 |
Event(evt="key", data="left", raw=bytearray(b"\x1bOD")), |
| 301 |
Event(evt="key", data="left", raw=bytearray(b"\x1bOD")), |
| 302 |
Event(evt="key", data="left", raw=bytearray(b"\x1bOD")), |
| 303 |
], |
| 304 |
) |
| 305 |
|
| 306 |
reader, _ = handle_all_events(events) |
| 307 |
self.assertEqual(reader.pos, 10) |
| 308 |
|
| 309 |
# 1 for quote, 1 for space, 2 per wide character, |
| 310 |
# 1 for semicolon, 1 for space, 2 per wide character |
| 311 |
self.assertEqual(reader.cxy, (16, 0)) |
| 312 |
|
| 313 |
def test_cursor_position_move_up_to_eol(self): |
| 314 |
first_line = "for _ in _:" |
| 315 |
second_line = " hello" |
| 316 |
|
| 317 |
# fmt: off |
| 318 |
code = ( |
| 319 |
f"{first_line}\n" |
| 320 |
f"{second_line}\n" |
| 321 |
" h\n" |
| 322 |
" hel" |
| 323 |
) |
| 324 |
# fmt: on |
| 325 |
|
| 326 |
events = itertools.chain( |
| 327 |
code_to_events(code), |
| 328 |
[ |
| 329 |
Event(evt="key", data="up", raw=bytearray(b"\x1bOA")), |
| 330 |
Event(evt="key", data="up", raw=bytearray(b"\x1bOA")), |
| 331 |
], |
| 332 |
) |
| 333 |
|
| 334 |
reader, _ = handle_all_events(events) |
| 335 |
|
| 336 |
# Cursor should be at end of line 1, even though line 2 is shorter |
| 337 |
# for _ in _: |
| 338 |
# hello |
| 339 |
# h |
| 340 |
# hel |
| 341 |
self.assertEqual( |
| 342 |
reader.pos, len(first_line) + len(second_line) + 1 |
| 343 |
) # +1 for newline |
| 344 |
self.assertEqual(reader.cxy, (len(second_line), 1)) |
| 345 |
|
| 346 |
def test_cursor_position_move_down_to_eol(self): |
| 347 |
last_line = " hel" |
| 348 |
|
| 349 |
# fmt: off |
| 350 |
code = ( |
| 351 |
"for _ in _:\n" |
| 352 |
" hello\n" |
| 353 |
" h\n" |
| 354 |
f"{last_line}" |
| 355 |
) |
| 356 |
# fmt: on |
| 357 |
|
| 358 |
events = itertools.chain( |
| 359 |
code_to_events(code), |
| 360 |
[ |
| 361 |
Event(evt="key", data="up", raw=bytearray(b"\x1bOA")), |
| 362 |
Event(evt="key", data="up", raw=bytearray(b"\x1bOA")), |
| 363 |
Event(evt="key", data="down", raw=bytearray(b"\x1bOB")), |
| 364 |
Event(evt="key", data="down", raw=bytearray(b"\x1bOB")), |
| 365 |
], |
| 366 |
) |
| 367 |
|
| 368 |
reader, _ = handle_all_events(events) |
| 369 |
|
| 370 |
# Cursor should be at end of line 3, even though line 2 is shorter |
| 371 |
# for _ in _: |
| 372 |
# hello |
| 373 |
# h |
| 374 |
# hel |
| 375 |
self.assertEqual(reader.pos, len(code)) |
| 376 |
self.assertEqual(reader.cxy, (len(last_line), 3)) |
| 377 |
|
| 378 |
def test_cursor_position_multiple_mixed_lines_move_up(self): |
| 379 |
# fmt: off |
| 380 |
code = ( |
| 381 |
"def foo():\n" |
| 382 |
" x = '可口可乐; 可口可樂'\n" |
| 383 |
" y = 'abckdfjskldfjslkdjf'" |
| 384 |
) |
| 385 |
# fmt: on |
| 386 |
|
| 387 |
events = itertools.chain( |
| 388 |
code_to_events(code), |
| 389 |
13 * [Event(evt="key", data="left", raw=bytearray(b"\x1bOD"))], |
| 390 |
[Event(evt="key", data="up", raw=bytearray(b"\x1bOA"))], |
| 391 |
) |
| 392 |
|
| 393 |
reader, _ = handle_all_events(events) |
| 394 |
|
| 395 |
# By moving left, we're before the s: |
| 396 |
# y = 'abckdfjskldfjslkdjf' |
| 397 |
# ^ |
| 398 |
# And we should move before the semi-colon despite the different offset |
| 399 |
# x = '可口可乐; 可口可樂' |
| 400 |
# ^ |
| 401 |
self.assertEqual(reader.pos, 22) |
| 402 |
self.assertEqual(reader.cxy, (15, 1)) |
| 403 |
|
| 404 |
def test_cursor_position_after_wrap_and_move_up(self): |
| 405 |
# fmt: off |
| 406 |
code = ( |
| 407 |
"def foo():\n" |
| 408 |
" hello" |
| 409 |
) |
| 410 |
# fmt: on |
| 411 |
|
| 412 |
events = itertools.chain( |
| 413 |
code_to_events(code), |
| 414 |
[ |
| 415 |
Event(evt="key", data="up", raw=bytearray(b"\x1bOA")), |
| 416 |
], |
| 417 |
) |
| 418 |
reader, _ = handle_events_narrow_console(events) |
| 419 |
|
| 420 |
# The code looks like this: |
| 421 |
# def foo()\ |
| 422 |
# : |
| 423 |
# hello |
| 424 |
# After moving up we should be after the colon in line 2 |
| 425 |
self.assertEqual(reader.pos, 10) |
| 426 |
self.assertEqual(reader.cxy, (1, 1)) |
| 427 |
|
| 428 |
|
| 429 |
class TestPyReplAutoindent(TestCase): |
| 430 |
def prepare_reader(self, events): |
| 431 |
console = FakeConsole(events) |
| 432 |
config = ReadlineConfig(readline_completer=None) |
| 433 |
reader = ReadlineAlikeReader(console=console, config=config) |
| 434 |
return reader |
| 435 |
|
| 436 |
def test_auto_indent_default(self): |
| 437 |
# fmt: off |
| 438 |
input_code = ( |
| 439 |
"def f():\n" |
| 440 |
"pass\n\n" |
| 441 |
) |
| 442 |
|
| 443 |
output_code = ( |
| 444 |
"def f():\n" |
| 445 |
" pass\n" |
| 446 |
" " |
| 447 |
) |
| 448 |
# fmt: on |
| 449 |
|
| 450 |
events = code_to_events(input_code) |
| 451 |
reader = self.prepare_reader(events) |
| 452 |
output = multiline_input(reader) |
| 453 |
self.assertEqual(output, output_code) |
| 454 |
|
| 455 |
def test_auto_indent_continuation(self): |
| 456 |
# auto indenting according to previous user indentation |
| 457 |
# fmt: off |
| 458 |
events = itertools.chain( |
| 459 |
code_to_events("def f():\n"), |
| 460 |
# add backspace to delete default auto-indent |
| 461 |
[ |
| 462 |
Event(evt="key", data="backspace", raw=bytearray(b"\x7f")), |
| 463 |
], |
| 464 |
code_to_events( |
| 465 |
" pass\n" |
| 466 |
"pass\n\n" |
| 467 |
), |
| 468 |
) |
| 469 |
|
| 470 |
output_code = ( |
| 471 |
"def f():\n" |
| 472 |
" pass\n" |
| 473 |
" pass\n" |
| 474 |
" " |
| 475 |
) |
| 476 |
# fmt: on |
| 477 |
|
| 478 |
reader = self.prepare_reader(events) |
| 479 |
output = multiline_input(reader) |
| 480 |
self.assertEqual(output, output_code) |
| 481 |
|
| 482 |
def test_auto_indent_prev_block(self): |
| 483 |
# auto indenting according to indentation in different block |
| 484 |
# fmt: off |
| 485 |
events = itertools.chain( |
| 486 |
code_to_events("def f():\n"), |
| 487 |
# add backspace to delete default auto-indent |
| 488 |
[ |
| 489 |
Event(evt="key", data="backspace", raw=bytearray(b"\x7f")), |
| 490 |
], |
| 491 |
code_to_events( |
| 492 |
" pass\n" |
| 493 |
"pass\n\n" |
| 494 |
), |
| 495 |
code_to_events( |
| 496 |
"def g():\n" |
| 497 |
"pass\n\n" |
| 498 |
), |
| 499 |
) |
| 500 |
|
| 501 |
output_code = ( |
| 502 |
"def g():\n" |
| 503 |
" pass\n" |
| 504 |
" " |
| 505 |
) |
| 506 |
# fmt: on |
| 507 |
|
| 508 |
reader = self.prepare_reader(events) |
| 509 |
output1 = multiline_input(reader) |
| 510 |
output2 = multiline_input(reader) |
| 511 |
self.assertEqual(output2, output_code) |
| 512 |
|
| 513 |
def test_auto_indent_multiline(self): |
| 514 |
# fmt: off |
| 515 |
events = itertools.chain( |
| 516 |
code_to_events( |
| 517 |
"def f():\n" |
| 518 |
"pass" |
| 519 |
), |
| 520 |
[ |
| 521 |
# go to the end of the first line |
| 522 |
Event(evt="key", data="up", raw=bytearray(b"\x1bOA")), |
| 523 |
Event(evt="key", data="\x05", raw=bytearray(b"\x1bO5")), |
| 524 |
# new line should be autoindented |
| 525 |
Event(evt="key", data="\n", raw=bytearray(b"\n")), |
| 526 |
], |
| 527 |
code_to_events( |
| 528 |
"pass" |
| 529 |
), |
| 530 |
[ |
| 531 |
# go to end of last line |
| 532 |
Event(evt="key", data="down", raw=bytearray(b"\x1bOB")), |
| 533 |
Event(evt="key", data="\x05", raw=bytearray(b"\x1bO5")), |
| 534 |
# double newline to terminate the block |
| 535 |
Event(evt="key", data="\n", raw=bytearray(b"\n")), |
| 536 |
Event(evt="key", data="\n", raw=bytearray(b"\n")), |
| 537 |
], |
| 538 |
) |
| 539 |
|
| 540 |
output_code = ( |
| 541 |
"def f():\n" |
| 542 |
" pass\n" |
| 543 |
" pass\n" |
| 544 |
" " |
| 545 |
) |
| 546 |
# fmt: on |
| 547 |
|
| 548 |
reader = self.prepare_reader(events) |
| 549 |
output = multiline_input(reader) |
| 550 |
self.assertEqual(output, output_code) |
| 551 |
|
| 552 |
def test_auto_indent_with_comment(self): |
| 553 |
# fmt: off |
| 554 |
events = code_to_events( |
| 555 |
"def f(): # foo\n" |
| 556 |
"pass\n\n" |
| 557 |
) |
| 558 |
|
| 559 |
output_code = ( |
| 560 |
"def f(): # foo\n" |
| 561 |
" pass\n" |
| 562 |
" " |
| 563 |
) |
| 564 |
# fmt: on |
| 565 |
|
| 566 |
reader = self.prepare_reader(events) |
| 567 |
output = multiline_input(reader) |
| 568 |
self.assertEqual(output, output_code) |
| 569 |
|
| 570 |
def test_auto_indent_with_multicomment(self): |
| 571 |
# fmt: off |
| 572 |
events = code_to_events( |
| 573 |
"def f(): ## foo\n" |
| 574 |
"pass\n\n" |
| 575 |
) |
| 576 |
|
| 577 |
output_code = ( |
| 578 |
"def f(): ## foo\n" |
| 579 |
" pass\n" |
| 580 |
" " |
| 581 |
) |
| 582 |
# fmt: on |
| 583 |
|
| 584 |
reader = self.prepare_reader(events) |
| 585 |
output = multiline_input(reader) |
| 586 |
self.assertEqual(output, output_code) |
| 587 |
|
| 588 |
def test_auto_indent_ignore_comments(self): |
| 589 |
# fmt: off |
| 590 |
events = code_to_events( |
| 591 |
"pass #:\n" |
| 592 |
) |
| 593 |
|
| 594 |
output_code = ( |
| 595 |
"pass #:" |
| 596 |
) |
| 597 |
# fmt: on |
| 598 |
|
| 599 |
reader = self.prepare_reader(events) |
| 600 |
output = multiline_input(reader) |
| 601 |
self.assertEqual(output, output_code) |
| 602 |
|
| 603 |
|
| 604 |
class TestPyReplOutput(ScreenEqualMixin, TestCase): |
| 605 |
def prepare_reader(self, events): |
| 606 |
console = FakeConsole(events) |
| 607 |
config = ReadlineConfig(readline_completer=None) |
| 608 |
reader = ReadlineAlikeReader(console=console, config=config) |
| 609 |
reader.can_colorize = False |
| 610 |
return reader |
| 611 |
|
| 612 |
def test_stdin_is_tty(self): |
| 613 |
# Used during test log analysis to figure out if a TTY was available. |
| 614 |
try: |
| 615 |
if os.isatty(sys.stdin.fileno()): |
| 616 |
return |
| 617 |
except OSError as ose: |
| 618 |
self.skipTest(f"stdin tty check failed: {ose}") |
| 619 |
else: |
| 620 |
self.skipTest("stdin is not a tty") |
| 621 |
|
| 622 |
def test_stdout_is_tty(self): |
| 623 |
# Used during test log analysis to figure out if a TTY was available. |
| 624 |
try: |
| 625 |
if os.isatty(sys.stdout.fileno()): |
| 626 |
return |
| 627 |
except OSError as ose: |
| 628 |
self.skipTest(f"stdout tty check failed: {ose}") |
| 629 |
else: |
| 630 |
self.skipTest("stdout is not a tty") |
| 631 |
|
| 632 |
def test_basic(self): |
| 633 |
reader = self.prepare_reader(code_to_events("1+1\n")) |
| 634 |
|
| 635 |
output = multiline_input(reader) |
| 636 |
self.assertEqual(output, "1+1") |
| 637 |
self.assert_screen_equal(reader, "1+1", clean=True) |
| 638 |
|
| 639 |
def test_get_line_buffer_returns_str(self): |
| 640 |
reader = self.prepare_reader(code_to_events("\n")) |
| 641 |
wrapper = _ReadlineWrapper(f_in=None, f_out=None, reader=reader) |
| 642 |
self.assertIs(type(wrapper.get_line_buffer()), str) |
| 643 |
|
| 644 |
def test_multiline_edit(self): |
| 645 |
events = itertools.chain( |
| 646 |
code_to_events("def f():\n...\n\n"), |
| 647 |
[ |
| 648 |
Event(evt="key", data="up", raw=bytearray(b"\x1bOA")), |
| 649 |
Event(evt="key", data="up", raw=bytearray(b"\x1bOA")), |
| 650 |
Event(evt="key", data="left", raw=bytearray(b"\x1bOD")), |
| 651 |
Event(evt="key", data="left", raw=bytearray(b"\x1bOD")), |
| 652 |
Event(evt="key", data="left", raw=bytearray(b"\x1bOD")), |
| 653 |
Event(evt="key", data="backspace", raw=bytearray(b"\x08")), |
| 654 |
Event(evt="key", data="g", raw=bytearray(b"g")), |
| 655 |
Event(evt="key", data="down", raw=bytearray(b"\x1bOB")), |
| 656 |
Event(evt="key", data="backspace", raw=bytearray(b"\x08")), |
| 657 |
Event(evt="key", data="delete", raw=bytearray(b"\x7F")), |
| 658 |
Event(evt="key", data="right", raw=bytearray(b"g")), |
| 659 |
Event(evt="key", data="backspace", raw=bytearray(b"\x08")), |
| 660 |
Event(evt="key", data="p", raw=bytearray(b"p")), |
| 661 |
Event(evt="key", data="a", raw=bytearray(b"a")), |
| 662 |
Event(evt="key", data="s", raw=bytearray(b"s")), |
| 663 |
Event(evt="key", data="s", raw=bytearray(b"s")), |
| 664 |
Event(evt="key", data="\n", raw=bytearray(b"\n")), |
| 665 |
Event(evt="key", data="\n", raw=bytearray(b"\n")), |
| 666 |
], |
| 667 |
) |
| 668 |
reader = self.prepare_reader(events) |
| 669 |
|
| 670 |
output = multiline_input(reader) |
| 671 |
expected = "def f():\n ...\n " |
| 672 |
self.assertEqual(output, expected) |
| 673 |
self.assert_screen_equal(reader, expected, clean=True) |
| 674 |
output = multiline_input(reader) |
| 675 |
expected = "def g():\n pass\n " |
| 676 |
self.assertEqual(output, expected) |
| 677 |
self.assert_screen_equal(reader, expected, clean=True) |
| 678 |
|
| 679 |
def test_history_navigation_with_up_arrow(self): |
| 680 |
events = itertools.chain( |
| 681 |
code_to_events("1+1\n2+2\n"), |
| 682 |
[ |
| 683 |
Event(evt="key", data="up", raw=bytearray(b"\x1bOA")), |
| 684 |
Event(evt="key", data="\n", raw=bytearray(b"\n")), |
| 685 |
Event(evt="key", data="up", raw=bytearray(b"\x1bOA")), |
| 686 |
Event(evt="key", data="up", raw=bytearray(b"\x1bOA")), |
| 687 |
Event(evt="key", data="up", raw=bytearray(b"\x1bOA")), |
| 688 |
Event(evt="key", data="\n", raw=bytearray(b"\n")), |
| 689 |
], |
| 690 |
) |
| 691 |
|
| 692 |
reader = self.prepare_reader(events) |
| 693 |
|
| 694 |
output = multiline_input(reader) |
| 695 |
self.assertEqual(output, "1+1") |
| 696 |
self.assert_screen_equal(reader, "1+1", clean=True) |
| 697 |
output = multiline_input(reader) |
| 698 |
self.assertEqual(output, "2+2") |
| 699 |
self.assert_screen_equal(reader, "2+2", clean=True) |
| 700 |
output = multiline_input(reader) |
| 701 |
self.assertEqual(output, "2+2") |
| 702 |
self.assert_screen_equal(reader, "2+2", clean=True) |
| 703 |
output = multiline_input(reader) |
| 704 |
self.assertEqual(output, "1+1") |
| 705 |
self.assert_screen_equal(reader, "1+1", clean=True) |
| 706 |
|
| 707 |
def test_history_with_multiline_entries(self): |
| 708 |
code = "def foo():\nx = 1\ny = 2\nz = 3\n\ndef bar():\nreturn 42\n\n" |
| 709 |
events = list(itertools.chain( |
| 710 |
code_to_events(code), |
| 711 |
[ |
| 712 |
Event(evt="key", data="up", raw=bytearray(b"\x1bOA")), |
| 713 |
Event(evt="key", data="up", raw=bytearray(b"\x1bOA")), |
| 714 |
Event(evt="key", data="up", raw=bytearray(b"\x1bOA")), |
| 715 |
Event(evt="key", data="\n", raw=bytearray(b"\n")), |
| 716 |
Event(evt="key", data="\n", raw=bytearray(b"\n")), |
| 717 |
] |
| 718 |
)) |
| 719 |
|
| 720 |
reader = self.prepare_reader(events) |
| 721 |
output = multiline_input(reader) |
| 722 |
output = multiline_input(reader) |
| 723 |
output = multiline_input(reader) |
| 724 |
expected = "def foo():\n x = 1\n y = 2\n z = 3\n " |
| 725 |
self.assert_screen_equal(reader, expected, clean=True) |
| 726 |
self.assertEqual(output, expected) |
| 727 |
|
| 728 |
|
| 729 |
def test_history_navigation_with_down_arrow(self): |
| 730 |
events = itertools.chain( |
| 731 |
code_to_events("1+1\n2+2\n"), |
| 732 |
[ |
| 733 |
Event(evt="key", data="up", raw=bytearray(b"\x1bOA")), |
| 734 |
Event(evt="key", data="up", raw=bytearray(b"\x1bOA")), |
| 735 |
Event(evt="key", data="\n", raw=bytearray(b"\n")), |
| 736 |
Event(evt="key", data="down", raw=bytearray(b"\x1bOB")), |
| 737 |
Event(evt="key", data="down", raw=bytearray(b"\x1bOB")), |
| 738 |
], |
| 739 |
) |
| 740 |
|
| 741 |
reader = self.prepare_reader(events) |
| 742 |
|
| 743 |
output = multiline_input(reader) |
| 744 |
self.assertEqual(output, "1+1") |
| 745 |
self.assert_screen_equal(reader, "1+1", clean=True) |
| 746 |
|
| 747 |
def test_history_search(self): |
| 748 |
events = itertools.chain( |
| 749 |
code_to_events("1+1\n2+2\n3+3\n"), |
| 750 |
[ |
| 751 |
Event(evt="key", data="\x12", raw=bytearray(b"\x12")), |
| 752 |
Event(evt="key", data="1", raw=bytearray(b"1")), |
| 753 |
Event(evt="key", data="\n", raw=bytearray(b"\n")), |
| 754 |
Event(evt="key", data="\n", raw=bytearray(b"\n")), |
| 755 |
], |
| 756 |
) |
| 757 |
|
| 758 |
reader = self.prepare_reader(events) |
| 759 |
|
| 760 |
output = multiline_input(reader) |
| 761 |
self.assertEqual(output, "1+1") |
| 762 |
self.assert_screen_equal(reader, "1+1", clean=True) |
| 763 |
output = multiline_input(reader) |
| 764 |
self.assertEqual(output, "2+2") |
| 765 |
self.assert_screen_equal(reader, "2+2", clean=True) |
| 766 |
output = multiline_input(reader) |
| 767 |
self.assertEqual(output, "3+3") |
| 768 |
self.assert_screen_equal(reader, "3+3", clean=True) |
| 769 |
output = multiline_input(reader) |
| 770 |
self.assertEqual(output, "1+1") |
| 771 |
self.assert_screen_equal(reader, "1+1", clean=True) |
| 772 |
|
| 773 |
def test_control_character(self): |
| 774 |
events = code_to_events("c\x1d\n") |
| 775 |
reader = self.prepare_reader(events) |
| 776 |
output = multiline_input(reader) |
| 777 |
self.assertEqual(output, "c\x1d") |
| 778 |
self.assert_screen_equal(reader, "c\x1d", clean=True) |
| 779 |
|
| 780 |
def test_history_search_backward(self): |
| 781 |
# Test <page up> history search backward with "imp" input |
| 782 |
events = itertools.chain( |
| 783 |
code_to_events("import os\n"), |
| 784 |
code_to_events("imp"), |
| 785 |
[ |
| 786 |
Event(evt='key', data='page up', raw=bytearray(b'\x1b[5~')), |
| 787 |
Event(evt="key", data="\n", raw=bytearray(b"\n")), |
| 788 |
], |
| 789 |
) |
| 790 |
|
| 791 |
# fill the history |
| 792 |
reader = self.prepare_reader(events) |
| 793 |
multiline_input(reader) |
| 794 |
|
| 795 |
# search for "imp" in history |
| 796 |
output = multiline_input(reader) |
| 797 |
self.assertEqual(output, "import os") |
| 798 |
self.assert_screen_equal(reader, "import os", clean=True) |
| 799 |
|
| 800 |
def test_history_search_backward_empty(self): |
| 801 |
# Test <page up> history search backward with an empty input |
| 802 |
events = itertools.chain( |
| 803 |
code_to_events("import os\n"), |
| 804 |
[ |
| 805 |
Event(evt='key', data='page up', raw=bytearray(b'\x1b[5~')), |
| 806 |
Event(evt="key", data="\n", raw=bytearray(b"\n")), |
| 807 |
], |
| 808 |
) |
| 809 |
|
| 810 |
# fill the history |
| 811 |
reader = self.prepare_reader(events) |
| 812 |
multiline_input(reader) |
| 813 |
|
| 814 |
# search backward in history |
| 815 |
output = multiline_input(reader) |
| 816 |
self.assertEqual(output, "import os") |
| 817 |
self.assert_screen_equal(reader, "import os", clean=True) |
| 818 |
|
| 819 |
|
| 820 |
class TestPyReplCompleter(TestCase): |
| 821 |
def prepare_reader(self, events, namespace): |
| 822 |
console = FakeConsole(events) |
| 823 |
config = ReadlineConfig() |
| 824 |
config.readline_completer = rlcompleter.Completer(namespace).complete |
| 825 |
reader = ReadlineAlikeReader(console=console, config=config) |
| 826 |
return reader |
| 827 |
|
| 828 |
@patch("rlcompleter._readline_available", False) |
| 829 |
def test_simple_completion(self): |
| 830 |
events = code_to_events("os.getpid\t\n") |
| 831 |
|
| 832 |
namespace = {"os": os} |
| 833 |
reader = self.prepare_reader(events, namespace) |
| 834 |
|
| 835 |
output = multiline_input(reader, namespace) |
| 836 |
self.assertEqual(output, "os.getpid()") |
| 837 |
|
| 838 |
def test_completion_with_many_options(self): |
| 839 |
# Test with something that initially displays many options |
| 840 |
# and then complete from one of them. The first time tab is |
| 841 |
# pressed, the options are displayed (which corresponds to |
| 842 |
# when the repl shows [ not unique ]) and the second completes |
| 843 |
# from one of them. |
| 844 |
events = code_to_events("os.\t\tO_AP\t\n") |
| 845 |
|
| 846 |
namespace = {"os": os} |
| 847 |
reader = self.prepare_reader(events, namespace) |
| 848 |
|
| 849 |
output = multiline_input(reader, namespace) |
| 850 |
self.assertEqual(output, "os.O_APPEND") |
| 851 |
|
| 852 |
def test_empty_namespace_completion(self): |
| 853 |
events = code_to_events("os.geten\t\n") |
| 854 |
namespace = {} |
| 855 |
reader = self.prepare_reader(events, namespace) |
| 856 |
|
| 857 |
output = multiline_input(reader, namespace) |
| 858 |
self.assertEqual(output, "os.geten") |
| 859 |
|
| 860 |
def test_global_namespace_completion(self): |
| 861 |
events = code_to_events("py\t\n") |
| 862 |
namespace = {"python": None} |
| 863 |
reader = self.prepare_reader(events, namespace) |
| 864 |
output = multiline_input(reader, namespace) |
| 865 |
self.assertEqual(output, "python") |
| 866 |
|
| 867 |
def test_up_down_arrow_with_completion_menu(self): |
| 868 |
"""Up arrow in the middle of unfinished tab completion when the menu is displayed |
| 869 |
should work and trigger going back in history. Down arrow should subsequently |
| 870 |
get us back to the incomplete command.""" |
| 871 |
code = "import os\nos.\t\t" |
| 872 |
namespace = {"os": os} |
| 873 |
|
| 874 |
events = itertools.chain( |
| 875 |
code_to_events(code), |
| 876 |
[ |
| 877 |
Event(evt="key", data="down", raw=bytearray(b"\x1bOB")), |
| 878 |
Event(evt="key", data="up", raw=bytearray(b"\x1bOA")), |
| 879 |
Event(evt="key", data="down", raw=bytearray(b"\x1bOB")), |
| 880 |
], |
| 881 |
code_to_events("\n"), |
| 882 |
) |
| 883 |
reader = self.prepare_reader(events, namespace=namespace) |
| 884 |
output = multiline_input(reader, namespace) |
| 885 |
# This is the first line, nothing to see here |
| 886 |
self.assertEqual(output, "import os") |
| 887 |
# This is the second line. We pressed up and down arrows |
| 888 |
# so we should end up where we were when we initiated tab completion. |
| 889 |
output = multiline_input(reader, namespace) |
| 890 |
self.assertEqual(output, "os.") |
| 891 |
|
| 892 |
@patch("_pyrepl.readline._ReadlineWrapper.get_reader") |
| 893 |
@patch("sys.stderr", new_callable=io.StringIO) |
| 894 |
def test_completion_with_warnings(self, mock_stderr, mock_get_reader): |
| 895 |
class Dummy: |
| 896 |
@property |
| 897 |
def test_func(self): |
| 898 |
import warnings |
| 899 |
|
| 900 |
warnings.warn("warnings\n") |
| 901 |
return None |
| 902 |
|
| 903 |
dummy = Dummy() |
| 904 |
events = code_to_events("dummy.test_func.\t\n\n") |
| 905 |
namespace = {"dummy": dummy} |
| 906 |
reader = self.prepare_reader(events, namespace) |
| 907 |
mock_get_reader.return_value = reader |
| 908 |
output = readline_multiline_input(more_lines, ">>>", "...") |
| 909 |
self.assertEqual(output, "dummy.test_func.__") |
| 910 |
self.assertEqual(mock_stderr.getvalue(), "") |
| 911 |
|
| 912 |
|
| 913 |
class TestPasteEvent(TestCase): |
| 914 |
def prepare_reader(self, events): |
| 915 |
console = FakeConsole(events) |
| 916 |
config = ReadlineConfig(readline_completer=None) |
| 917 |
reader = ReadlineAlikeReader(console=console, config=config) |
| 918 |
return reader |
| 919 |
|
| 920 |
def test_paste(self): |
| 921 |
# fmt: off |
| 922 |
code = ( |
| 923 |
"def a():\n" |
| 924 |
" for x in range(10):\n" |
| 925 |
" if x%2:\n" |
| 926 |
" print(x)\n" |
| 927 |
" else:\n" |
| 928 |
" pass\n" |
| 929 |
) |
| 930 |
# fmt: on |
| 931 |
|
| 932 |
events = itertools.chain( |
| 933 |
[ |
| 934 |
Event(evt="key", data="f3", raw=bytearray(b"\x1bOR")), |
| 935 |
], |
| 936 |
code_to_events(code), |
| 937 |
[ |
| 938 |
Event(evt="key", data="f3", raw=bytearray(b"\x1bOR")), |
| 939 |
], |
| 940 |
code_to_events("\n"), |
| 941 |
) |
| 942 |
reader = self.prepare_reader(events) |
| 943 |
output = multiline_input(reader) |
| 944 |
self.assertEqual(output, code) |
| 945 |
|
| 946 |
def test_paste_mid_newlines(self): |
| 947 |
# fmt: off |
| 948 |
code = ( |
| 949 |
"def f():\n" |
| 950 |
" x = y\n" |
| 951 |
" \n" |
| 952 |
" y = z\n" |
| 953 |
) |
| 954 |
# fmt: on |
| 955 |
|
| 956 |
events = itertools.chain( |
| 957 |
[ |
| 958 |
Event(evt="key", data="f3", raw=bytearray(b"\x1bOR")), |
| 959 |
], |
| 960 |
code_to_events(code), |
| 961 |
[ |
| 962 |
Event(evt="key", data="f3", raw=bytearray(b"\x1bOR")), |
| 963 |
], |
| 964 |
code_to_events("\n"), |
| 965 |
) |
| 966 |
reader = self.prepare_reader(events) |
| 967 |
output = multiline_input(reader) |
| 968 |
self.assertEqual(output, code) |
| 969 |
|
| 970 |
def test_paste_mid_newlines_not_in_paste_mode(self): |
| 971 |
# fmt: off |
| 972 |
code = ( |
| 973 |
"def f():\n" |
| 974 |
"x = y\n" |
| 975 |
"\n" |
| 976 |
"y = z\n\n" |
| 977 |
) |
| 978 |
|
| 979 |
expected = ( |
| 980 |
"def f():\n" |
| 981 |
" x = y\n" |
| 982 |
" " |
| 983 |
) |
| 984 |
# fmt: on |
| 985 |
|
| 986 |
events = code_to_events(code) |
| 987 |
reader = self.prepare_reader(events) |
| 988 |
output = multiline_input(reader) |
| 989 |
self.assertEqual(output, expected) |
| 990 |
|
| 991 |
def test_paste_not_in_paste_mode(self): |
| 992 |
# fmt: off |
| 993 |
input_code = ( |
| 994 |
"def a():\n" |
| 995 |
"for x in range(10):\n" |
| 996 |
"if x%2:\n" |
| 997 |
"print(x)\n" |
| 998 |
"else:\n" |
| 999 |
"pass\n\n" |
| 1000 |
) |
| 1001 |
|
| 1002 |
output_code = ( |
| 1003 |
"def a():\n" |
| 1004 |
" for x in range(10):\n" |
| 1005 |
" if x%2:\n" |
| 1006 |
" print(x)\n" |
| 1007 |
" else:" |
| 1008 |
) |
| 1009 |
# fmt: on |
| 1010 |
|
| 1011 |
events = code_to_events(input_code) |
| 1012 |
reader = self.prepare_reader(events) |
| 1013 |
output = multiline_input(reader) |
| 1014 |
self.assertEqual(output, output_code) |
| 1015 |
|
| 1016 |
def test_bracketed_paste(self): |
| 1017 |
"""Test that bracketed paste using \x1b[200~ and \x1b[201~ works.""" |
| 1018 |
# fmt: off |
| 1019 |
input_code = ( |
| 1020 |
"def a():\n" |
| 1021 |
" for x in range(10):\n" |
| 1022 |
"\n" |
| 1023 |
" if x%2:\n" |
| 1024 |
" print(x)\n" |
| 1025 |
"\n" |
| 1026 |
" else:\n" |
| 1027 |
" pass\n" |
| 1028 |
) |
| 1029 |
|
| 1030 |
output_code = ( |
| 1031 |
"def a():\n" |
| 1032 |
" for x in range(10):\n" |
| 1033 |
"\n" |
| 1034 |
" if x%2:\n" |
| 1035 |
" print(x)\n" |
| 1036 |
"\n" |
| 1037 |
" else:\n" |
| 1038 |
" pass\n" |
| 1039 |
) |
| 1040 |
# fmt: on |
| 1041 |
|
| 1042 |
paste_start = "\x1b[200~" |
| 1043 |
paste_end = "\x1b[201~" |
| 1044 |
|
| 1045 |
events = itertools.chain( |
| 1046 |
code_to_events(paste_start), |
| 1047 |
code_to_events(input_code), |
| 1048 |
code_to_events(paste_end), |
| 1049 |
code_to_events("\n"), |
| 1050 |
) |
| 1051 |
reader = self.prepare_reader(events) |
| 1052 |
output = multiline_input(reader) |
| 1053 |
self.assertEqual(output, output_code) |
| 1054 |
|
| 1055 |
def test_bracketed_paste_single_line(self): |
| 1056 |
input_code = "oneline" |
| 1057 |
|
| 1058 |
paste_start = "\x1b[200~" |
| 1059 |
paste_end = "\x1b[201~" |
| 1060 |
|
| 1061 |
events = itertools.chain( |
| 1062 |
code_to_events(paste_start), |
| 1063 |
code_to_events(input_code), |
| 1064 |
code_to_events(paste_end), |
| 1065 |
code_to_events("\n"), |
| 1066 |
) |
| 1067 |
reader = self.prepare_reader(events) |
| 1068 |
output = multiline_input(reader) |
| 1069 |
self.assertEqual(output, input_code) |
| 1070 |
|
| 1071 |
|
| 1072 |
@skipUnless(pty, "requires pty") |
| 1073 |
class TestDumbTerminal(ReplTestCase): |
| 1074 |
def test_dumb_terminal_exits_cleanly(self): |
| 1075 |
env = os.environ.copy() |
| 1076 |
# Ignore PYTHONSTARTUP to not pollute the output |
| 1077 |
# with an unrelated traceback. See GH-137568. |
| 1078 |
env.pop('PYTHONSTARTUP', None) |
| 1079 |
env.update({"TERM": "dumb"}) |
| 1080 |
output, exit_code = self.run_repl("exit()\n", env=env) |
| 1081 |
self.assertEqual(exit_code, 0) |
| 1082 |
self.assertIn("warning: can't use pyrepl", output) |
| 1083 |
self.assertNotIn("Exception", output) |
| 1084 |
self.assertNotIn("Traceback", output) |
| 1085 |
|
| 1086 |
|
| 1087 |
@skipUnless(pty, "requires pty") |
| 1088 |
@skipIf((os.environ.get("TERM") or "dumb") == "dumb", "can't use pyrepl in dumb terminal") |
| 1089 |
class TestMain(ReplTestCase): |
| 1090 |
def setUp(self): |
| 1091 |
# Cleanup from PYTHON* variables to isolate from local |
| 1092 |
# user settings, see #121359. Such variables should be |
| 1093 |
# added later in test methods to patched os.environ. |
| 1094 |
patcher = patch('os.environ', new=make_clean_env()) |
| 1095 |
self.addCleanup(patcher.stop) |
| 1096 |
patcher.start() |
| 1097 |
|
| 1098 |
@force_not_colorized |
| 1099 |
def test_exposed_globals_in_repl(self): |
| 1100 |
pre = "['__annotations__', '__builtins__'" |
| 1101 |
post = "'__loader__', '__name__', '__package__', '__spec__']" |
| 1102 |
output, exit_code = self.run_repl(["sorted(dir())", "exit()"], skip=True) |
| 1103 |
self.assertEqual(exit_code, 0) |
| 1104 |
|
| 1105 |
# if `__main__` is not a file (impossible with pyrepl) |
| 1106 |
case1 = f"{pre}, '__doc__', {post}" in output |
| 1107 |
|
| 1108 |
# if `__main__` is an uncached .py file (no .pyc) |
| 1109 |
case2 = f"{pre}, '__doc__', '__file__', {post}" in output |
| 1110 |
|
| 1111 |
# if `__main__` is a cached .pyc file and the .py source exists |
| 1112 |
case3 = f"{pre}, '__cached__', '__doc__', '__file__', {post}" in output |
| 1113 |
|
| 1114 |
# if `__main__` is a cached .pyc file but there's no .py source file |
| 1115 |
case4 = f"{pre}, '__cached__', '__doc__', {post}" in output |
| 1116 |
|
| 1117 |
self.assertTrue(case1 or case2 or case3 or case4, output) |
| 1118 |
|
| 1119 |
def _assertMatchOK( |
| 1120 |
self, var: str, expected: str | re.Pattern, actual: str |
| 1121 |
) -> None: |
| 1122 |
if isinstance(expected, re.Pattern): |
| 1123 |
self.assertTrue( |
| 1124 |
expected.match(actual), |
| 1125 |
f"{var}={actual} does not match {expected.pattern}", |
| 1126 |
) |
| 1127 |
else: |
| 1128 |
self.assertEqual( |
| 1129 |
actual, |
| 1130 |
expected, |
| 1131 |
f"expected {var}={expected}, got {var}={actual}", |
| 1132 |
) |
| 1133 |
|
| 1134 |
@force_not_colorized |
| 1135 |
def _run_repl_globals_test(self, expectations, *, as_file=False, as_module=False): |
| 1136 |
clean_env = make_clean_env() |
| 1137 |
clean_env["NO_COLOR"] = "1" # force_not_colorized doesn't touch subprocesses |
| 1138 |
|
| 1139 |
with tempfile.TemporaryDirectory() as td: |
| 1140 |
blue = pathlib.Path(td) / "blue" |
| 1141 |
blue.mkdir() |
| 1142 |
mod = blue / "calx.py" |
| 1143 |
mod.write_text("FOO = 42", encoding="utf-8") |
| 1144 |
commands = [ |
| 1145 |
"print(f'^{" + var + "=}')" for var in expectations |
| 1146 |
] + ["exit()"] |
| 1147 |
if as_file and as_module: |
| 1148 |
self.fail("as_file and as_module are mutually exclusive") |
| 1149 |
elif as_file: |
| 1150 |
output, exit_code = self.run_repl( |
| 1151 |
commands, |
| 1152 |
cmdline_args=[str(mod)], |
| 1153 |
env=clean_env, |
| 1154 |
skip=True, |
| 1155 |
) |
| 1156 |
elif as_module: |
| 1157 |
output, exit_code = self.run_repl( |
| 1158 |
commands, |
| 1159 |
cmdline_args=["-m", "blue.calx"], |
| 1160 |
env=clean_env, |
| 1161 |
cwd=td, |
| 1162 |
skip=True, |
| 1163 |
) |
| 1164 |
else: |
| 1165 |
self.fail("Choose one of as_file or as_module") |
| 1166 |
|
| 1167 |
self.assertEqual(exit_code, 0) |
| 1168 |
for var, expected in expectations.items(): |
| 1169 |
with self.subTest(var=var, expected=expected): |
| 1170 |
if m := re.search(rf"\^{var}=(.+?)[\r\n]", output): |
| 1171 |
self._assertMatchOK(var, expected, actual=m.group(1)) |
| 1172 |
else: |
| 1173 |
self.fail(f"{var}= not found in output: {output!r}\n\n{output}") |
| 1174 |
|
| 1175 |
self.assertNotIn("Exception", output) |
| 1176 |
self.assertNotIn("Traceback", output) |
| 1177 |
|
| 1178 |
def test_inspect_keeps_globals_from_inspected_file(self): |
| 1179 |
expectations = { |
| 1180 |
"FOO": "42", |
| 1181 |
"__name__": "'__main__'", |
| 1182 |
"__package__": "None", |
| 1183 |
# "__file__" is missing in -i, like in the basic REPL |
| 1184 |
} |
| 1185 |
self._run_repl_globals_test(expectations, as_file=True) |
| 1186 |
|
| 1187 |
def test_inspect_keeps_globals_from_inspected_module(self): |
| 1188 |
expectations = { |
| 1189 |
"FOO": "42", |
| 1190 |
"__name__": "'__main__'", |
| 1191 |
"__package__": "'blue'", |
| 1192 |
"__file__": re.compile(r"^'.*calx.py'$"), |
| 1193 |
} |
| 1194 |
self._run_repl_globals_test(expectations, as_module=True) |
| 1195 |
|
| 1196 |
@force_not_colorized |
| 1197 |
def test_python_basic_repl(self): |
| 1198 |
env = os.environ.copy() |
| 1199 |
commands = ("from test.support import initialized_with_pyrepl\n" |
| 1200 |
"initialized_with_pyrepl()\n" |
| 1201 |
"exit()\n") |
| 1202 |
|
| 1203 |
env.pop("PYTHON_BASIC_REPL", None) |
| 1204 |
output, exit_code = self.run_repl(commands, env=env, skip=True) |
| 1205 |
self.assertEqual(exit_code, 0) |
| 1206 |
self.assertIn("True", output) |
| 1207 |
self.assertNotIn("False", output) |
| 1208 |
self.assertNotIn("Exception", output) |
| 1209 |
self.assertNotIn("Traceback", output) |
| 1210 |
|
| 1211 |
env["PYTHON_BASIC_REPL"] = "1" |
| 1212 |
output, exit_code = self.run_repl(commands, env=env) |
| 1213 |
self.assertEqual(exit_code, 0) |
| 1214 |
self.assertIn("False", output) |
| 1215 |
self.assertNotIn("True", output) |
| 1216 |
self.assertNotIn("Exception", output) |
| 1217 |
self.assertNotIn("Traceback", output) |
| 1218 |
|
| 1219 |
# The site module must not load _pyrepl if PYTHON_BASIC_REPL is set |
| 1220 |
commands = ("import sys\n" |
| 1221 |
"print('_pyrepl' in sys.modules)\n" |
| 1222 |
"exit()\n") |
| 1223 |
env["PYTHON_BASIC_REPL"] = "1" |
| 1224 |
output, exit_code = self.run_repl(commands, env=env) |
| 1225 |
self.assertEqual(exit_code, 0) |
| 1226 |
self.assertIn("False", output) |
| 1227 |
self.assertNotIn("True", output) |
| 1228 |
self.assertNotIn("Exception", output) |
| 1229 |
self.assertNotIn("Traceback", output) |
| 1230 |
|
| 1231 |
@force_not_colorized |
| 1232 |
def test_no_pyrepl_source_in_exc(self): |
| 1233 |
# Avoid using _pyrepl/__main__.py in traceback reports |
| 1234 |
# See https://github.com/python/cpython/issues/129098. |
| 1235 |
pyrepl_main_file = os.path.join(STDLIB_DIR, "_pyrepl", "__main__.py") |
| 1236 |
self.assertTrue(os.path.exists(pyrepl_main_file), pyrepl_main_file) |
| 1237 |
with open(pyrepl_main_file) as fp: |
| 1238 |
excluded_lines = fp.readlines() |
| 1239 |
excluded_lines = list(filter(None, map(str.strip, excluded_lines))) |
| 1240 |
|
| 1241 |
for filename in ['?', 'unknown-filename', '<foo>', '<...>']: |
| 1242 |
self._test_no_pyrepl_source_in_exc(filename, excluded_lines) |
| 1243 |
|
| 1244 |
def _test_no_pyrepl_source_in_exc(self, filename, excluded_lines): |
| 1245 |
with EnvironmentVarGuard() as env, self.subTest(filename=filename): |
| 1246 |
env.unset("PYTHON_BASIC_REPL") |
| 1247 |
commands = (f"eval(compile('spam', {filename!r}, 'eval'))\n" |
| 1248 |
f"exit()\n") |
| 1249 |
output, _ = self.run_repl(commands, env=env) |
| 1250 |
self.assertIn("Traceback (most recent call last)", output) |
| 1251 |
self.assertIn("NameError: name 'spam' is not defined", output) |
| 1252 |
for line in excluded_lines: |
| 1253 |
with self.subTest(line=line): |
| 1254 |
self.assertNotIn(line, output) |
| 1255 |
|
| 1256 |
@force_not_colorized |
| 1257 |
def test_bad_sys_excepthook_doesnt_crash_pyrepl(self): |
| 1258 |
env = os.environ.copy() |
| 1259 |
commands = ("import sys\n" |
| 1260 |
"sys.excepthook = 1\n" |
| 1261 |
"1/0\n" |
| 1262 |
"exit()\n") |
| 1263 |
|
| 1264 |
def check(output, exitcode): |
| 1265 |
self.assertIn("Error in sys.excepthook:", output) |
| 1266 |
self.assertEqual(output.count("'int' object is not callable"), 1) |
| 1267 |
self.assertIn("Original exception was:", output) |
| 1268 |
self.assertIn("division by zero", output) |
| 1269 |
self.assertEqual(exitcode, 0) |
| 1270 |
env.pop("PYTHON_BASIC_REPL", None) |
| 1271 |
output, exit_code = self.run_repl(commands, env=env, skip=True) |
| 1272 |
check(output, exit_code) |
| 1273 |
|
| 1274 |
env["PYTHON_BASIC_REPL"] = "1" |
| 1275 |
output, exit_code = self.run_repl(commands, env=env) |
| 1276 |
check(output, exit_code) |
| 1277 |
|
| 1278 |
def test_not_wiping_history_file(self): |
| 1279 |
# skip, if readline module is not available |
| 1280 |
import_module('readline') |
| 1281 |
|
| 1282 |
hfile = tempfile.NamedTemporaryFile(delete=False) |
| 1283 |
self.addCleanup(unlink, hfile.name) |
| 1284 |
env = os.environ.copy() |
| 1285 |
env["PYTHON_HISTORY"] = hfile.name |
| 1286 |
commands = "123\nspam\nexit()\n" |
| 1287 |
|
| 1288 |
env.pop("PYTHON_BASIC_REPL", None) |
| 1289 |
output, exit_code = self.run_repl(commands, env=env) |
| 1290 |
self.assertEqual(exit_code, 0) |
| 1291 |
self.assertIn("123", output) |
| 1292 |
self.assertIn("spam", output) |
| 1293 |
self.assertNotEqual(pathlib.Path(hfile.name).stat().st_size, 0) |
| 1294 |
|
| 1295 |
hfile.file.truncate() |
| 1296 |
hfile.close() |
| 1297 |
|
| 1298 |
env["PYTHON_BASIC_REPL"] = "1" |
| 1299 |
output, exit_code = self.run_repl(commands, env=env) |
| 1300 |
self.assertEqual(exit_code, 0) |
| 1301 |
self.assertIn("123", output) |
| 1302 |
self.assertIn("spam", output) |
| 1303 |
self.assertNotEqual(pathlib.Path(hfile.name).stat().st_size, 0) |
| 1304 |
|
| 1305 |
@force_not_colorized |
| 1306 |
def test_correct_filename_in_syntaxerrors(self): |
| 1307 |
env = os.environ.copy() |
| 1308 |
commands = "a b c\nexit()\n" |
| 1309 |
output, exit_code = self.run_repl(commands, env=env, skip=True) |
| 1310 |
self.assertIn("SyntaxError: invalid syntax", output) |
| 1311 |
self.assertIn("<python-input-0>", output) |
| 1312 |
commands = " b\nexit()\n" |
| 1313 |
output, exit_code = self.run_repl(commands, env=env) |
| 1314 |
self.assertIn("IndentationError: unexpected indent", output) |
| 1315 |
self.assertIn("<python-input-0>", output) |
| 1316 |
|
| 1317 |
@force_not_colorized |
| 1318 |
def test_proper_tracebacklimit(self): |
| 1319 |
env = os.environ.copy() |
| 1320 |
for set_tracebacklimit in [True, False]: |
| 1321 |
commands = ("import sys\n" + |
| 1322 |
("sys.tracebacklimit = 1\n" if set_tracebacklimit else "") + |
| 1323 |
"def x1(): 1/0\n\n" |
| 1324 |
"def x2(): x1()\n\n" |
| 1325 |
"def x3(): x2()\n\n" |
| 1326 |
"x3()\n" |
| 1327 |
"exit()\n") |
| 1328 |
|
| 1329 |
for basic_repl in [True, False]: |
| 1330 |
if basic_repl: |
| 1331 |
env["PYTHON_BASIC_REPL"] = "1" |
| 1332 |
else: |
| 1333 |
env.pop("PYTHON_BASIC_REPL", None) |
| 1334 |
with self.subTest(set_tracebacklimit=set_tracebacklimit, |
| 1335 |
basic_repl=basic_repl): |
| 1336 |
output, exit_code = self.run_repl(commands, env=env, skip=True) |
| 1337 |
self.assertIn("in x1", output) |
| 1338 |
if set_tracebacklimit: |
| 1339 |
self.assertNotIn("in x2", output) |
| 1340 |
self.assertNotIn("in x3", output) |
| 1341 |
self.assertNotIn("in <module>", output) |
| 1342 |
else: |
| 1343 |
self.assertIn("in x2", output) |
| 1344 |
self.assertIn("in x3", output) |
| 1345 |
self.assertIn("in <module>", output) |
| 1346 |
|
| 1347 |
def test_null_byte(self): |
| 1348 |
output, exit_code = self.run_repl("\x00\nexit()\n") |
| 1349 |
self.assertEqual(exit_code, 0) |
| 1350 |
self.assertNotIn("TypeError", output) |
| 1351 |
|
| 1352 |
@force_not_colorized |
| 1353 |
def test_non_string_suggestion_candidates(self): |
| 1354 |
commands = ("import runpy\n" |
| 1355 |
"runpy._run_module_code('blech', {0: '', 'bluch': ''}, '')\n" |
| 1356 |
"exit()\n") |
| 1357 |
|
| 1358 |
output, exit_code = self.run_repl(commands) |
| 1359 |
self.assertEqual(exit_code, 0) |
| 1360 |
self.assertNotIn("all elements in 'candidates' must be strings", output) |
| 1361 |
self.assertIn("bluch", output) |
| 1362 |
|
| 1363 |
def test_readline_history_file(self): |
| 1364 |
# skip, if readline module is not available |
| 1365 |
readline = import_module('readline') |
| 1366 |
if readline.backend != "editline": |
| 1367 |
self.skipTest("GNU readline is not affected by this issue") |
| 1368 |
|
| 1369 |
with tempfile.NamedTemporaryFile() as hfile: |
| 1370 |
env = os.environ.copy() |
| 1371 |
env["PYTHON_HISTORY"] = hfile.name |
| 1372 |
|
| 1373 |
env["PYTHON_BASIC_REPL"] = "1" |
| 1374 |
output, exit_code = self.run_repl("spam \nexit()\n", env=env) |
| 1375 |
self.assertEqual(exit_code, 0) |
| 1376 |
self.assertIn("spam ", output) |
| 1377 |
self.assertNotEqual(pathlib.Path(hfile.name).stat().st_size, 0) |
| 1378 |
self.assertIn("spam\\040", pathlib.Path(hfile.name).read_text()) |
| 1379 |
|
| 1380 |
env.pop("PYTHON_BASIC_REPL", None) |
| 1381 |
output, exit_code = self.run_repl("exit\n", env=env) |
| 1382 |
self.assertEqual(exit_code, 0) |
| 1383 |
self.assertNotIn("\\040", pathlib.Path(hfile.name).read_text()) |
| 1384 |
|
| 1385 |
def test_keyboard_interrupt_after_isearch(self): |
| 1386 |
output, exit_code = self.run_repl(["\x12", "\x03", "exit"]) |
| 1387 |
self.assertEqual(exit_code, 0) |
| 1388 |
|
| 1389 |
def test_prompt_after_help(self): |
| 1390 |
output, exit_code = self.run_repl(["help", "q", "exit"]) |
| 1391 |
|
| 1392 |
# Regex pattern to remove ANSI escape sequences |
| 1393 |
ansi_escape = re.compile(r"(\x1B(=|>|(\[)[0-?]*[ -\/]*[@-~]))") |
| 1394 |
cleaned_output = ansi_escape.sub("", output) |
| 1395 |
self.assertEqual(exit_code, 0) |
| 1396 |
|
| 1397 |
# Ensure that we don't see multiple prompts after exiting `help` |
| 1398 |
# Extra stuff (newline and `exit` rewrites) are necessary |
| 1399 |
# because of how run_repl works. |
| 1400 |
self.assertNotIn(">>> \n>>> >>>", cleaned_output) |
| 1401 |
|
| 1402 |
@skipUnless(Py_DEBUG, '-X showrefcount requires a Python debug build') |
| 1403 |
def test_showrefcount(self): |
| 1404 |
env = os.environ.copy() |
| 1405 |
env.pop("PYTHON_BASIC_REPL", "") |
| 1406 |
output, _ = self.run_repl("1\n1+2\nexit()\n", cmdline_args=['-Xshowrefcount'], env=env) |
| 1407 |
matches = re.findall(r'\[-?\d+ refs, \d+ blocks\]', output) |
| 1408 |
self.assertEqual(len(matches), 3) |
| 1409 |
|
| 1410 |
env["PYTHON_BASIC_REPL"] = "1" |
| 1411 |
output, _ = self.run_repl("1\n1+2\nexit()\n", cmdline_args=['-Xshowrefcount'], env=env) |
| 1412 |
matches = re.findall(r'\[-?\d+ refs, \d+ blocks\]', output) |
| 1413 |
self.assertEqual(len(matches), 3) |
| 1414 |
|
| 1415 |
|
| 1416 |
@force_not_colorized |
| 1417 |
def test_no_newline(self): |
| 1418 |
env = os.environ.copy() |
| 1419 |
env.pop("PYTHON_BASIC_REPL", "") |
| 1420 |
env["PYTHON_BASIC_REPL"] = "1" |
| 1421 |
|
| 1422 |
commands = "print('Something pretty long', end='')\nexit()\n" |
| 1423 |
expected_output_sequence = "Something pretty long>>> exit()" |
| 1424 |
|
| 1425 |
# gh-143394: The basic REPL needs the readline module to turn off |
| 1426 |
# ECHO terminal attribute. |
| 1427 |
if readline_module is not None: |
| 1428 |
basic_output, basic_exit_code = self.run_repl(commands, env=env) |
| 1429 |
self.assertEqual(basic_exit_code, 0) |
| 1430 |
self.assertIn(expected_output_sequence, basic_output) |
| 1431 |
|
| 1432 |
output, exit_code = self.run_repl(commands) |
| 1433 |
self.assertEqual(exit_code, 0) |
| 1434 |
|
| 1435 |
# Build patterns for escape sequences that don't affect cursor position |
| 1436 |
# or visual output. Use terminfo to get platform-specific sequences, |
| 1437 |
# falling back to hard-coded patterns for capabilities not in terminfo. |
| 1438 |
try: |
| 1439 |
from _pyrepl import curses |
| 1440 |
except ImportError: |
| 1441 |
self.skipTest("curses required for capability discovery") |
| 1442 |
|
| 1443 |
curses.setupterm(os.environ.get("TERM", ""), 1) |
| 1444 |
safe_patterns = [] |
| 1445 |
|
| 1446 |
# smkx/rmkx - application cursor keys and keypad mode |
| 1447 |
smkx = curses.tigetstr("smkx") |
| 1448 |
rmkx = curses.tigetstr("rmkx") |
| 1449 |
if smkx: |
| 1450 |
safe_patterns.append(re.escape(smkx.decode("ascii"))) |
| 1451 |
if rmkx: |
| 1452 |
safe_patterns.append(re.escape(rmkx.decode("ascii"))) |
| 1453 |
if not smkx and not rmkx: |
| 1454 |
safe_patterns.append(r'\x1b\[\?1[hl]') # application cursor keys |
| 1455 |
safe_patterns.append(r'\x1b[=>]') # application keypad mode |
| 1456 |
|
| 1457 |
# ich1 - insert character (only safe form that inserts exactly 1 char) |
| 1458 |
ich1 = curses.tigetstr("ich1") |
| 1459 |
if ich1: |
| 1460 |
safe_patterns.append(re.escape(ich1.decode("ascii")) + r'(?=[ -~])') |
| 1461 |
else: |
| 1462 |
safe_patterns.append(r'\x1b\[(?:1)?@(?=[ -~])') |
| 1463 |
|
| 1464 |
# civis/cnorm - cursor visibility (may include cursor blinking control) |
| 1465 |
civis = curses.tigetstr("civis") |
| 1466 |
cnorm = curses.tigetstr("cnorm") |
| 1467 |
if civis: |
| 1468 |
safe_patterns.append(re.escape(civis.decode("ascii"))) |
| 1469 |
if cnorm: |
| 1470 |
safe_patterns.append(re.escape(cnorm.decode("ascii"))) |
| 1471 |
if not civis and not cnorm: |
| 1472 |
safe_patterns.append(r'\x1b\[\?25[hl]') # cursor visibility |
| 1473 |
safe_patterns.append(r'\x1b\[\?12[hl]') # cursor blinking |
| 1474 |
|
| 1475 |
# rmam / smam - automatic margins |
| 1476 |
rmam = curses.tigetstr("rmam") |
| 1477 |
smam = curses.tigetstr("smam") |
| 1478 |
if rmam: |
| 1479 |
safe_patterns.append(re.escape(rmam.decode("ascii"))) |
| 1480 |
if smam: |
| 1481 |
safe_patterns.append(re.escape(smam.decode("ascii"))) |
| 1482 |
if not rmam and not smam: |
| 1483 |
safe_patterns.append(r'\x1b\[\?7l') # turn off automatic margins |
| 1484 |
safe_patterns.append(r'\x1b\[\?7h') # turn on automatic margins |
| 1485 |
|
| 1486 |
# Modern extensions not in standard terminfo - always use patterns |
| 1487 |
safe_patterns.append(r'\x1b\[\?2004[hl]') # bracketed paste mode |
| 1488 |
safe_patterns.append(r'\x1b\[\?12[hl]') # cursor blinking (may be separate) |
| 1489 |
safe_patterns.append(r'\x1b\[\?[01]c') # device attributes |
| 1490 |
|
| 1491 |
safe_escapes = re.compile('|'.join(safe_patterns)) |
| 1492 |
cleaned_output = safe_escapes.sub('', output) |
| 1493 |
self.assertIn(expected_output_sequence, cleaned_output) |
| 1494 |
|
| 1495 |
|
| 1496 |
@skipUnless(sys.platform == "darwin", "macOS only") |
| 1497 |
class TestMainAppleTerminal(TestMain): |
| 1498 |
"""Test the REPL with Apple Terminal's TERM_PROGRAM set.""" |
| 1499 |
|
| 1500 |
def run_repl(self, repl_input, env=None, **kwargs): |
| 1501 |
if env is None: |
| 1502 |
env = os.environ.copy() |
| 1503 |
env["TERM_PROGRAM"] = "Apple_Terminal" |
| 1504 |
return super().run_repl(repl_input, env=env, **kwargs) |
| 1505 |
|
| 1506 |
|
| 1507 |
class TestPyReplCtrlD(TestCase): |
| 1508 |
"""Test Ctrl+D behavior in _pyrepl to match old pre-3.13 REPL behavior. |
| 1509 |
|
| 1510 |
Ctrl+D should: |
| 1511 |
- Exit on empty buffer (raises EOFError) |
| 1512 |
- Delete character when cursor is in middle of line |
| 1513 |
- Perform no operation when cursor is at end of line without newline |
| 1514 |
- Exit multiline mode when cursor is at end with trailing newline |
| 1515 |
- Run code up to that point when pressed on blank line with preceding lines |
| 1516 |
""" |
| 1517 |
def prepare_reader(self, events): |
| 1518 |
console = FakeConsole(events) |
| 1519 |
config = ReadlineConfig(readline_completer=None) |
| 1520 |
reader = ReadlineAlikeReader(console=console, config=config) |
| 1521 |
return reader |
| 1522 |
|
| 1523 |
def test_ctrl_d_empty_line(self): |
| 1524 |
"""Test that pressing Ctrl+D on empty line exits the program""" |
| 1525 |
events = [ |
| 1526 |
Event(evt="key", data="\x04", raw=bytearray(b"\x04")), # Ctrl+D |
| 1527 |
] |
| 1528 |
reader = self.prepare_reader(events) |
| 1529 |
with self.assertRaises(EOFError): |
| 1530 |
multiline_input(reader) |
| 1531 |
|
| 1532 |
def test_ctrl_d_multiline_with_new_line(self): |
| 1533 |
"""Test that pressing Ctrl+D in multiline mode with trailing newline exits multiline mode""" |
| 1534 |
events = itertools.chain( |
| 1535 |
code_to_events("def f():\n pass\n"), # Enter multiline mode with trailing newline |
| 1536 |
[ |
| 1537 |
Event(evt="key", data="\x04", raw=bytearray(b"\x04")), # Ctrl+D |
| 1538 |
], |
| 1539 |
) |
| 1540 |
reader, _ = handle_all_events(events) |
| 1541 |
self.assertTrue(reader.finished) |
| 1542 |
self.assertEqual("def f():\n pass\n", "".join(reader.buffer)) |
| 1543 |
|
| 1544 |
def test_ctrl_d_multiline_middle_of_line(self): |
| 1545 |
"""Test that pressing Ctrl+D in multiline mode with cursor in middle deletes character""" |
| 1546 |
events = itertools.chain( |
| 1547 |
code_to_events("def f():\n hello world"), # Enter multiline mode |
| 1548 |
[ |
| 1549 |
Event(evt="key", data="left", raw=bytearray(b"\x1bOD")) |
| 1550 |
] * 5, # move cursor to 'w' in "world" |
| 1551 |
[ |
| 1552 |
Event(evt="key", data="\x04", raw=bytearray(b"\x04")) |
| 1553 |
], # Ctrl+D should delete 'w' |
| 1554 |
) |
| 1555 |
reader, _ = handle_all_events(events) |
| 1556 |
self.assertFalse(reader.finished) |
| 1557 |
self.assertEqual("def f():\n hello orld", "".join(reader.buffer)) |
| 1558 |
|
| 1559 |
def test_ctrl_d_multiline_end_of_line_no_newline(self): |
| 1560 |
"""Test that pressing Ctrl+D at end of line without newline performs no operation""" |
| 1561 |
events = itertools.chain( |
| 1562 |
code_to_events("def f():\n hello"), # Enter multiline mode, no trailing newline |
| 1563 |
[ |
| 1564 |
Event(evt="key", data="\x04", raw=bytearray(b"\x04")) |
| 1565 |
], # Ctrl+D should be no-op |
| 1566 |
) |
| 1567 |
reader, _ = handle_all_events(events) |
| 1568 |
self.assertFalse(reader.finished) |
| 1569 |
self.assertEqual("def f():\n hello", "".join(reader.buffer)) |
| 1570 |
|
| 1571 |
def test_ctrl_d_single_line_middle_of_line(self): |
| 1572 |
"""Test that pressing Ctrl+D in single line mode deletes current character""" |
| 1573 |
events = itertools.chain( |
| 1574 |
code_to_events("hello"), |
| 1575 |
[Event(evt="key", data="left", raw=bytearray(b"\x1bOD"))], # move left |
| 1576 |
[Event(evt="key", data="\x04", raw=bytearray(b"\x04"))], # Ctrl+D |
| 1577 |
) |
| 1578 |
reader, _ = handle_all_events(events) |
| 1579 |
self.assertEqual("hell", "".join(reader.buffer)) |
| 1580 |
|
| 1581 |
def test_ctrl_d_single_line_end_no_newline(self): |
| 1582 |
"""Test that pressing Ctrl+D at end of single line without newline does nothing""" |
| 1583 |
events = itertools.chain( |
| 1584 |
code_to_events("hello"), # cursor at end of line |
| 1585 |
[Event(evt="key", data="\x04", raw=bytearray(b"\x04"))], # Ctrl+D |
| 1586 |
) |
| 1587 |
reader, _ = handle_all_events(events) |
| 1588 |
self.assertEqual("hello", "".join(reader.buffer)) |
| 1589 |
|
| 1590 |
|
| 1591 |
@skipUnless(sys.platform == "win32", "windows console only") |
| 1592 |
class TestWindowsConsoleEolWrap(TestCase): |
| 1593 |
def _make_mock_console(self, width=80): |
| 1594 |
from _pyrepl import windows_console as wc |
| 1595 |
|
| 1596 |
console = object.__new__(wc.WindowsConsole) |
| 1597 |
|
| 1598 |
console.width = width |
| 1599 |
console.posxy = (0, 0) |
| 1600 |
console.screen = [""] |
| 1601 |
|
| 1602 |
console._hide_cursor = Mock() |
| 1603 |
console._show_cursor = Mock() |
| 1604 |
console._erase_to_end = Mock() |
| 1605 |
console._move_relative = Mock() |
| 1606 |
console.move_cursor = Mock() |
| 1607 |
console._WindowsConsole__write = Mock() |
| 1608 |
|
| 1609 |
return console, wc |
| 1610 |
|
| 1611 |
def test_short_line_sets_posxy_normally(self): |
| 1612 |
width = 10 |
| 1613 |
y = 3 |
| 1614 |
console, wc = self._make_mock_console(width=width) |
| 1615 |
old_line = "" |
| 1616 |
new_line = "a" * 3 |
| 1617 |
wc.WindowsConsole._WindowsConsole__write_changed_line( |
| 1618 |
console, y, old_line, new_line, 0 |
| 1619 |
) |
| 1620 |
self.assertEqual(console.posxy, (3, y)) |
| 1621 |
|
| 1622 |
def test_exact_width_line_does_not_wrap(self): |
| 1623 |
width = 10 |
| 1624 |
y = 3 |
| 1625 |
console, wc = self._make_mock_console(width=width) |
| 1626 |
old_line = "" |
| 1627 |
new_line = "a" * width |
| 1628 |
|
| 1629 |
wc.WindowsConsole._WindowsConsole__write_changed_line( |
| 1630 |
console, y, old_line, new_line, 0 |
| 1631 |
) |
| 1632 |
self.assertEqual(console.posxy, (width - 1, y)) |