|
| 1 | +"""Reservation boundaries interpreted by a terminal, rather than a fixed row-one CPR stub.""" |
| 2 | + |
| 3 | +import io |
| 4 | +import sys |
| 5 | +import threading |
| 6 | +from types import SimpleNamespace |
| 7 | + |
| 8 | +import pyte |
| 9 | +import pytest |
| 10 | + |
| 11 | +from cmd2.reserved_toolbar import ReservedToolbar |
| 12 | +from cmd2.utils import StdSim |
| 13 | + |
| 14 | +from .test_reserved_lifecycle import Harness |
| 15 | + |
| 16 | + |
| 17 | +class TerminalScreen(pyte.HistoryScreen): |
| 18 | + """Keep DECRC's physical position even when it is outside the scroll margins. |
| 19 | +
|
| 20 | + pyte 0.8.2 unconditionally clamps a restored cursor to the margins. iTerm2 and |
| 21 | + tmux retain the physical row when origin mode is off; that distinction is the |
| 22 | + bug these tests exercise. Let pyte restore against the whole screen in that mode. |
| 23 | + """ |
| 24 | + |
| 25 | + def restore_cursor(self) -> None: |
| 26 | + margins = self.margins |
| 27 | + if self.savepoints and not self.savepoints[-1].origin: |
| 28 | + self.margins = None |
| 29 | + try: |
| 30 | + super().restore_cursor() |
| 31 | + finally: |
| 32 | + self.margins = margins |
| 33 | + |
| 34 | + |
| 35 | +class EmulatedTerminal(io.StringIO): |
| 36 | + """Parse output and answer CPR where the cursor actually is when the query arrives.""" |
| 37 | + |
| 38 | + def __init__(self, rows, reply) -> None: |
| 39 | + super().__init__() |
| 40 | + self.screen = TerminalScreen(80, rows, history=1000) |
| 41 | + self.reports = [] |
| 42 | + |
| 43 | + def respond(data): |
| 44 | + self.reports.append(self.screen.cursor.y + 1) |
| 45 | + reply(data) |
| 46 | + |
| 47 | + self.screen.write_process_input = respond |
| 48 | + self.parser = pyte.Stream(self.screen) |
| 49 | + self.buffer = SimpleNamespace(write=lambda data: self.write(data.decode("utf-8"))) |
| 50 | + |
| 51 | + def write(self, data): |
| 52 | + count = super().write(data) |
| 53 | + # The tty's output processing supplies carriage returns to subprocess newlines. |
| 54 | + self.parser.feed(data.replace("\n", "\r\n")) |
| 55 | + return count |
| 56 | + |
| 57 | + def isatty(self) -> bool: |
| 58 | + return True |
| 59 | + |
| 60 | + |
| 61 | +@pytest.fixture |
| 62 | +def terminal_harness(request): |
| 63 | + rows = getattr(request, "param", 24) |
| 64 | + harness = Harness(rows=rows) |
| 65 | + stream = EmulatedTerminal(rows, harness.pipe.send_text) |
| 66 | + harness.stream = stream |
| 67 | + harness.backend.stdout = stream |
| 68 | + harness.app.stdout = stream |
| 69 | + try: |
| 70 | + yield harness, stream |
| 71 | + finally: |
| 72 | + harness.close() |
| 73 | + |
| 74 | + |
| 75 | +def read_prompt(harness, terminal) -> None: |
| 76 | + """Use the real input reader and CPR binding, then accept a prompt with known height.""" |
| 77 | + ui = harness.app.main_session.app |
| 78 | + sent = False |
| 79 | + |
| 80 | + def ready(app): |
| 81 | + nonlocal sent |
| 82 | + if not sent and app.renderer._min_available_height > 0: |
| 83 | + sent = True |
| 84 | + harness.pipe.send_text("next\n") |
| 85 | + |
| 86 | + ui.after_render += ready |
| 87 | + watchdog = threading.Timer(5, harness.pipe.close) |
| 88 | + watchdog.daemon = True |
| 89 | + watchdog.start() |
| 90 | + try: |
| 91 | + assert harness.app._read_raw_input("TEST> ", harness.app.main_session) == "next" |
| 92 | + assert sent |
| 93 | + assert terminal.reports |
| 94 | + assert all(row < terminal.screen.lines for row in terminal.reports) |
| 95 | + assert terminal.screen.display[-1].startswith("STATUS") |
| 96 | + finally: |
| 97 | + watchdog.cancel() |
| 98 | + watchdog.join() |
| 99 | + ui.after_render -= ready |
| 100 | + |
| 101 | + |
| 102 | +@pytest.mark.parametrize("row", [1, 22, 23, 24]) |
| 103 | +@pytest.mark.parametrize("reserved", [1, 2]) |
| 104 | +def test_acquisition_keeps_existing_output_and_cursor_above_the_band(terminal_harness, row, reserved) -> None: |
| 105 | + harness, terminal = terminal_harness |
| 106 | + terminal.write(f"\x1b[{row};1Hexisting output") |
| 107 | + with ReservedToolbar(harness.app.main_session, lambda: "STATUS", reserved_rows=reserved): |
| 108 | + expected_row = min(row, 24 - reserved) |
| 109 | + assert terminal.screen.cursor.y + 1 == expected_row |
| 110 | + assert terminal.screen.cursor.x == len("existing output") |
| 111 | + assert terminal.screen.display[expected_row - 1].startswith("existing output") |
| 112 | + assert terminal.screen.display[24 - reserved].startswith("STATUS") |
| 113 | + assert terminal.screen.margins is None |
| 114 | + |
| 115 | + |
| 116 | +@pytest.mark.parametrize("terminal_harness", [12, 24, 40], indirect=True) |
| 117 | +def test_a_prompt_started_on_the_bottom_row_gets_a_usable_cursor_report(terminal_harness, capsys) -> None: |
| 118 | + harness, terminal = terminal_harness |
| 119 | + terminal.write(f"\x1b[{terminal.screen.lines};1H") |
| 120 | + with harness.app._reserved_toolbar_context(): |
| 121 | + # Fail before trying input if startup has left the cursor in the band. |
| 122 | + assert terminal.screen.cursor.y < terminal.screen.lines - 1 |
| 123 | + read_prompt(harness, terminal) |
| 124 | + assert "doesn't support cursor position requests" not in capsys.readouterr().err |
| 125 | + assert terminal.screen.margins is None |
| 126 | + |
| 127 | + |
| 128 | +@pytest.mark.parametrize("terminal_harness", [12, 24, 40], indirect=True) |
| 129 | +def test_shell_output_scrolling_to_the_bottom_returns_a_working_prompt(terminal_harness, capfd) -> None: |
| 130 | + harness, terminal = terminal_harness |
| 131 | + # Exercise a real shell subprocess and ProcReader, echoing its captured bytes to |
| 132 | + # the same terminal as the toolbar. This supplies a real pipe rather than fileno() |
| 133 | + # on the in-memory terminal. |
| 134 | + harness.app.stdout = StdSim(terminal, echo=True) |
| 135 | + with harness.app._reserved_toolbar_context(): |
| 136 | + command = f"!\"{sys.executable}\" -S -c \"print('out\\n' * 80, end='')\"" |
| 137 | + harness.app.onecmd_plus_hooks(command) |
| 138 | + assert harness.app.last_result == 0 |
| 139 | + assert terminal.screen.cursor.y == terminal.screen.lines - 2 |
| 140 | + assert terminal.screen.display[-3].rstrip() == "out" |
| 141 | + assert terminal.screen.display[-1].startswith("STATUS") |
| 142 | + # Every emitted line must remain in the viewport or scrollback exactly once. |
| 143 | + history = ["".join(line[x].data for x in sorted(line)) for line in terminal.screen.history.top] |
| 144 | + assert sum(line.rstrip() == "out" for line in history + terminal.screen.display) == 80 |
| 145 | + read_prompt(harness, terminal) |
| 146 | + assert "doesn't support cursor position requests" not in capfd.readouterr().err |
| 147 | + assert terminal.screen.margins is None |
| 148 | + |
| 149 | + |
| 150 | +def test_release_does_not_erase_rows_from_a_changed_viewport(terminal_harness) -> None: |
| 151 | + harness, terminal = terminal_harness |
| 152 | + with harness.app._reserved_toolbar_context(): |
| 153 | + # The reserved row was cropped by a resize; the new bottom row is application |
| 154 | + # output. CUP to the old row would clamp there and erase somebody else's text. |
| 155 | + terminal.screen.resize(lines=12, columns=80) |
| 156 | + harness.size = type(harness.size)(rows=12, columns=80) |
| 157 | + terminal.write("\x1b[12;1Hkeep this output") |
| 158 | + assert terminal.screen.display[-1].startswith("keep this output") |
| 159 | + assert terminal.screen.margins is None |
| 160 | + |
| 161 | + |
| 162 | +def test_release_still_resets_margins_when_geometry_cannot_be_measured(terminal_harness, monkeypatch) -> None: |
| 163 | + harness, terminal = terminal_harness |
| 164 | + with harness.app._reserved_toolbar_context(): |
| 165 | + |
| 166 | + def unavailable(): |
| 167 | + raise OSError("terminal size unavailable") |
| 168 | + |
| 169 | + monkeypatch.setattr(harness.backend, "get_size", unavailable) |
| 170 | + assert terminal.screen.margins is None |
0 commit comments