diff --git a/CHANGES b/CHANGES index 9f042a29..5d6f6fb5 100644 --- a/CHANGES +++ b/CHANGES @@ -8,6 +8,20 @@ _Notes on the upcoming release will go here._ ### What's new +#### Drive terminal processes synchronously (#142) + +{func}`~libvt.contrib.subprocess.open_terminal` opens an interactive child on a +POSIX PTY or Windows ConPTY, returning a +{class}`~libvt.contrib.subprocess.TerminalProcess` handle. Use +{func}`~libvt.contrib.subprocess.run_terminal` to collect a child's exit +status, final viewport, and bounded output in a +{class}`~libvt.contrib.subprocess.CompletedTerminal` result. Both +{class}`~libvt.contrib.subprocess.TerminalProcess` and +{class}`~libvt.contrib.subprocess.Capture` implement +{class}`~libvt.testing.SupportsVtTarget` for +{func}`~libvt.testing.vt_screen` and +{func}`~libvt.testing.serialize_vt_snapshot`. + #### Recorder protocol, target protocol, and state replacement (#203) Pass any {class}`~libvt.recorder.TerminalRecorder` implementation to @@ -26,6 +40,28 @@ directly. {func}`~libvt.modes.is_private_mode_supported` exposes profile mode support queries, and {class}`~libvt.snapshot.SnapshotDict` types the dictionary returned by {meth}`~libvt.snapshot.Snapshot.to_dict`. +#### Find snapshot text by cell coordinates (#133) + +{meth}`~libvt.snapshot.Snapshot.find_cells` returns each visible match as a +{class}`~libvt.snapshot.CellSpan` with a row and a half-open column range. +Use the coordinates to click or inspect labels that include wide or +combined graphemes. + +#### Replay failed pytest terminal tests (#139) + +Run pytest with `--vt-replay-dir` to save the bytes fed to the terminal, +resizes, initial encoding, and the observed screen from a failed test. Run +`python -m libvt replay` on the saved file to check the final rows, wraps, +styles, and cursor offline. See {ref}`replaying-pytest-failures`. + +### Fixes + +#### Identify hidden screen assertion differences (#139) + +{func}`~libvt.testing.assert_screen` reports the first differing row or +column even when box padding hides a written space or expected text lies +beyond the viewport. + ### Documentation #### Split API reference into per-module pages @@ -36,6 +72,30 @@ Add dedicated API reference pages for {mod}`libvt.views`, `syrupy`) into per-module directories, and add Sphinx `rediraffe` redirects for moved API URLs. +#### Drive a Python child from the README (#131) + +The README example starts a child in a POSIX terminal, sends input, and +waits for the child's response on screen. Use it to check that a program +consumed input after the terminal echoed it. + +#### Test selection and cancellation in fzf (#138) + +The {ref}`fzf recipe ` drives a real picker in a private +PTY. Check the highlighted item, selected output, and exit status after +sending Enter or Escape. + +#### Play and replay The Last Beacon (#140) + +The {ref}`game walkthrough ` drives a playable +terminal game, checks its winning screen after resizing, and replays a +saved run from the command line. + +#### Observe a pane and its attached tmux client (#141) + +The {doc}`tmux screen guide ` compares application +output with an attached client's copy-mode view. The example translates a +pane-local click after resize and checks which child received it. + ## libvt 0.0.1a6 (2026-12-05) `libvt` 0.0.1a6 adds soft-wrapped logical-line reading and `wait_for()` diff --git a/README.md b/README.md index af46dc13..efc61271 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,32 @@ or use it to test terminal programs. Requires Python 3.12 or later (CPython and PyPy). Written in Python, with type annotations and no runtime dependencies. +## Drive a terminal program + +On POSIX, use [`open_pty()`][open_pty] to launch a program, send input, and +wait for a response on its screen. The child prints `Taken: key` after it +reads the command. + +```python +>>> import asyncio +>>> import os +>>> import sys +>>> from libvt.aio import open_pty + +>>> async def take_key() -> None: +... child = "print('Quay'); print('Taken: ' + input())" +... async with open_pty([sys.executable, "-u", "-c", child]) as session: +... await session.wait_for("Quay", timeout=5) +... session.paste("key") +... session.send_key("enter") +... await session.wait_for( +... lambda screen: "Taken: key" in screen.lines, timeout=5 +... ) + +>>> if os.name == "posix": +... asyncio.run(take_key()) +``` + ## Installation Install with `uv`: @@ -41,6 +67,9 @@ breaking API changes; pin `libvt>=0.0.1a6,<0.1` while the package is pre-1.0. ## Quickstart +For a complete PTY walkthrough, +[play, test, and replay The Last Beacon](https://libvt.git-pull.com/topics/interactive-game/). + ### Feed bytes and inspect immutable snapshots Each call to [`feed()`][feed] updates the screen. Read live text and cursor @@ -65,8 +94,13 @@ styles: r0[0..11]: bold fg=green >>> snap.viewport(offset=1).lines ('booting', 'Loading 20%') +>>> snap.find_cells("done") +(CellSpan(row=1, start=0, stop=4),) ``` +Use [`Snapshot.find_cells()`][find_cells] to turn a visible label into cell +coordinates for a click, highlight, or assertion. + ### Assert screen boxes inline Most unit tests can stop at [`assert_screen_box()`][assert_screen_box], which @@ -133,7 +167,10 @@ styles: [`libvt.pytest_plugin`][pytest_plugin] (`libvt[pytest]`) provides `vt_terminal` (wired to a 4 KiB `FlightRecorder`), `vt_factory`, `vt_recorder`, `vt_parser`, -and POSIX `vt_pty` fixtures with no snapshot-tool dependencies: +and POSIX `vt_pty` fixtures with no snapshot-tool dependencies. + +Use `--vt-replay-dir` to [replay a failed terminal test][pytest_replay] +from the bytes and resizes saved by pytest. ```python >>> import libvt @@ -155,6 +192,10 @@ and POSIX `vt_pty` fixtures with no snapshot-tool dependencies: >>> test_prompt(libvt.Terminal) ``` +The [fzf cookbook test](https://github.com/tmux-python/libvt/blob/master/tests/test_fzf_cookbook.py) +checks the highlighted row, the record accepted with Enter, and the empty result +on Escape. + ### Persist `.ambr` snapshots (`libvt[syrupy]`) [`libvt.contrib.syrupy`][contrib_syrupy] (`libvt[syrupy]`) adapts @@ -203,22 +244,31 @@ styles: (`?2026`). - Encode keyboard, mouse, focus, and paste events according to the active terminal modes. +- Drive [terminal processes](https://libvt.git-pull.com/api/contrib/subprocess/) + synchronously on POSIX or Windows. - Run terminal programs on POSIX PTYs or connect to `asyncio` streams. Read `tmux` captures as screen cells and decode control-mode output with -[`libvt.contrib.tmux`](https://libvt.git-pull.com/api/contrib/tmux/). Full -guides and API reference are at [libvt.git-pull.com](https://libvt.git-pull.com/). +[`libvt.contrib.tmux`](https://libvt.git-pull.com/api/contrib/tmux/). See +[Which screen am I testing?](https://libvt.git-pull.com/topics/tmux-screens/) +and its +[runnable example](https://github.com/tmux-python/libvt/blob/master/examples/tmux_screens.py) +for attached-client checks. Full guides and API reference are at +[libvt.git-pull.com](https://libvt.git-pull.com/). ## License MIT License. See [LICENSE](LICENSE). +[open_pty]: https://libvt.git-pull.com/api/aio/pty/#libvt.aio.open_pty [feed]: https://libvt.git-pull.com/api/terminal/#libvt.terminal.Terminal.feed +[find_cells]: https://libvt.git-pull.com/topics/snapshots/#locate-text-by-cell-coordinates [committed]: https://libvt.git-pull.com/api/terminal/#libvt.terminal.Terminal.committed [viewport]: https://libvt.git-pull.com/api/snapshot/#libvt.snapshot.Snapshot.viewport [assert_screen_box]: https://libvt.git-pull.com/api/testing/#libvt.testing.assert_screen_box [contrib_syrupy]: https://libvt.git-pull.com/api/contrib/syrupy/ [pytest_plugin]: https://libvt.git-pull.com/api/pytest_plugin/ +[pytest_replay]: https://libvt.git-pull.com/topics/testing/#replay-a-failed-terminal-test [vt_snapshot]: https://libvt.git-pull.com/api/contrib/syrupy/#libvt.contrib.syrupy.vt_snapshot [vt_screen]: https://libvt.git-pull.com/api/testing/#libvt.testing.vt_screen [serialize_vt_snapshot]: https://libvt.git-pull.com/api/testing/#libvt.testing.serialize_vt_snapshot diff --git a/docs/api/contrib/index.md b/docs/api/contrib/index.md index 10ab0f4f..8948cd2c 100644 --- a/docs/api/contrib/index.md +++ b/docs/api/contrib/index.md @@ -12,6 +12,12 @@ Decoupled `tmux` profiles, `capture-pane` decoders, multi-pane window compositing, and `-C` / `-CC` control-mode synchronization. ::: +:::{grid-item-card} `libvt.contrib.subprocess` +:link: subprocess +:link-type: doc +Synchronous child processes on POSIX PTYs and Windows ConPTY. +::: + :::{grid-item-card} `libvt.contrib.syrupy` :link: syrupy :link-type: doc @@ -30,5 +36,6 @@ fixture (`libvt[syrupy]`). :maxdepth: 2 tmux/index +subprocess syrupy ``` diff --git a/docs/api/contrib/subprocess.md b/docs/api/contrib/subprocess.md new file mode 100644 index 00000000..1a627041 --- /dev/null +++ b/docs/api/contrib/subprocess.md @@ -0,0 +1,86 @@ +# Synchronous terminal processes + +Use {mod}`libvt.contrib.subprocess` to drive a terminal application from +synchronous Python. The session reads merged terminal output in the +background while your test waits for text, sends keys, or resizes the +viewport. + +```python +>>> import ctypes +>>> import sys +>>> from libvt.contrib import subprocess as sp +>>> command = [sys.executable, "-u", "-c", +... "print('Ready'); print('Result:', input()[::-1])"] +>>> supported = sys.platform != "win32" or hasattr( +... ctypes.WinDLL("kernel32"), "ReleasePseudoConsole", +... ) +>>> if supported: +... with sp.open_terminal(command, vt=sp.VT(rows=6, cols=40)) as child: +... _ = child.wait_for("Ready", timeout=8) +... child.resize(rows=8, cols=48) +... child.paste("pear") +... child.send_key("enter") +... status = child.wait(timeout=8) +... final = child.wait_eof(timeout=8) +... assert status == 0 and final.snapshot.cols == 48 +... assert "Result: raep" in final.snapshot.text +``` + +{meth}`~libvt.contrib.subprocess.TerminalProcess.wait` returns the direct +child's exit status. Use +{meth}`~libvt.contrib.subprocess.TerminalProcess.wait_eof` to collect the +final output after every process attached to the terminal has closed its +terminal handles. Descendants can keep the terminal open after the direct +child exits. Both waits accept timeouts and leave the live handle available +when they time out. +{meth}`~libvt.contrib.subprocess.TerminalProcess.wait_for` times out through +{exc}`libvt.exc.TerminalTimeoutError`. + +For a command that finishes on its own, call +{func}`~libvt.contrib.subprocess.run_terminal`. It waits for both the direct +child and terminal EOF. Its timeout covers both waits after launch. It closes +the terminal and reaps the direct child before raising +{exc}`~libvt.contrib.subprocess.TerminalTimeoutExpired`. Use the exception's +`phase` and `capture` to inspect where it timed out and what it recorded. The +optional `input` bytes are queued after launch. Interactive commands that +wait for a prompt before accepting input work with +{func}`~libvt.contrib.subprocess.open_terminal`. + +Use the live handle from its creating thread. +{meth}`~libvt.contrib.subprocess.TerminalProcess.close` and context exit shut +down the terminal and may interrupt its remaining clients. Call `wait_eof()` +first when their output matters. On POSIX, a descendant that ignores hangup +can outlive the terminal after the direct child exits. This also applies when +`run_terminal()` closes a terminal after a timeout. +{class}`~libvt.contrib.subprocess.Capture`, +{class}`~libvt.contrib.subprocess.CompletedTerminal`, and +{class}`~libvt.contrib.subprocess.TerminalProcess` implement +{class}`~libvt.testing.SupportsVtTarget` so you can pass them directly to +{func}`~libvt.testing.vt_screen` and +{func}`~libvt.testing.serialize_vt_snapshot`. + +The result includes a snapshot, the retained raw tail, and the total number +of recorded bytes. The terminal and recorder retain only the configured +scrollback and byte tail (`raw_limit=0` disables raw tail retention while +still counting `raw_total`). Raw bytes include terminal control sequences and +native console translation. + +Terminal mode uses a POSIX PTY or native ConPTY. On macOS a single-trampoline +helper owns the terminal session over a socketpair so the direct child's exit +leaves the terminal available to descendants. + +Opening `/dev/tty` can leave a Darwin kernel reference to the terminal until +the session closes. If that reference keeps EOF pending, use `close()` after +collecting the output you need. +[Apple's controlling-terminal driver](https://github.com/apple-oss-distributions/xnu/blob/f6217f891ac0bb64f3d375211650a4c1ff8ca1ea/bsd/kern/tty_tty.c) + +On Windows terminal mode requires `ReleasePseudoConsole` (Windows 11 24H2 or +Windows Server 2025, build 26100) to observe natural EOF after the last +console client exits. Pass an absolute executable path when you need +consistent executable selection across operating systems. +[Microsoft's ReleasePseudoConsole documentation](https://learn.microsoft.com/en-us/windows/console/releasepseudoconsole) + +```{eval-rst} +.. automodule:: libvt.contrib.subprocess + :members: VT, Capture, CompletedTerminal, TerminalProcess, CalledTerminalError, TerminalTimeoutExpired, open_terminal, run_terminal +``` diff --git a/docs/api/index.md b/docs/api/index.md index ffb8f192..89e8f9ed 100644 --- a/docs/api/index.md +++ b/docs/api/index.md @@ -92,6 +92,12 @@ Import-light `vt_terminal`, `vt_factory`, `vt_recorder`, `vt_parser`, and Decoupled `tmux` `profile`, `capture`, `window`, and `control` submodules. ::: +:::{grid-item-card} `libvt.contrib.subprocess` +:link: contrib/subprocess +:link-type: doc +Synchronous child processes on POSIX PTYs and Windows ConPTY. +::: + :::{grid-item-card} `libvt.contrib.syrupy` :link: contrib/syrupy :link-type: doc diff --git a/docs/api/terminal.md b/docs/api/terminal.md index ef7a51fa..2f7e1b9b 100644 --- a/docs/api/terminal.md +++ b/docs/api/terminal.md @@ -8,5 +8,5 @@ re-exports live in their owning modules: {mod}`libvt.snapshot`, .. automodule:: libvt.terminal :members: Terminal, StopOn, StepResult, render, strip :no-private-members: - :exclude-members: _state, __new__, FlightRecorder, Formatter, OutputFormat, ResyncReason, ScreenDelta, Snapshot, SnapshotDict, SyncToken, SyncView, TerminalRecorder + :exclude-members: _state, __new__, CellSpan, FlightRecorder, Formatter, OutputFormat, ResyncReason, ScreenDelta, Snapshot, SnapshotDict, SyncToken, SyncView, TerminalRecorder ``` diff --git a/docs/project/public-api.md b/docs/project/public-api.md index e5085444..cacb3089 100644 --- a/docs/project/public-api.md +++ b/docs/project/public-api.md @@ -25,8 +25,9 @@ Import specialized types and helpers from their owning submodules: - {mod}`libvt.parser`, {mod}`libvt.screen`, {mod}`libvt.views`, {mod}`libvt.snapshot`, {mod}`libvt.format`, {mod}`libvt.recorder`, and {mod}`libvt.terminal` — streaming VT500 parser, screen grids and views, - immutable snapshots and incremental {class}`~libvt.snapshot.SyncToken` / + immutable snapshots, incremental {class}`~libvt.snapshot.SyncToken` / {class}`~libvt.snapshot.ScreenDelta` replicas, + {class}`~libvt.snapshot.CellSpan` coordinates, {class}`~libvt.format.Formatter`, and {class}`~libvt.recorder.TerminalRecorder` - {mod}`libvt.input`, {mod}`libvt.aio`, and {mod}`libvt.codec` — mode-aware input encoders, {class}`~libvt.aio.AsyncSession` transports, and sequence @@ -44,6 +45,9 @@ Import specialized types and helpers from their owning submodules: {mod}`~libvt.contrib.tmux.control`) — decoupled `tmux` inner-pane profiles, `capture-pane` decoders, multi-pane window compositing, and `-C` / `-CC` control-mode parser and pane sync +- {mod}`libvt.contrib.subprocess` — synchronous child processes with + {func}`~libvt.contrib.subprocess.open_terminal` and + {func}`~libvt.contrib.subprocess.run_terminal` on POSIX PTYs and Windows ConPTY - {mod}`libvt.contrib.syrupy` — optional `syrupy` `.ambr` adapter (`libvt[syrupy]`): {class}`~libvt.contrib.syrupy.VtSnapshotExtension` and conditional {fixture}`vt_snapshot` `pytest11` fixture diff --git a/docs/topics/index.md b/docs/topics/index.md index 596eeb7d..56352e89 100644 --- a/docs/topics/index.md +++ b/docs/topics/index.md @@ -27,6 +27,20 @@ Immutable {class}`~libvt.snapshot.Snapshot` captures, {attr}`~libvt.terminal.Ter Three decoupled testing systems built on snapshots: {mod}`libvt.testing`, {mod}`libvt.pytest_plugin` (`libvt[pytest]`), and {mod}`libvt.contrib.syrupy` (`libvt[syrupy]`). ::: +:::{grid-item-card} Test an Interactive Game +:link: interactive-game +:link-type: doc +Drive a text adventure on a PTY, verify its window size and replay the +winning screen. +::: + +:::{grid-item-card} Which screen am I testing? +:link: tmux-screens +:link-type: doc +Compare a tmux pane with an attached client in copy mode and route a mouse +click after a resize. +::: + :::{grid-item-card} Synchronized Output & `asyncio` :link: sync-and-asyncio :link-type: doc @@ -55,6 +69,8 @@ Differences in terminal construction, coordinates, alternate screens, and query architecture snapshots testing +interactive-game +tmux-screens sync-and-asyncio protocols-and-input migrating-from-pyte diff --git a/docs/topics/interactive-game.md b/docs/topics/interactive-game.md new file mode 100644 index 00000000..3ad6b657 --- /dev/null +++ b/docs/topics/interactive-game.md @@ -0,0 +1,130 @@ +(topics-interactive-game)= + +# Test an interactive game + +In *The Last Beacon*, the harbor is dark. Find the brass key at Lantern Quay, +go north, and light the beacon. The game uses only the standard library. +Run the commands from the repository root with `libvt` installed. + +## Play the game + +On a POSIX terminal, run the game to explore with the arrow keys. Type +`help` for commands and `quit` to leave. + +```console +$ python examples/last_beacon/game.py +``` + +Use `--transcript` for line-by-line play on any platform. Enter `north` +and try to light the beacon without the key. + +```python +>>> import subprocess +>>> import sys +>>> game = subprocess.run( +... [sys.executable, "examples/last_beacon/game.py", "--transcript"], +... input="north\nlight beacon\nquit\n", +... text=True, +... capture_output=True, +... check=True, +... ) +>>> "You need the brass key." in game.stdout +True +``` + +## Drive the game from a test + +On POSIX, run the tour to play through a real pseudo-terminal. + +```console +$ python examples/last_beacon/tour.py +``` + +The tour opens the child with {func}`~libvt.aio.open_pty`. It pastes +`take key`, submits it with Enter, and sends Up using the cursor-key mode +requested by the child. It waits for the room heading to confirm movement, +then resizes to 45 columns by 10 rows. The new size in the title comes from +the child's terminal, so it confirms the resize reached the application. + +The tour checks the victory message for bold green text and keeps the arrival +{class}`~libvt.snapshot.Snapshot` to verify that it still shows the quay at +the original width. Capture the winning screen before quitting because the +child restores the primary screen as it exits. + +```python +>>> import os +>>> import pathlib +>>> import subprocess +>>> import sys +>>> import tempfile +>>> if os.name == "posix": +... with tempfile.TemporaryDirectory() as directory: +... trace = pathlib.Path(directory) / "beacon.json" +... tour = [sys.executable, "examples/last_beacon/tour.py"] +... live = subprocess.check_output([*tour, "--record", str(trace)], timeout=30) +... saved = subprocess.check_output([*tour, "--replay", str(trace)], timeout=30) +... assert b"The beacon is lit!" in live and live == saved +``` + +## Replay the winning screen + +The bundled recording stores output bytes and viewport sizes at each +checkpoint. Replay applies the sizes and feeds the bytes to a fresh +{class}`~libvt.terminal.Terminal`. Each checkpoint is compared with its +original {func}`~libvt.testing.serialize_vt_snapshot` output. Feeding one +byte at a time exercises escape sequences split across reads. + +```console +$ python examples/last_beacon/tour.py --replay --chunk-size 1 +``` + +```python +>>> import subprocess +>>> import sys +>>> replay = subprocess.run( +... [sys.executable, "examples/last_beacon/tour.py", "--replay", "--chunk-size", "1"], +... capture_output=True, encoding="utf-8", check=True, +... ) +>>> replay.stdout.splitlines()[0] +'size=45x10 cursor=(9,2,vis=True) alt=True modes=[DECCKM,BRACKETED_PASTE]' +>>> "r8[0..18]: bold fg=green" in replay.stdout +True +``` + +Replay stops at the first checkpoint whose saved screen differs. The error +names the checkpoint. You can check a recording from an optimized interpreter +as well. + +```python +>>> import json +>>> import pathlib +>>> import subprocess +>>> import sys +>>> import tempfile +>>> example = pathlib.Path("examples/last_beacon") +>>> frames = json.loads((example / "walkthrough.json").read_text(encoding="utf-8")) +>>> frames[1]["screen"] = frames[0]["screen"] +>>> with tempfile.TemporaryDirectory() as directory: +... trace = pathlib.Path(directory) / "changed.json" +... _ = trace.write_text(json.dumps(frames), encoding="utf-8") +... result = subprocess.run( +... [sys.executable, "-O", str(example / "tour.py"), "--replay", str(trace)], +... capture_output=True, text=True, check=False, +... ) +>>> result.returncode, result.stderr.strip() +(1, "tour.py: Screen differs at checkpoint 'key'") +``` + +On POSIX, use `--record` to save a fresh run. The bounded +{class}`~libvt.recorder.FlightRecorder` supplies the bytes received from +the child. A fresh trace can include an intermediate redraw between paste +and Enter. The completed checkpoints still match. Replay runs on any +supported platform without starting the game. + +```console +$ python examples/last_beacon/tour.py --record beacon.json +``` + +```console +$ python examples/last_beacon/tour.py --replay beacon.json +``` diff --git a/docs/topics/snapshots.md b/docs/topics/snapshots.md index 2fd60c3b..6c2557b8 100644 --- a/docs/topics/snapshots.md +++ b/docs/topics/snapshots.md @@ -169,6 +169,25 @@ its captured dimensions. A row's `used` extent includes written background-only cells. Its `text_used` extent ends with the text. Both are measured from the start of the row view. +## Locate text by cell coordinates + +Use {meth}`~libvt.snapshot.Snapshot.find_cells` to locate a label in the active +viewport. Each {class}`~libvt.snapshot.CellSpan` gives a zero-based row and a +half-open column range. Use the start column for a +{class}`~libvt.input.MouseEvent`, or slice the snapshot with both columns. + +```python +>>> from libvt import Terminal +>>> from libvt.input import MouseAction, MouseButton, MouseEvent +>>> term = Terminal(rows=2, cols=16) +>>> term.feed("\x1b[?1000;1006h界界界·Go".encode()) +>>> (hit,) = term.committed.find_cells("Go") +>>> hit +CellSpan(row=0, start=7, stop=9) +>>> term.encode(MouseEvent(MouseButton.LEFT, MouseAction.PRESS, hit.row, hit.start)) +b'\x1b[<0;8;1M' +``` + ## Stateless scrollback paging (`viewport()`) Primary-screen snapshots retain frozen scrollback alongside the active diff --git a/docs/topics/testing.md b/docs/topics/testing.md index e02a2a9a..af87c4f9 100644 --- a/docs/topics/testing.md +++ b/docs/topics/testing.md @@ -479,6 +479,86 @@ with no dependency on `syrupy` or any other snapshot tool: >>> test_parser_actions(vt_parser) # doctest: +HIDE ``` +(topics-testing-fzf)= + +### Select or cancel in fzf + +[fzf](https://github.com/junegunn/fzf) reads candidates from standard input, +draws its picker on the controlling terminal, and writes the accepted record +to standard output. Use {func}`~libvt.aio.open_pty` for the screen and redirect +the records to files in the test directory. The picker gets an 8-row, +40-column PTY and uses that directory for temporary files. The test checks +the highlighted row on the PTY and reads the selected record from the file. + +The test uses [pytest-asyncio](https://pytest-asyncio.readthedocs.io/). +Install fzf on a POSIX host, then run both outcomes from the repository root. + +```console +$ uv run pytest tests/test_fzf_cookbook.py +``` + +```{literalinclude} ../../tests/test_fzf_cookbook.py +:language: python +:start-at: import asyncio +:end-before: pytestmark = +``` + +Down highlights the second Cedar record. Enter returns that line with a +newline. Escape exits with status 130 and leaves the selection file empty. + +(replaying-pytest-failures)= + +### Replay a failed terminal test + +Pass `--vt-replay-dir` to capture failures from tests using +{fixture}`vt_terminal`, {fixture}`vt_factory`, or POSIX {fixture}`vt_pty`. +The {download}`example <../../examples/replay_prompt.py>` draws `X` while +the screen is four columns wide. After widening the screen, it writes a +space in column 4. The assertion deliberately omits that space. + +```{literalinclude} ../../examples/replay_prompt.py +:language: python +:start-at: from libvt.pytest_plugin +``` + +Run the failing test from the repository root to save the trace. + +```console +$ uv run pytest -q examples/replay_prompt.py --vt-replay-dir=.vt-replays +``` + +Run `python -m libvt replay` with the JSON path printed in the test report. +The replay command runs offline with libvt installed. It feeds the captured +bytes to a fresh terminal, applies each resize in order, and prints the box +and style spans. Python string literals show written spaces in the visible +rows. Pass `--chunk-size 1` to replay each feed one byte at a time. The CLI +exits with status 1 if replay is unavailable or the captured frame differs. + +{func}`~libvt.testing.assert_screen` reports the first differing row or +zero-based display column and shows the full glyph on each side. It prints +a written trailing space as `' '` and shows `padding` past the written cells. +Pass the live fixture terminal to capture the expected rows and the exact +state at the assertion. +A boxed assertion captures its actual rows at the assertion. A plain pytest +failure or an assertion on an immutable snapshot captures the fixture terminals +as they stand at the end of the test call. The artifact cannot infer the +expected cells or recover an earlier snapshot from those assertions. + +Replay preserves the terminal's initial `encoding` (`"utf-8"` or `"latin-1"`) +and uses the default profile, policy, and limits. A custom event callback +leaves the trace incomplete. The plugin tracks +{meth}`~libvt.terminal.Terminal.feed`, the bytes consumed by +{meth}`~libvt.terminal.Terminal.feed_until`, and caller-initiated +{meth}`~libvt.terminal.Terminal.resize`. With `vt_pty`, the trace begins +before the first read of the child's output. Set `rows`, `cols`, and `env` +when the child needs fixed dimensions or a controlled `TMPDIR`. The file +includes output from the child and any input the terminal echoed. + +Capture stops after 1 MiB of input or 10,000 events per terminal. Unsupported +configuration, oversized geometry or an incomplete history can still produce +a diagnostic artifact with actual rows and the assertion difference. The +JSON includes raw terminal bytes, which may contain private data. + --- ## Syrupy `.ambr` adapter (`libvt.contrib.syrupy`) diff --git a/docs/topics/tmux-screens.md b/docs/topics/tmux-screens.md new file mode 100644 index 00000000..e68d75c5 --- /dev/null +++ b/docs/topics/tmux-screens.md @@ -0,0 +1,95 @@ +# Which screen am I testing? + +Choose the screen whose behavior your test checks. A tmux pane capture shows +the application's grid. An attached tmux client renders the window, including +copy mode, borders and the status line. Use an attached client when checking +what a person can see or click. + +## Compare a pane with its copy-mode viewport + +The example opens an archive on the left and a mouse-aware picker on the right. +The archive prints 32 ledger entries and `ARCHIVE LIVE`. After tmux enters +copy mode and moves to the start of history, the two observations differ. + +| Observation | Text in the archive pane | +| --- | --- | +| Application grid from {func}`~libvt.contrib.tmux.capture.build_tmux_capture_command` | `ARCHIVE LIVE` | +| Rendering from a tmux client attached through {func}`~libvt.aio.open_pty` | `Ledger entry 00` | + +The example runs the capture bundle against the same server and crops the +attached snapshot by **cell** coordinates. The one-row offset accounts for the +status line above the window. The example selects at the start of the ledger +and checks for the configured selection background in the attached frame. + +```{literalinclude} ../../examples/tmux_screens.py +:language: python +:start-at: Compare the application grid +:end-before: Read the mode grid +:dedent: 16 +``` + +When `tmux list-commands capture-pane` advertises `-M`, use it to read the +copy-mode grid. Read `#{scroll_position}` while the pane is in copy mode and +use an inclusive range from `-scroll` through `pane_height - 1 - scroll`. +Without that range, the command can return rows closer to the live grid. +An attached client also observes presentation details such as selection and +the copy-mode position indicator. + +```{literalinclude} ../../examples/tmux_screens.py +:language: python +:start-at: Read the mode grid +:end-before: Leave copy mode +:dedent: 16 +``` + +On builds that omit `-M`, use the attached snapshot for the visible rows. +Control mode can supply application output and layout changes to a test through +{mod}`libvt.contrib.tmux.control`. Use the attached PTY to observe tmux's +rendering of that layout. + +## Translate a click after resize + +Cancel copy mode, resize the attached PTY, and wait for tmux to report the new +client and window dimensions. Query `#{pane_top}` and `#{pane_left}` again. +For this single-client, unpanned window with status at the top, add the +one-row status line and the pane origin to the target's local row and column. +Here `PIN` holds the target's `(row, column)` inside the picker. + +```{literalinclude} ../../examples/tmux_screens.py +:language: python +:start-at: outer_row = 1 + top + PIN[0] +:end-at: outer_col = left + PIN[1] +:dedent: 20 +``` + +Use zero-based rows and columns for {class}`~libvt.input.MouseEvent`. The +encoder converts them to the one-based coordinates on the mouse protocol +wire. Check the target against the attached snapshot. Borders and status +cells belong to tmux. A change to the window, status position, or a viewport +offset can change the mapping. + +The picker starts unfocused. With mouse enabled and the example server's +default bindings, the click focuses it. The example sends both button edges +and waits for the picker to report the pane-local coordinates before checking +the active pane and sending the key. + +```{literalinclude} ../../examples/tmux_screens.py +:language: python +:start-at: MouseEvent accepts zero-based +:end-before: The child has received +:dedent: 16 +``` + +## Run the example + +From the repository root with libvt installed, run the +{download}`example <../../examples/tmux_screens.py>` on POSIX with tmux 3.1 or +newer that advertises `capture-pane -N`. The example starts a private server +and shuts it down on exit. + +```console +$ python examples/tmux_screens.py +``` + +Use `--tmux` to select another binary. Run with `--stale-origin` to see the +picker receive column 11 in place of column 3 after the split's origin moves. diff --git a/examples/last_beacon/game.py b/examples/last_beacon/game.py new file mode 100644 index 00000000..4a906c76 --- /dev/null +++ b/examples/last_beacon/game.py @@ -0,0 +1,246 @@ +"""Play The Last Beacon, an original game written for libvt's examples.""" + +from __future__ import annotations + +import argparse +import collections.abc +import contextlib +import os +import select +import signal +import sys +from dataclasses import dataclass + +TITLE = "THE LAST BEACON" +QUAY, HALL, CHART = "Lantern Quay", "Beacon Hall", "Chart Room" +ROOMS = { + QUAY: ("The shore light has gone dark.", {"north": HALL, "east": CHART}), + HALL: ("A brass lock holds the wick.", {"south": QUAY}), + CHART: ("A chalk arrow points north from the quay.", {"west": QUAY}), +} +WIN = "The beacon is lit!" +HELP = "take key / north / light beacon / quit" +QUIT = {"quit", "exit"} + + +@dataclass +class Game: + """Track the room, brass key, and the last action's result.""" + + room: str = QUAY + has_key: bool = False + lit: bool = False + message: str = "Find the brass key and light the beacon." + + def move(self, direction: str) -> None: + """Move through an exit from the current room.""" + destination = ROOMS[self.room][1].get(direction) + if destination is None: + self.message = "There is no passage that way." + else: + self.room = destination + self.message = f"You go {direction}." + + def act(self, command: str) -> None: + """Apply a typed command or an arrow movement.""" + match " ".join(command.lower().split()).removeprefix("go "): + case "north" | "south" | "east" | "west" as direction: + self.move(direction) + case "take key" if self.has_key: + self.message = "You already carry the brass key." + case "take key" if self.room == QUAY: + self.has_key = True + self.message = "You take the brass key." + case "take key": + self.message = "There is no brass key here." + case "light beacon" if self.room != HALL: + self.message = "The lamp is in Beacon Hall." + case "light beacon" if not self.has_key: + self.message = "You need the brass key." + case "light beacon": + self.lit = True + self.message = WIN + case "help": + self.message = HELP + case _: + self.message = "Unknown command. Type help." + + def lines(self) -> tuple[str, ...]: + """Return the room, exits, visible key, and inventory.""" + description, exits = ROOMS[self.room] + key_here = self.room == QUAY and not self.has_key + return ( + self.room, + description, + "Exits: " + ", ".join(exits), + "On the stones: " + ("a brass key" if key_here else "nothing"), + "Pack: " + ("brass key" if self.has_key else "empty"), + "Beacon: " + ("lit" if self.lit else "dark"), + ) + + +class Editor: + """Read ASCII commands, application arrows, and bracketed paste.""" + + def __init__(self) -> None: + self.text = "" + self.escape = "" + self.pasting = False + + def feed(self, data: bytes) -> collections.abc.Iterator[str]: + """Yield each complete command while retaining a partly typed line.""" + for char in data.decode("ascii", errors="ignore"): + if char == "\x1b": + self.escape = char + elif self.escape: + self.escape += char + if self.escape in {"\x1b[", "\x1bO"}: + continue + if not "@" <= char <= "~" and len(self.escape) < 16: + continue + sequence, self.escape = self.escape, "" + match sequence: + case "\x1b[200~": + self.pasting = True + case "\x1b[201~": + self.pasting = False + case _ if not self.pasting and not self.text: + directions = { + "A": "north", + "B": "south", + "C": "east", + "D": "west", + } + if sequence[:-1] in {"\x1b[", "\x1bO"} and char in directions: + yield directions[char] + elif self.pasting: + if len(self.text) < 120 and (char.isprintable() or char.isspace()): + self.text += char if char.isprintable() else " " + elif char in "\x03\x04": + yield "quit" + elif char in "\r\n": + command, self.text = self.text.strip(), "" + if command: + yield command + elif char in "\b\x7f": + self.text = self.text[:-1] + elif char.isprintable() and len(self.text) < 120: + self.text += char + + +def redraw(game: Game, draft: str, size: os.terminal_size) -> None: + """Redraw the alternate screen with dimensions read by the child.""" + columns, rows = size + columns, rows = columns or 80, rows or 24 + header = f"{TITLE} | {columns}x{rows}" + lines = [("1;36", header), ("1;33", game.room)] + lines.extend(("0", line) for line in game.lines()[1:]) + lines.append(("2", "Arrows move. Type help or quit.")) + display = [ + f"\x1b[{row};1H\x1b[{style}m{text[:columns]}\x1b[0m" + for row, (style, text) in enumerate(lines[: max(0, rows - 2)], 1) + ] + if rows > 1: + style = "1;32" if game.message == WIN else "0" + display.append( + f"\x1b[{rows - 1};1H\x1b[{style}m{game.message[:columns]}\x1b[0m" + ) + prompt = ("> " + draft[-max(1, columns - 3) :])[:columns] + display.append(f"\x1b[{rows};1H\x1b[1;36m{prompt}\x1b[0m") + sys.stdout.write("\x1b[?2026h\x1b[H\x1b[2J" + "".join(display) + "\x1b[?2026l") + sys.stdout.flush() + + +@contextlib.contextmanager +def raw_terminal() -> collections.abc.Generator[None]: + """Restore terminal modes and the primary screen on exit.""" + if sys.platform == "win32": + message = "Full-screen play requires a POSIX terminal" + raise NotImplementedError(message) + + import termios + import tty + + fd = sys.stdin.fileno() + saved = termios.tcgetattr(fd) + + def stop(*_args: object) -> None: + raise SystemExit(0) + + previous = signal.signal(signal.SIGTERM, stop) + try: + tty.setraw(fd) + sys.stdout.write("\x1b[?1049h\x1b[?1h\x1b[?2004h") + sys.stdout.flush() + yield + finally: + try: + sys.stdout.write("\x1b[?2026l\x1b[0m\x1b[?2004l\x1b[?1l\x1b[?1049l") + sys.stdout.flush() + finally: + termios.tcsetattr(fd, termios.TCSANOW, saved) + signal.signal(signal.SIGTERM, previous) + + +def play() -> None: + """Play on a local POSIX terminal with arrows and a command prompt.""" + game, editor = Game(), Editor() + fd = sys.stdin.fileno() + with raw_terminal(): + size = os.get_terminal_size(sys.stdout.fileno()) + redraw(game, editor.text, size) + while True: + ready, _, _ = select.select([fd], [], [], 0.1) + if ready: + data = os.read(fd, 4096) + if not data: + return + for command in editor.feed(data): + if command.lower() in QUIT: + return + game.act(command) + current_size = os.get_terminal_size(sys.stdout.fileno()) + if ready or current_size != size: + size = current_size + redraw(game, editor.text, size) + + +def transcript() -> None: + """Play by typing one command per line on any supported Python.""" + game = Game() + sys.stdout.write(TITLE + "\n") + while True: + sys.stdout.write("\n".join((*game.lines(), game.message)) + "\n") + sys.stdout.flush() + try: + command = input("> ").strip() + except EOFError: + return + if command.lower() in QUIT: + return + game.act(command) + + +def main() -> None: + """Use a full-screen POSIX terminal, with line input elsewhere.""" + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "--transcript", action="store_true", help="use one command per line" + ) + args = parser.parse_args() + try: + if ( + args.transcript + or os.name != "posix" + or not sys.stdin.isatty() + or not sys.stdout.isatty() + ): + transcript() + else: + play() + except KeyboardInterrupt: + pass + + +if __name__ == "__main__": + main() diff --git a/examples/last_beacon/tour.py b/examples/last_beacon/tour.py new file mode 100644 index 00000000..fe23c413 --- /dev/null +++ b/examples/last_beacon/tour.py @@ -0,0 +1,210 @@ +"""Win The Last Beacon on a PTY or replay its captured screens offline.""" + +from __future__ import annotations + +import argparse +import asyncio +import base64 +import json +import pathlib +import sys +import typing as t + +from libvt import Limits, Snapshot, Terminal +from libvt.aio import open_pty +from libvt.style import AnsiColor +from libvt.terminal import FlightRecorder +from libvt.testing import serialize_vt_snapshot + +HERE = pathlib.Path(__file__).resolve().parent +RECORDING = HERE / "walkthrough.json" +START_ROWS, START_COLS = 14, 60 +WIN_ROWS, WIN_COLS = 10, 45 +VICTORY = "The beacon is lit!" + + +class Frame(t.TypedDict): + """A viewport checkpoint and the bytes received since the last one.""" + + name: str + rows: int + cols: int + output: str + screen: str + + +def assert_victory(view: Snapshot) -> None: + """Check the message, style, and command prompt at the end of the game.""" + if view.lines[-2] != VICTORY: + msg = f"Expected {VICTORY!r} in the victory frame, got {view.lines[-2]!r}" + raise ValueError(msg) + ink = view[view.rows - 2, 0].style + if not ink.bold or ink.fg != AnsiColor.GREEN: + msg = f"Victory message has the wrong style: {ink}" + raise ValueError(msg) + if (view.cursor.row, view.cursor.col) != (view.rows - 1, 2): + msg = "Victory frame cursor moved away from the command prompt" + raise ValueError(msg) + + +async def play(destination: pathlib.Path | None) -> Snapshot: + """Drive the real child and optionally save its output and size changes.""" + frames: list[Frame] = [] + offset = 0 + async with open_pty( + (sys.executable, str(HERE / "game.py")), + rows=START_ROWS, + cols=START_COLS, + limits=Limits(max_recorder_bytes=16 * 1024), + ) as player: + recorder = player.terminal.recorder + if not isinstance(recorder, FlightRecorder): + msg = "Recording requires a FlightRecorder" + raise TypeError(msg) + + async def capture( + name: str, room: str, message: str, rows: int, cols: int + ) -> Snapshot: + nonlocal offset + view = await player.wait_for( + lambda screen: ( + screen.lines[0] == f"THE LAST BEACON | {cols}x{rows}" + and screen.lines[1] == room + and screen.lines[-2] == message + ), + timeout=5, + ) + if (view.rows, view.cols) != (rows, cols): + msg = f"Expected {cols}x{rows} at checkpoint {name!r}" + raise ValueError(msg) + if destination is not None: + raw = recorder.tail(recorder.total_bytes) + if len(raw) != recorder.total_bytes: + msg = "The recording buffer filled before the checkpoint" + raise ValueError(msg) + frames.append( + { + "name": name, + "rows": rows, + "cols": cols, + "output": base64.b64encode(raw[offset:]).decode("ascii"), + "screen": serialize_vt_snapshot(view), + } + ) + offset = len(raw) + return view + + arrival = await capture( + "arrival", + "Lantern Quay", + "Find the brass key and light the beacon.", + START_ROWS, + START_COLS, + ) + player.paste("take key") + player.send_key("enter") + await capture( + "key", "Lantern Quay", "You take the brass key.", START_ROWS, START_COLS + ) + + player.send_key("up") + await capture("hall", "Beacon Hall", "You go north.", START_ROWS, START_COLS) + + player.resize(rows=WIN_ROWS, cols=WIN_COLS) + await capture("resize", "Beacon Hall", "You go north.", WIN_ROWS, WIN_COLS) + + player.paste("light beacon") + player.send_key("enter") + victory = await capture("win", "Beacon Hall", VICTORY, WIN_ROWS, WIN_COLS) + assert_victory(victory) + if arrival.lines[1] != "Lantern Quay" or arrival.cols != START_COLS: + msg = "The saved arrival frame changed during the game" + raise ValueError(msg) + player.send_key("ctrl+d") + status = await asyncio.wait_for(player.process.wait(), timeout=5) + if status: + msg = f"The game exited with status {status}" + raise ChildProcessError(msg) + + if destination is not None: + destination.write_text( + json.dumps(frames, ensure_ascii=False, indent=2) + "\n", encoding="utf-8" + ) + return victory + + +def _is_frame(value: object) -> t.TypeGuard[Frame]: + if not isinstance(value, dict): + return False + return ( + isinstance(value.get("name"), str) + and isinstance(value.get("output"), str) + and isinstance(value.get("screen"), str) + and type(value.get("rows")) is int + and value["rows"] > 0 + and type(value.get("cols")) is int + and value["cols"] > 0 + ) + + +def replay(source: pathlib.Path, chunk_size: int) -> Snapshot: + """Feed the captured output in chunks, checking each recorded checkpoint.""" + if chunk_size < 1: + message = "chunk size must be positive" + raise ValueError(message) + frames: object = json.loads(source.read_text(encoding="utf-8")) + if not isinstance(frames, list) or not frames: + msg = "A recording must contain at least one checkpoint" + raise ValueError(msg) + terminal = Terminal(rows=START_ROWS, cols=START_COLS) + for number, frame in enumerate(frames, 1): + if not _is_frame(frame): + msg = f"Invalid checkpoint {number} in {source}" + raise ValueError(msg) + rows, cols = frame["rows"], frame["cols"] + if (terminal.rows, terminal.cols) != (rows, cols): + terminal.resize(rows=rows, cols=cols) + chunk = base64.b64decode(frame["output"], validate=True) + for offset in range(0, len(chunk), chunk_size): + terminal.feed(chunk[offset : offset + chunk_size]) + if serialize_vt_snapshot(terminal.committed) != frame["screen"]: + msg = f"Screen differs at checkpoint {frame['name']!r}" + raise ValueError(msg) + victory = terminal.committed + assert_victory(victory) + return victory + + +def main() -> None: + """Run the live game, save a recording, or replay a recording.""" + parser = argparse.ArgumentParser(description=__doc__) + modes = parser.add_mutually_exclusive_group() + modes.add_argument("--record", type=pathlib.Path, help="save a live game to FILE") + modes.add_argument( + "--replay", + nargs="?", + const=RECORDING, + type=pathlib.Path, + metavar="FILE", + help="replay FILE or the bundled recording", + ) + parser.add_argument( + "--chunk-size", type=int, default=17, help="bytes per replay feed" + ) + args = parser.parse_args() + if args.replay is not None: + if args.chunk_size < 1: + parser.error("--chunk-size must be positive") + try: + view = replay(args.replay, args.chunk_size) + except (OSError, ValueError) as error: + parser.exit(1, f"{parser.prog}: {error}\n") + else: + if sys.platform == "win32": + parser.error("live play requires a POSIX PTY; use --replay") + view = asyncio.run(play(args.record)) + sys.stdout.buffer.write((serialize_vt_snapshot(view) + "\n").encode("utf-8")) + + +if __name__ == "__main__": + main() diff --git a/examples/last_beacon/walkthrough.json b/examples/last_beacon/walkthrough.json new file mode 100644 index 00000000..e3f1ea19 --- /dev/null +++ b/examples/last_beacon/walkthrough.json @@ -0,0 +1,37 @@ +[ + { + "name": "arrival", + "rows": 14, + "cols": 60, + "output": "G1s/MTA0OWgbWz8xaBtbPzIwMDRoG1s/MjAyNmgbW0gbWzJKG1sxOzFIG1sxOzM2bVRIRSBMQVNUIEJFQUNPTiAgfCAgNjB4MTQbWzBtG1syOzFIG1sxOzMzbUxhbnRlcm4gUXVheRtbMG0bWzM7MUgbWzBtVGhlIHNob3JlIGxpZ2h0IGhhcyBnb25lIGRhcmsuG1swbRtbNDsxSBtbMG1FeGl0czogbm9ydGgsIGVhc3QbWzBtG1s1OzFIG1swbU9uIHRoZSBzdG9uZXM6IGEgYnJhc3Mga2V5G1swbRtbNjsxSBtbMG1QYWNrOiBlbXB0eRtbMG0bWzc7MUgbWzBtQmVhY29uOiBkYXJrG1swbRtbODsxSBtbMm1BcnJvd3MgbW92ZS4gVHlwZSBoZWxwIG9yIHF1aXQuG1swbRtbMTM7MUgbWzBtRmluZCB0aGUgYnJhc3Mga2V5IGFuZCBsaWdodCB0aGUgYmVhY29uLhtbMG0bWzE0OzFIG1sxOzM2bT4gG1swbRtbPzIwMjZs", + "screen": "size=60x14 cursor=(13,2,vis=True) alt=True modes=[DECCKM,BRACKETED_PASTE]\n┌────────────────────────────────────────────────────────────┐\n│THE LAST BEACON | 60x14 │\n│Lantern Quay │\n│The shore light has gone dark. │\n│Exits: north, east │\n│On the stones: a brass key │\n│Pack: empty │\n│Beacon: dark │\n│Arrows move. Type help or quit. │\n│ │\n│ │\n│ │\n│ │\n│Find the brass key and light the beacon. │\n│> │\n└────────────────────────────────────────────────────────────┘\nstyles:\n r0[0..25]: bold fg=cyan\n r1[0..12]: bold fg=yellow\n r7[0..31]: dim\n r13[0..2]: bold fg=cyan" + }, + { + "name": "key", + "rows": 14, + "cols": 60, + "output": "G1s/MjAyNmgbW0gbWzJKG1sxOzFIG1sxOzM2bVRIRSBMQVNUIEJFQUNPTiAgfCAgNjB4MTQbWzBtG1syOzFIG1sxOzMzbUxhbnRlcm4gUXVheRtbMG0bWzM7MUgbWzBtVGhlIHNob3JlIGxpZ2h0IGhhcyBnb25lIGRhcmsuG1swbRtbNDsxSBtbMG1FeGl0czogbm9ydGgsIGVhc3QbWzBtG1s1OzFIG1swbU9uIHRoZSBzdG9uZXM6IG5vdGhpbmcbWzBtG1s2OzFIG1swbVBhY2s6IGJyYXNzIGtleRtbMG0bWzc7MUgbWzBtQmVhY29uOiBkYXJrG1swbRtbODsxSBtbMm1BcnJvd3MgbW92ZS4gVHlwZSBoZWxwIG9yIHF1aXQuG1swbRtbMTM7MUgbWzBtWW91IHRha2UgdGhlIGJyYXNzIGtleS4bWzBtG1sxNDsxSBtbMTszNm0+IBtbMG0bWz8yMDI2bA==", + "screen": "size=60x14 cursor=(13,2,vis=True) alt=True modes=[DECCKM,BRACKETED_PASTE]\n┌────────────────────────────────────────────────────────────┐\n│THE LAST BEACON | 60x14 │\n│Lantern Quay │\n│The shore light has gone dark. │\n│Exits: north, east │\n│On the stones: nothing │\n│Pack: brass key │\n│Beacon: dark │\n│Arrows move. Type help or quit. │\n│ │\n│ │\n│ │\n│ │\n│You take the brass key. │\n│> │\n└────────────────────────────────────────────────────────────┘\nstyles:\n r0[0..25]: bold fg=cyan\n r1[0..12]: bold fg=yellow\n r7[0..31]: dim\n r13[0..2]: bold fg=cyan" + }, + { + "name": "hall", + "rows": 14, + "cols": 60, + "output": "G1s/MjAyNmgbW0gbWzJKG1sxOzFIG1sxOzM2bVRIRSBMQVNUIEJFQUNPTiAgfCAgNjB4MTQbWzBtG1syOzFIG1sxOzMzbUJlYWNvbiBIYWxsG1swbRtbMzsxSBtbMG1BIGJyYXNzIGxvY2sgaG9sZHMgdGhlIHdpY2suG1swbRtbNDsxSBtbMG1FeGl0czogc291dGgbWzBtG1s1OzFIG1swbU9uIHRoZSBzdG9uZXM6IG5vdGhpbmcbWzBtG1s2OzFIG1swbVBhY2s6IGJyYXNzIGtleRtbMG0bWzc7MUgbWzBtQmVhY29uOiBkYXJrG1swbRtbODsxSBtbMm1BcnJvd3MgbW92ZS4gVHlwZSBoZWxwIG9yIHF1aXQuG1swbRtbMTM7MUgbWzBtWW91IGdvIG5vcnRoLhtbMG0bWzE0OzFIG1sxOzM2bT4gG1swbRtbPzIwMjZs", + "screen": "size=60x14 cursor=(13,2,vis=True) alt=True modes=[DECCKM,BRACKETED_PASTE]\n┌────────────────────────────────────────────────────────────┐\n│THE LAST BEACON | 60x14 │\n│Beacon Hall │\n│A brass lock holds the wick. │\n│Exits: south │\n│On the stones: nothing │\n│Pack: brass key │\n│Beacon: dark │\n│Arrows move. Type help or quit. │\n│ │\n│ │\n│ │\n│ │\n│You go north. │\n│> │\n└────────────────────────────────────────────────────────────┘\nstyles:\n r0[0..25]: bold fg=cyan\n r1[0..11]: bold fg=yellow\n r7[0..31]: dim\n r13[0..2]: bold fg=cyan" + }, + { + "name": "resize", + "rows": 10, + "cols": 45, + "output": "G1s/MjAyNmgbW0gbWzJKG1sxOzFIG1sxOzM2bVRIRSBMQVNUIEJFQUNPTiAgfCAgNDV4MTAbWzBtG1syOzFIG1sxOzMzbUJlYWNvbiBIYWxsG1swbRtbMzsxSBtbMG1BIGJyYXNzIGxvY2sgaG9sZHMgdGhlIHdpY2suG1swbRtbNDsxSBtbMG1FeGl0czogc291dGgbWzBtG1s1OzFIG1swbU9uIHRoZSBzdG9uZXM6IG5vdGhpbmcbWzBtG1s2OzFIG1swbVBhY2s6IGJyYXNzIGtleRtbMG0bWzc7MUgbWzBtQmVhY29uOiBkYXJrG1swbRtbODsxSBtbMm1BcnJvd3MgbW92ZS4gVHlwZSBoZWxwIG9yIHF1aXQuG1swbRtbOTsxSBtbMG1Zb3UgZ28gbm9ydGguG1swbRtbMTA7MUgbWzE7MzZtPiAbWzBtG1s/MjAyNmw=", + "screen": "size=45x10 cursor=(9,2,vis=True) alt=True modes=[DECCKM,BRACKETED_PASTE]\n┌─────────────────────────────────────────────┐\n│THE LAST BEACON | 45x10 │\n│Beacon Hall │\n│A brass lock holds the wick. │\n│Exits: south │\n│On the stones: nothing │\n│Pack: brass key │\n│Beacon: dark │\n│Arrows move. Type help or quit. │\n│You go north. │\n│> │\n└─────────────────────────────────────────────┘\nstyles:\n r0[0..25]: bold fg=cyan\n r1[0..11]: bold fg=yellow\n r7[0..31]: dim\n r9[0..2]: bold fg=cyan" + }, + { + "name": "win", + "rows": 10, + "cols": 45, + "output": "G1s/MjAyNmgbW0gbWzJKG1sxOzFIG1sxOzM2bVRIRSBMQVNUIEJFQUNPTiAgfCAgNDV4MTAbWzBtG1syOzFIG1sxOzMzbUJlYWNvbiBIYWxsG1swbRtbMzsxSBtbMG1BIGJyYXNzIGxvY2sgaG9sZHMgdGhlIHdpY2suG1swbRtbNDsxSBtbMG1FeGl0czogc291dGgbWzBtG1s1OzFIG1swbU9uIHRoZSBzdG9uZXM6IG5vdGhpbmcbWzBtG1s2OzFIG1swbVBhY2s6IGJyYXNzIGtleRtbMG0bWzc7MUgbWzBtQmVhY29uOiBkYXJrG1swbRtbODsxSBtbMm1BcnJvd3MgbW92ZS4gVHlwZSBoZWxwIG9yIHF1aXQuG1swbRtbOTsxSBtbMG1Zb3UgZ28gbm9ydGguG1swbRtbMTA7MUgbWzE7MzZtPiBsaWdodCBiZWFjb24bWzBtG1s/MjAyNmwbWz8yMDI2aBtbSBtbMkobWzE7MUgbWzE7MzZtVEhFIExBU1QgQkVBQ09OICB8ICA0NXgxMBtbMG0bWzI7MUgbWzE7MzNtQmVhY29uIEhhbGwbWzBtG1szOzFIG1swbUEgYnJhc3MgbG9jayBob2xkcyB0aGUgd2ljay4bWzBtG1s0OzFIG1swbUV4aXRzOiBzb3V0aBtbMG0bWzU7MUgbWzBtT24gdGhlIHN0b25lczogbm90aGluZxtbMG0bWzY7MUgbWzBtUGFjazogYnJhc3Mga2V5G1swbRtbNzsxSBtbMG1CZWFjb246IGxpdBtbMG0bWzg7MUgbWzJtQXJyb3dzIG1vdmUuIFR5cGUgaGVscCBvciBxdWl0LhtbMG0bWzk7MUgbWzE7MzJtVGhlIGJlYWNvbiBpcyBsaXQhG1swbRtbMTA7MUgbWzE7MzZtPiAbWzBtG1s/MjAyNmw=", + "screen": "size=45x10 cursor=(9,2,vis=True) alt=True modes=[DECCKM,BRACKETED_PASTE]\n┌─────────────────────────────────────────────┐\n│THE LAST BEACON | 45x10 │\n│Beacon Hall │\n│A brass lock holds the wick. │\n│Exits: south │\n│On the stones: nothing │\n│Pack: brass key │\n│Beacon: lit │\n│Arrows move. Type help or quit. │\n│The beacon is lit! │\n│> │\n└─────────────────────────────────────────────┘\nstyles:\n r0[0..25]: bold fg=cyan\n r1[0..11]: bold fg=yellow\n r7[0..31]: dim\n r8[0..18]: bold fg=green\n r9[0..2]: bold fg=cyan" + } +] diff --git a/examples/replay_prompt.py b/examples/replay_prompt.py new file mode 100644 index 00000000..9440f8e6 --- /dev/null +++ b/examples/replay_prompt.py @@ -0,0 +1,17 @@ +"""A deliberately failing screen assertion for the pytest replay guide.""" + +from __future__ import annotations + +from libvt.pytest_plugin import TerminalFactory +from libvt.testing import assert_screen + + +def test_prompt(vt_factory: TerminalFactory) -> None: + """Draw while the terminal is narrow and leave a written space after X.""" + term = vt_factory(rows=2, cols=8) + term.resize(rows=2, cols=4, reflow=False) + term.feed(b"\x1b[1;7") + term.feed(b"HX") + term.resize(rows=2, cols=8, reflow=False) + term.feed(b"\x1b[1;5H ") + assert_screen(term, [" X"]) diff --git a/examples/tmux_screens.py b/examples/tmux_screens.py new file mode 100644 index 00000000..16efdce3 --- /dev/null +++ b/examples/tmux_screens.py @@ -0,0 +1,322 @@ +"""Compare tmux pane and attached-client screens, then click after a resize.""" + +from __future__ import annotations + +import argparse +import asyncio +import functools +import os +import pathlib +import shutil +import subprocess +import sys +import tempfile + +from libvt.aio import open_pty +from libvt.contrib.tmux import ( + build_tmux_capture_command, + parse_tmux_version, + tmux_profile, +) +from libvt.input import MouseAction, MouseButton, MouseEvent +from libvt.profiles import XTERM_PROFILE +from libvt.style import AnsiColor + +START = (12, 84) +RESIZED = (14, 68) +PIN = (2, 3) + + +def _check(condition: bool, message: str) -> None: + if not condition: + raise AssertionError(message) + + +async def _run(*argv: str, env: dict[str, str], check: bool = True) -> str: + """Read both pipes while the attached client continues to receive output.""" + proc = await asyncio.create_subprocess_exec( + *argv, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, env=env + ) + try: + async with asyncio.timeout(5): + output, error = await proc.communicate() + finally: + if proc.returncode is None: + proc.kill() + await proc.communicate() + if check and proc.returncode: + raise subprocess.CalledProcessError(proc.returncode, argv, output, error) + return output.decode().rstrip("\n") + + +def _guest(role: str) -> None: + if sys.platform == "win32": + msg = "The tmux example requires a POSIX terminal" + raise NotImplementedError(msg) + + import tty + + if role == "archive": + for number in range(32): + sys.stdout.write(f"Ledger entry {number:02}\n") + sys.stdout.write("ARCHIVE LIVE\n") + sys.stdout.flush() + sys.stdin.read() + return + + tty.setraw(0) + os.write(1, b"\x1b[?1000;1006hPicker READY\x1b[3;4H[Pin]") + for label, edge, line in (("press", b"M", 5), ("release", b"m", 6)): + packet = bytearray() + while (byte := os.read(0, 1)) not in (b"M", b"m"): + if not byte: + msg = "Incomplete mouse report" + raise EOFError(msg) + packet.extend(byte) + _check(packet.startswith(b"\x1b[<") and byte == edge, f"Mouse bytes {packet!r}") + button, col, row = map(int, packet[3:].split(b";")) + _check(button == 0, f"Expected the left mouse button, received {button}") + os.write( + 1, f"\x1b[{line};1HPicker {label} row={row - 1} col={col - 1}".encode() + ) + key = os.read(0, 1) + os.write(1, b"\x1b[7;1HPicker key " + key) + sys.stdin.read() + + +async def _demo(binary: str, version: str, *, stale_origin: bool) -> None: + env = dict(os.environ, TERM="xterm-256color") + env.pop("TMUX", None) + env.pop("TMUX_PANE", None) + profile = tmux_profile(version) + + with tempfile.TemporaryDirectory(prefix="vt-tmux-") as folder: + env["TMPDIR"] = folder + socket = pathlib.Path(folder) / "s" + server = [binary, "-u", "-S", str(socket), "-f", "/dev/null"] + + tm = functools.partial(_run, *server, env=env) + + commands = await tm("list-commands", "capture-pane") + flags = commands.partition("[")[2].partition("]")[0] + if "N" not in flags: + msg = "This example requires a tmux build with capture-pane -N" + raise RuntimeError(msg) + + async def geometry(pane: str) -> tuple[int, int, int, int]: + value = await tm( + "display-message", + "-p", + "-t", + pane, + "#{pane_top} #{pane_left} #{pane_height} #{pane_width}", + ) + top, left, height, width = map(int, value.split()) + return top, left, height, width + + async def capture(pane: str) -> tuple[str, ...]: + bundle = build_tmux_capture_command(pane, tmux_version=version) + return bundle.parse(await tm(*bundle.argv), profile=profile).snapshot.lines + + guest = [sys.executable, "-u", str(pathlib.Path(__file__).resolve()), "--guest"] + try: + archive = await tm( + "new-session", + "-d", + "-s", + "desk", + "-x", + str(START[1]), + "-y", + str(START[0]), + "-P", + "-F", + "#{pane_id}", + *guest, + "archive", + ) + await tm("set", "-g", "status", "on") + await tm("set", "-g", "status-position", "top") + await tm("set", "-g", "mouse", "on") + await tm("set", "-g", "mode-style", "fg=yellow,bg=blue") + picker = await tm( + "split-window", + "-dh", + "-t", + archive, + "-P", + "-F", + "#{pane_id}", + *guest, + "picker", + ) + await tm("select-pane", "-t", archive) + async with open_pty( + [*server, "attach-session", "-t", "=desk"], + rows=START[0], + cols=START[1], + profile=XTERM_PROFILE, + env=env, + ) as client: + await client.wait_for("ARCHIVE LIVE", timeout=6) + await client.wait_for("Picker READY", timeout=6) + + # Compare the application grid with the rendered client. + await tm("copy-mode", "-t", archive) + await tm("send-keys", "-X", "-t", archive, "history-top") + await tm("send-keys", "-X", "-t", archive, "begin-selection") + await tm("send-keys", "-X", "-t", archive, "cursor-right") + pane_y, pane_x, height, width = await geometry(archive) + # This example puts one status row above the window. + client_y = 1 + pane_y + rows = slice(client_y, client_y + height) + cols = slice(pane_x, pane_x + width) + ledger = tuple(f"Ledger entry {index:02}" for index in range(height)) + visible = await client.wait_for( + lambda snap: ( + snap[client_y, pane_x].style.bg == AnsiColor.BLUE + and all( + row.startswith(label) + for row, label in zip( + snap[rows, cols].lines, ledger, strict=True + ) + ) + ), + timeout=6, + ) + _check(visible[client_y, pane_x].text == "L", "Missing selected L") + _check( + visible[client_y, pane_x + 4].style.bg != AnsiColor.BLUE, + "Selection extends past the marked cells", + ) + app = await capture(archive) + _check( + "ARCHIVE LIVE" in app and "Ledger entry 00" not in app, + "Pane capture did not show the live archive", + ) + sys.stdout.write( + "app pane: ARCHIVE LIVE\nattached copy mode: Ledger entry 00\n" + ) + + # Read the mode grid at the current scroll offset. + if "M" in flags: + scroll = int( + await tm( + "display-message", "-p", "-t", archive, "#{scroll_position}" + ) + ) + mode_rows = await tm( + "capture-pane", + "-p", + "-M", + "-t", + archive, + "-S", + str(-scroll), + "-E", + str(height - 1 - scroll), + ) + attached_rows = visible[rows, cols].lines + # Compare ledger labels before any copy-mode decorations. + label_width = len(ledger[0]) + _check( + tuple(row[:label_width] for row in mode_rows.splitlines()) + == tuple(row[:label_width] for row in attached_rows), + "Copy-mode rows differ from the attached viewport", + ) + sys.stdout.write("mode capture at scroll offset: Ledger entry 00\n") + + # Leave copy mode before sending application input. + await tm("send-keys", "-X", "-t", archive, "cancel") + await client.wait_for("ARCHIVE LIVE", timeout=6) + old_left = (await geometry(picker))[1] + client.resize(rows=RESIZED[0], cols=RESIZED[1]) + deadline = asyncio.get_running_loop().time() + 6 + while True: + native = await tm( + "list-clients", + "-F", + "#{client_height} #{client_width} " + "#{window_height} #{window_width}", + ) + top, left, pane_rows, pane_cols = await geometry(picker) + snap = client.terminal.committed + outer_row = 1 + top + PIN[0] + outer_col = left + PIN[1] + if ( + native + == f"{RESIZED[0]} {RESIZED[1]} {RESIZED[0] - 1} {RESIZED[1]}" + and left != old_left + and (snap.rows, snap.cols) == RESIZED + and 0 <= PIN[0] < pane_rows + and 0 <= PIN[1] < pane_cols + and snap[outer_row, outer_col].text == "[" + ): + break + if asyncio.get_running_loop().time() >= deadline: + msg = ( + f"Client and picker did not settle after resize: {native!r}" + ) + raise AssertionError(msg) + await asyncio.sleep(0.025) + + active = await tm("display-message", "-p", "-t", "desk:", "#{pane_id}") + _check( + active == archive, + f"Expected the archive to own focus, got {active}", + ) + if stale_origin: + outer_col = old_left + PIN[1] + + # MouseEvent accepts zero-based outer coordinates and encodes them. + for edge in (MouseAction.PRESS, MouseAction.RELEASE): + client.send_event( + MouseEvent(MouseButton.LEFT, edge, outer_row, outer_col) + ) + receipt = await client.wait_for("Picker release", timeout=6) + want = f"Picker release row={PIN[0]} col={PIN[1]}" + actual = receipt[1 + top + 5, left : left + pane_cols].lines[0] + _check( + actual == want, + f"Picker reported {actual.removeprefix('Picker ')}, wanted {want}", + ) + _check( + f"Picker press row={PIN[0]} col={PIN[1]}" in receipt.text, + "Picker missed the button press", + ) + active = await tm("display-message", "-p", "-t", "desk:", "#{pane_id}") + _check( + active == picker, f"Expected the picker to own focus, got {active}" + ) + client.send_key("v") + await client.wait_for("Picker key v", timeout=6) + # The child has received both button edges and the key. + sys.stdout.write(f"Picker received press, release and key at {PIN}\n") + finally: + await tm("kill-server", check=False) + + +def _main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--tmux", default="tmux", help="tmux executable") + parser.add_argument( + "--stale-origin", action="store_true", help="Reuse the old pane origin" + ) + parser.add_argument( + "--guest", choices=("archive", "picker"), help=argparse.SUPPRESS + ) + args = parser.parse_args() + if args.guest: + _guest(args.guest) + else: + binary = shutil.which(args.tmux) + if binary is None: + parser.error(f"Cannot find tmux executable {args.tmux!r}") + version = subprocess.check_output([binary, "-V"], text=True, timeout=5).strip() + if parse_tmux_version(version) < (3, 1): + parser.error("The example requires tmux 3.1 or newer with capture-pane -N") + asyncio.run(_demo(binary, version, stale_origin=args.stale_origin)) + + +if __name__ == "__main__": + _main() diff --git a/src/libvt/__main__.py b/src/libvt/__main__.py index 8f652607..140abd8a 100644 --- a/src/libvt/__main__.py +++ b/src/libvt/__main__.py @@ -1,4 +1,4 @@ -"""Command-line entry point for ``python -m libvt`` (explain, render, strip).""" +"""Command-line entry point for ``python -m libvt`` (explain, render, replay, strip).""" from __future__ import annotations @@ -32,7 +32,7 @@ def main(argv: list[str] | None = None) -> int: """Run ``python -m libvt`` subcommands.""" parser = argparse.ArgumentParser( prog="python -m libvt", - description="Inspect, render, or strip VT byte streams.", + description="Inspect VT byte streams and replay terminal failures.", ) sub = parser.add_subparsers(dest="command", required=True) @@ -51,6 +51,16 @@ def main(argv: list[str] | None = None) -> int: p_strip = sub.add_parser("strip", help="Strip VT control sequences from input") p_strip.add_argument("file", nargs="?", default="-", help="Input file or '-'") + p_replay = sub.add_parser( + "replay", help="Replay a pytest terminal failure artifact" + ) + p_replay.add_argument("file", help="Replay artifact file or '-'") + p_replay.add_argument( + "--chunk-size", + type=_positive_dimension, + help="Split each feed into N-byte chunks", + ) + args = parser.parse_args(argv) try: raw = _read_input(args.file) @@ -58,6 +68,16 @@ def main(argv: list[str] | None = None) -> int: path = sanitize_terminal_text(args.file) parser.error(f"cannot read {path}: {exc.strerror or exc}") + if args.command == "replay": + from libvt._replay import _format_replay + + try: + out, matches = _format_replay(raw, args.chunk_size) + except ValueError as exc: + p_replay.error(sanitize_terminal_text(str(exc))) + sys.stdout.buffer.write((out + "\n").encode("utf-8")) + return 0 if matches else 1 + if args.command == "explain": out = format_explain(raw) elif args.command == "render": diff --git a/src/libvt/_replay.py b/src/libvt/_replay.py new file mode 100644 index 00000000..8342e594 --- /dev/null +++ b/src/libvt/_replay.py @@ -0,0 +1,314 @@ +"""Bounded capture and offline playback of terminal assertion failures.""" + +from __future__ import annotations + +import collections.abc +import json +import typing as t + +from libvt._ucd import sanitize_terminal_text +from libvt._util import _byte_view +from libvt.parser import ParserEncoding +from libvt.snapshot import Snapshot +from libvt.terminal import Terminal +from libvt.testing import serialize_vt_snapshot + +_MAX_BYTES = 1_048_576 +_MAX_EVENTS = 10_000 +_MAX_CELLS = 100_000 + +type _Event = tuple[t.Literal["feed"], str] | tuple[t.Literal["resize"], int, int, bool] + + +class _ReplayArtifact(t.TypedDict): + version: int + rows: int + cols: int + scrollback: int + encoding: ParserEncoding + events: list[_Event] + actual: tuple[str, ...] + frame: str + cursor: tuple[int, int] + pending_wrap: bool + viewport: tuple[int, int] + expected: list[str] | None + difference: str | None + incomplete: str | None + + +def _geometry_ok(rows: int, cols: int) -> bool: + return ( + not isinstance(rows, bool) + and not isinstance(cols, bool) + and rows > 0 + and cols > 0 + and rows * cols <= _MAX_CELLS + ) + + +class _ReplayCapture: + """Bounded :class:`~libvt.recorder.TerminalRecorder` for pytest failure replay.""" + + __slots__ = ( + "byte_count", + "cols", + "encoding", + "events", + "incomplete", + "rows", + "scrollback", + ) + + def __init__( + self, + rows: int, + cols: int, + scrollback: int, + *, + encoding: ParserEncoding = "utf-8", + supported: bool, + ) -> None: + self.rows = rows + self.cols = cols + self.scrollback = scrollback + self.encoding: ParserEncoding = encoding + self.events: list[_Event] = [] + self.byte_count = 0 + self.incomplete: str | None = None + if not supported: + self.incomplete = ( + "Capture requires default profile, policy, limits and no event callback" + ) + elif not _geometry_ok(rows, cols) or not 0 <= scrollback <= _MAX_CELLS: + self.incomplete = "Initial geometry or scrollback exceeds replay bounds" + + def on_feed(self, data: memoryview, /) -> None: + """Record a normalized 1-D C-contiguous unsigned-byte span.""" + if self.incomplete: + return + with _byte_view(data) as mv: + if not mv.nbytes: + return + if ( + self.byte_count + mv.nbytes > _MAX_BYTES + or len(self.events) >= _MAX_EVENTS + ): + self.incomplete = "Capture exceeded the byte or event limit" + return + self.byte_count += mv.nbytes + self.events.append(("feed", mv.hex())) + + def on_resize(self, rows: int, cols: int, reflow: bool, /) -> None: + """Record an explicit external terminal resize.""" + if self.incomplete: + return + if not _geometry_ok(rows, cols) or len(self.events) >= _MAX_EVENTS: + self.incomplete = "Capture exceeded the geometry or event limit" + return + self.events.append(("resize", rows, cols, reflow)) + + def artifact( + self, + snap: Snapshot, + expected: list[str] | None = None, + difference: str | None = None, + ) -> _ReplayArtifact: + """Build a JSON-serializable replay artifact for *snap*.""" + artifact: _ReplayArtifact = { + "version": 1, + "rows": self.rows, + "cols": self.cols, + "scrollback": self.scrollback, + "encoding": self.encoding, + "events": self.events.copy(), + "actual": snap.lines, + "frame": serialize_vt_snapshot(snap, include_cursor_shape=True), + "cursor": (snap.cursor.row, snap.cursor.col), + "pending_wrap": snap.cursor.pending_wrap, + "viewport": (snap.rows, snap.cols), + "expected": expected, + "difference": difference, + "incomplete": self.incomplete, + } + return artifact + + +def _frame_matches(artifact: _ReplayArtifact, snap: Snapshot, frame: str) -> bool: + return ( + snap.lines == artifact["actual"] + and (snap.cursor.row, snap.cursor.col) == artifact["cursor"] + and (snap.rows, snap.cols) == artifact["viewport"] + and snap.cursor.pending_wrap == artifact["pending_wrap"] + and frame == artifact["frame"] + ) + + +def _verify_capture(artifact: _ReplayArtifact) -> None: + if artifact["incomplete"] is not None: + return + replayed = _play( + artifact["rows"], + artifact["cols"], + artifact["scrollback"], + artifact["events"], + encoding=artifact["encoding"], + ) + if not _frame_matches( + artifact, replayed, serialize_vt_snapshot(replayed, include_cursor_shape=True) + ): + artifact["incomplete"] = ( + "Feed and resize history does not reproduce the captured screen" + ) + + +def _play( + rows: int, + cols: int, + scrollback: int, + events: collections.abc.Sequence[_Event], + chunk_size: int | None = None, + *, + encoding: ParserEncoding = "utf-8", +) -> Snapshot: + term = Terminal(rows=rows, cols=cols, scrollback=scrollback, encoding=encoding) + for event in events: + match event: + case ("feed", encoded): + data = bytes.fromhex(encoded) + if chunk_size is None: + term.feed(data) + else: + for offset in range(0, len(data), chunk_size): + term.feed(data[offset : offset + chunk_size]) + case ("resize", new_rows, new_cols, reflow): + term.resize(rows=new_rows, cols=new_cols, reflow=reflow) + return term.snapshot() + + +def _parse_encoding(raw: object) -> ParserEncoding: + if raw == "utf-8": + return "utf-8" + if raw == "latin-1": + return "latin-1" + msg = f"Invalid encoding in replay artifact: {raw!r}" + raise ValueError(msg) + + +def _read_artifact(raw: bytes) -> _ReplayArtifact: + record: object = json.loads(raw) + match record: + case { + "version": int(version), + "rows": int(rows), + "cols": int(cols), + "scrollback": int(scrollback), + "actual": list(actual), + "frame": str(frame), + "cursor": [int(row), int(col)], + "pending_wrap": bool(pending_wrap), + "viewport": [int(view_rows), int(view_cols)], + "events": list(events), + "expected": expected, + "difference": difference, + "incomplete": incomplete, + } if version == 1 and type(version) is int: + encoding = _parse_encoding(record.get("encoding", "utf-8")) + case _: + msg = "Invalid libvt replay artifact" + raise ValueError(msg) + + expected_lines: list[str] | None = None + if isinstance(expected, list): + expected_lines = [line for line in expected if isinstance(line, str)] + if len(expected_lines) != len(expected): + msg = "Invalid expected rows in replay artifact" + raise ValueError(msg) + elif expected is not None: + msg = "Invalid expected rows in replay artifact" + raise ValueError(msg) + actual_lines = tuple(line for line in actual if isinstance(line, str)) + if ( + len(actual_lines) != len(actual) + or len(actual_lines) != view_rows + or (difference is not None and not isinstance(difference, str)) + or (incomplete is not None and not isinstance(incomplete, str)) + or any(isinstance(n, bool) for n in (row, col, view_rows, view_cols)) + or len(events) > _MAX_EVENTS + ): + msg = "Invalid rows, cursor, viewport or event count in replay artifact" + raise ValueError(msg) + if incomplete is None and ( + not _geometry_ok(rows, cols) + or isinstance(scrollback, bool) + or not 0 <= scrollback <= _MAX_CELLS + ): + msg = "Replay geometry or scrollback exceeds capture limits" + raise ValueError(msg) + + validated: list[_Event] = [] + hex_length = 0 + for event in events: + match event: + case ["feed", str(encoded)]: + hex_length += len(encoded) + if hex_length > 2 * _MAX_BYTES: + msg = "Replay exceeds capture byte limit" + raise ValueError(msg) + validated.append(("feed", encoded)) + case ["resize", int(new_rows), int(new_cols), bool(reflow)] if _geometry_ok( + new_rows, new_cols + ): + validated.append(("resize", new_rows, new_cols, reflow)) + case _: + msg = "Invalid replay event" + raise ValueError(msg) + return { + "version": version, + "rows": rows, + "cols": cols, + "scrollback": scrollback, + "encoding": encoding, + "events": validated, + "actual": actual_lines, + "frame": frame, + "cursor": (row, col), + "pending_wrap": pending_wrap, + "viewport": (view_rows, view_cols), + "expected": expected_lines, + "difference": difference, + "incomplete": incomplete, + } + + +def _format_replay(raw: bytes, chunk_size: int | None) -> tuple[str, bool]: + artifact = _read_artifact(raw) + rows, cols = artifact["viewport"] + output = [f"size: {cols}x{rows}"] + if artifact["difference"] is not None: + output.append(sanitize_terminal_text(artifact["difference"])) + if artifact["incomplete"] is not None: + reason = sanitize_terminal_text(artifact["incomplete"]) + output.append(f"Replay unavailable: {reason}") + lines = artifact["actual"] + row, col = artifact["cursor"] + matches = False + else: + snap = _play( + artifact["rows"], + artifact["cols"], + artifact["scrollback"], + artifact["events"], + chunk_size, + encoding=artifact["encoding"], + ) + frame = serialize_vt_snapshot(snap, include_cursor_shape=True) + lines = snap.lines + row, col = snap.cursor.row, snap.cursor.col + matches = _frame_matches(artifact, snap, frame) + if not matches: + output.append("Replayed frame differs from the artifact") + output.append(frame) + output.extend(f"row {index}: {line!r}" for index, line in enumerate(lines)) + output.append(f"cursor: ({row}, {col})") + return "\n".join(output), matches diff --git a/src/libvt/aio/_pty.py b/src/libvt/aio/_pty.py index 79568736..22aa411e 100644 --- a/src/libvt/aio/_pty.py +++ b/src/libvt/aio/_pty.py @@ -321,6 +321,11 @@ async def _wait_for_frame(self, wait_slice: float) -> None: with contextlib.suppress(TimeoutError): await asyncio.wait_for(self._frame_event.wait(), timeout=wait_slice) + def _start_reading(self, loop: asyncio.AbstractEventLoop) -> None: + self._loop = loop + loop.add_reader(self._master_fd, self._on_readable) + self._reader_registered = True + def _remove_reader(self) -> None: if self._loop is not None and self._reader_registered: self._reader_registered = False @@ -678,6 +683,89 @@ async def _close_pty(self) -> int: return self.process.returncode or 0 +def _resolve_python_executable( + python_executable: str | os.PathLike[str] | None, + *, + caller: str = "open_pty", +) -> str: + if python_executable is None: + if getattr(sys, "frozen", False) or not sys.executable: + msg = ( + f"{caller} requires python_executable in frozen or embedded " + "Python runtimes" + ) + raise RuntimeError(msg) + return sys.executable + return os.fspath(python_executable) + + +def _make_pty_terminal( + *, + rows: int, + cols: int, + scrollback: int, + profile: Profile, + policy: Policy, + limits: Limits, + encoding: ParserEncoding = "utf-8", + record_events: bool = False, +) -> Terminal: + recorder = FlightRecorder(max_bytes=limits.max_recorder_bytes) + eff_policy = policy + if policy.osc7_hosts is None: + fqdn = socket.gethostname().lower() + short = fqdn.partition(".")[0] + eff_policy = dataclasses.replace( + policy, + osc7_hosts=DEFAULT_OSC7_HOSTS | frozenset({fqdn, short}), + ) + return Terminal( + rows=rows, + cols=cols, + scrollback=scrollback, + profile=profile, + policy=eff_policy, + limits=limits, + encoding=encoding, + record_events=record_events, + recorder=recorder, + ) + + +def _prepare_pty_fds( + master_fd: int, + slave_fd: int, + *, + rows: int, + cols: int, + profile: Profile, + tty_mode: TtyMode = "cooked", +) -> None: + if sys.platform == "win32": + msg = "POSIX PTY setup requires termios" + raise NotImplementedError(msg) + import fcntl + import termios + import tty + + fcntl.ioctl( + slave_fd, + termios.TIOCSWINSZ, + _pack_winsize(rows, cols, profile), + ) + if tty_mode == "cbreak": + tty.setcbreak(slave_fd) + elif tty_mode == "raw": + tty.setraw(slave_fd) + os.set_blocking(master_fd, False) + + +def _child_pty_env(env: collections.abc.Mapping[str, str] | None) -> dict[str, str]: + child_env = dict(os.environ if env is None else env) + child_env.setdefault("TERM", "xterm-256color") + return child_env + + @contextlib.asynccontextmanager async def open_pty( argv: collections.abc.Sequence[str], @@ -778,44 +866,19 @@ async def open_pty( raise ValueError(msg) _validate_nonneg_seconds(sync_timeout, "sync_timeout") eff_hw, eff_max = _resolve_write_limits(write_high_water, max_write_buffer) - recorder = FlightRecorder(max_bytes=limits.max_recorder_bytes) - - if python_executable is None: - if getattr(sys, "frozen", False) or not sys.executable: - msg = ( - "open_pty requires python_executable in frozen or embedded " - "Python runtimes" - ) - raise RuntimeError(msg) - py_bin = sys.executable - else: - py_bin = os.fspath(python_executable) - - eff_policy = policy - if policy.osc7_hosts is None: - fqdn = socket.gethostname().lower() - short = fqdn.partition(".")[0] - eff_policy = dataclasses.replace( - policy, - osc7_hosts=DEFAULT_OSC7_HOSTS | frozenset({fqdn, short}), - ) - - terminal = Terminal( + py_bin = _resolve_python_executable(python_executable, caller="open_pty") + terminal = _make_pty_terminal( rows=rows, cols=cols, scrollback=scrollback, profile=profile, - policy=eff_policy, + policy=policy, limits=limits, encoding=encoding, record_events=record_events, - recorder=recorder, ) - import fcntl import pty - import termios - import tty loop = asyncio.get_running_loop() master_fd, slave_fd = pty.openpty() @@ -827,19 +890,16 @@ async def open_pty( proc: asyncio.subprocess.Process | None = None try: receiver, sender = socket.socketpair() - fcntl.ioctl( + _prepare_pty_fds( + master_fd, slave_fd, - termios.TIOCSWINSZ, - _pack_winsize(rows, cols, profile), + rows=rows, + cols=cols, + profile=profile, + tty_mode=tty_mode, ) - if tty_mode == "cbreak": - tty.setcbreak(slave_fd) - elif tty_mode == "raw": - tty.setraw(slave_fd) - os.set_blocking(master_fd, False) receiver.setblocking(False) - child_env = dict(os.environ if env is None else env) - child_env.setdefault("TERM", "xterm-256color") + child_env = _child_pty_env(env) launch_fd = sender.fileno() proc = await asyncio.create_subprocess_exec( py_bin, @@ -900,8 +960,7 @@ async def open_pty( os.close(master_fd) try: - loop.add_reader(master_fd, session._on_readable) - session._reader_registered = True + session._start_reading(loop) yield session finally: await session.aclose() diff --git a/src/libvt/contrib/_conpty.py b/src/libvt/contrib/_conpty.py new file mode 100644 index 00000000..efcee90c --- /dev/null +++ b/src/libvt/contrib/_conpty.py @@ -0,0 +1,336 @@ +"""Attach a Win32 console client and adapt its pseudoconsole pipes to libvt.""" + +from __future__ import annotations + +import asyncio +import collections.abc +import contextlib +import ctypes as c +import ctypes.wintypes as w +import subprocess +import sys + +from libvt.aio import AsyncTerminalStream +from libvt.recorder import FlightRecorder +from libvt.terminal import Terminal + +from .subprocess import VT, _Attachment + +if sys.platform == "win32": + + class Coord(c.Structure): + _fields_ = [("X", w.SHORT), ("Y", w.SHORT)] + + class StartupInfo(c.Structure): + _fields_ = [ + ("cb", w.DWORD), + ("lpReserved", w.LPWSTR), + ("lpDesktop", w.LPWSTR), + ("lpTitle", w.LPWSTR), + ("dwX", w.DWORD), + ("dwY", w.DWORD), + ("dwXSize", w.DWORD), + ("dwYSize", w.DWORD), + ("dwXCountChars", w.DWORD), + ("dwYCountChars", w.DWORD), + ("dwFillAttribute", w.DWORD), + ("dwFlags", w.DWORD), + ("wShowWindow", w.WORD), + ("cbReserved2", w.WORD), + ("lpReserved2", c.c_void_p), + ("hStdInput", w.HANDLE), + ("hStdOutput", w.HANDLE), + ("hStdError", w.HANDLE), + ] + + class StartupInfoEx(c.Structure): + _fields_ = [("StartupInfo", StartupInfo), ("lpAttributeList", c.c_void_p)] + + class ProcessInfo(c.Structure): + _fields_ = [ + ("hProcess", w.HANDLE), + ("hThread", w.HANDLE), + ("pid", w.DWORD), + ("tid", w.DWORD), + ] + + class _Kernel: + def __init__(self) -> None: + self.error = c.WinError + self.last_error = c.get_last_error + kernel = c.WinDLL("kernel32", use_last_error=True) + + try: + self.release_console = kernel["ReleasePseudoConsole"] + except AttributeError as exc: + msg = "ConPTY EOF requires ReleasePseudoConsole (Windows build 26100)" + raise NotImplementedError(msg) from exc + self.release_console.restype = w.LONG + self.release_console.argtypes = (w.HANDLE,) + + self.create_console = kernel["CreatePseudoConsole"] + self.create_console.restype = w.LONG + self.create_console.argtypes = ( + Coord, + w.HANDLE, + w.HANDLE, + w.DWORD, + c.POINTER(w.HANDLE), + ) + + self.resize_console = kernel["ResizePseudoConsole"] + self.resize_console.restype = w.LONG + self.resize_console.argtypes = (w.HANDLE, Coord) + + self.close_console = kernel["ClosePseudoConsole"] + self.close_console.restype = None + self.close_console.argtypes = (w.HANDLE,) + + self.init_attrs = kernel["InitializeProcThreadAttributeList"] + self.init_attrs.restype = w.BOOL + self.init_attrs.argtypes = ( + c.c_void_p, + w.DWORD, + w.DWORD, + c.POINTER(c.c_size_t), + ) + + self.update_attr = kernel["UpdateProcThreadAttribute"] + self.update_attr.restype = w.BOOL + self.update_attr.argtypes = ( + c.c_void_p, + w.DWORD, + c.c_size_t, + c.c_void_p, + c.c_size_t, + c.c_void_p, + c.c_void_p, + ) + + self.delete_attrs = kernel["DeleteProcThreadAttributeList"] + self.delete_attrs.restype = None + self.delete_attrs.argtypes = (c.c_void_p,) + + self.create_process = kernel["CreateProcessW"] + self.create_process.restype = w.BOOL + self.create_process.argtypes = ( + w.LPCWSTR, + w.LPWSTR, + c.c_void_p, + c.c_void_p, + w.BOOL, + w.DWORD, + c.c_void_p, + w.LPCWSTR, + c.POINTER(StartupInfoEx), + c.POINTER(ProcessInfo), + ) + + self.wait_handle = kernel["WaitForSingleObject"] + self.wait_handle.restype = w.DWORD + self.wait_handle.argtypes = (w.HANDLE, w.DWORD) + + self.get_exit = kernel["GetExitCodeProcess"] + self.get_exit.restype = w.BOOL + self.get_exit.argtypes = (w.HANDLE, c.POINTER(w.DWORD)) + + self.terminate = kernel["TerminateProcess"] + self.terminate.restype = w.BOOL + self.terminate.argtypes = (w.HANDLE, w.UINT) + + self.close_handle = kernel["CloseHandle"] + self.close_handle.restype = w.BOOL + self.close_handle.argtypes = (w.HANDLE,) + + def check(self, value: int) -> None: + if not value: + raise self.error(self.last_error()) + + def hr_ok(value: int, name: str) -> None: + if value < 0: + msg_0 = f"{name} failed with HRESULT 0x{value & 0xFFFFFFFF:08x}" + raise OSError(msg_0) + + def attach( + api: _Kernel, + console: w.HANDLE, + args: tuple[str, ...], + cwd: str | None, + env: dict[str, str] | None, + ) -> ProcessInfo: + size = c.c_size_t() + if api.init_attrs(None, 1, 0, c.byref(size)) or api.last_error() != 122: + msg_0 = "could not size the Win32 startup attributes" + raise RuntimeError(msg_0) + storage = c.create_string_buffer(size.value) + api.check(api.init_attrs(storage, 1, 0, c.byref(size))) + try: + # PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE points directly at the HPCON. + api.check( + api.update_attr( + storage, 0, 0x00020016, console, c.sizeof(w.HANDLE), None, None + ) + ) + startup = StartupInfoEx() + startup.StartupInfo.cb = c.sizeof(startup) + # Null standard handles here let the new console supply all three even + # when the controller's own standard streams have been redirected. + startup.StartupInfo.dwFlags = 0x100 # STARTF_USESTDHANDLES + startup.lpAttributeList = c.addressof(storage) + environment = None + flags = 0x00080000 # EXTENDED_STARTUPINFO_PRESENT + if env is not None: + flags |= 0x400 # CREATE_UNICODE_ENVIRONMENT + pairs = sorted(env.items(), key=lambda pair: pair[0].upper()) + environment = c.create_unicode_buffer( + "\0".join(f"{k}={v}" for k, v in pairs) + "\0" + ) + info = ProcessInfo() + command = c.create_unicode_buffer(subprocess.list2cmdline(args)) + api.check( + api.create_process( + None, + command, + None, + None, + False, + flags, + environment, + cwd, + c.byref(startup), + c.byref(info), + ) + ) + return info + finally: + api.delete_attrs(storage) + + class WinChild: + def __init__(self, api: _Kernel, info: ProcessInfo) -> None: + self._api = api + self.pid = info.pid + self._handle = info.hProcess + self._termination_requested = False + self._api.check(self._api.close_handle(info.hThread)) + self._exit = asyncio.get_running_loop().run_in_executor( + None, self._wait_handle + ) + + def _wait_handle(self) -> int: + if self._api.wait_handle(self._handle, 0xFFFFFFFF) != 0: + raise self._api.error(self._api.last_error()) + status = w.DWORD() + self._api.check(self._api.get_exit(self._handle, c.byref(status))) + return status.value + + @property + def returncode(self) -> int | None: + return self._exit.result() if self._exit.done() else None + + async def wait(self) -> int: + return await asyncio.shield(self._exit) + + def kill(self) -> None: + if ( + self._termination_requested + or self._api.wait_handle(self._handle, 0) == 0 + ): + return + if self._api.terminate(self._handle, 1): + # TerminateProcess returns before the handle necessarily signals. + self._termination_requested = True + else: + error = self._api.last_error() + if self._api.wait_handle(self._handle, 0) != 0: + raise self._api.error(error) + + async def close(self) -> None: + try: + self.kill() + finally: + try: + await self.wait() + finally: + self._api.check(self._api.close_handle(self._handle)) + + @contextlib.asynccontextmanager + async def open_conpty( + args: tuple[str, ...], options: VT, cwd: str | None, env: dict[str, str] | None + ) -> collections.abc.AsyncGenerator[_Attachment]: + import asyncio.windows_utils as winpipes + + api = _Kernel() + + def pipe( + stack: contextlib.AsyncExitStack, *, input_pipe: bool + ) -> tuple[winpipes.PipeHandle, winpipes.PipeHandle]: + # The two ConPTY ends use synchronous I/O. The host's overlapped ends + # let the Proactor drain output even while an input write is stalled. + read, write = winpipes.pipe( + duplex=input_pipe, overlapped=(not input_pipe, input_pipe) + ) + return ( + stack.enter_context(winpipes.PipeHandle(read)), + stack.enter_context(winpipes.PipeHandle(write)), + ) + + loop = asyncio.get_running_loop() + async with contextlib.AsyncExitStack() as stack: + con_in, host_out = pipe(stack, input_pipe=True) + host_in, con_out = pipe(stack, input_pipe=False) + reader = asyncio.StreamReader() + read_transport, _ = await loop.connect_read_pipe( + lambda: asyncio.StreamReaderProtocol(reader), host_in + ) + stack.callback(read_transport.close) + write_protocol = asyncio.StreamReaderProtocol(asyncio.StreamReader()) + write_transport, _ = await loop.connect_write_pipe( + lambda: write_protocol, host_out + ) + stack.callback(write_transport.close) + writer = asyncio.StreamWriter(write_transport, write_protocol, None, loop) + term = Terminal( + rows=options.rows, + cols=options.cols, + scrollback=options.scrollback, + recorder=FlightRecorder(max_bytes=options.raw_limit), + ) + stream = AsyncTerminalStream(reader, writer, terminal=term) + pump = stream.start() + stack.push_async_callback(stream.aclose) + + console = w.HANDLE() + hr_ok( + api.create_console( + Coord(options.cols, options.rows), + con_in.fileno(), + con_out.fileno(), + 0, + c.byref(console), + ), + "CreatePseudoConsole", + ) + + async def finish_output() -> None: + await asyncio.to_thread(api.close_console, console) + await asyncio.wait_for(asyncio.shield(pump), timeout=8) + + stack.push_async_callback(finish_output) + try: + process = WinChild(api, attach(api, console, args, cwd, env)) + stack.push_async_callback(process.close) + hr_ok(api.release_console(console), "ReleasePseudoConsole") + finally: + con_in.close() + con_out.close() + + def resize(*, rows: int, cols: int) -> None: + hr_ok( + api.resize_console(console, Coord(cols, rows)), + "ResizePseudoConsole", + ) + term.resize(rows=rows, cols=cols) + if replies := term.drain_replies(): + stream.send(replies) + + yield _Attachment(stream, process, resize) diff --git a/src/libvt/contrib/_darwin_pty.py b/src/libvt/contrib/_darwin_pty.py new file mode 100644 index 00000000..8bd649db --- /dev/null +++ b/src/libvt/contrib/_darwin_pty.py @@ -0,0 +1,299 @@ +"""Keep the controlling PTY session alive until the terminal closes.""" + +from __future__ import annotations + +import asyncio +import collections.abc +import contextlib +import errno +import os +import signal +import socket +import sys +import typing as t + +from libvt._util import _parse_ascii_int, _parse_ascii_uint +from libvt.aio._pty import ( + PtySession, + _child_pty_env, + _make_pty_terminal, + _prepare_pty_fds, + _resolve_python_executable, +) +from libvt.config import DEFAULT_POLICY, DEFAULT_PROFILE, Limits + +from .subprocess import VT, _Attachment + +# XNU revokes the slave's open descriptors when its session leader exits. +# This single trampoline becomes the session leader, acquires the controlling +# terminal, spawns the command, drops its own slave descriptors so native PTY +# EOF tracks terminal users, and relays child PID/exit over a socketpair. +_DARWIN_LEADER = ( + "stage = 'bootstrap'\n" + "control = None\n" + "child = None\n" + "try:\n" + " import errno, fcntl, os, signal, socket, subprocess, sys, termios, threading\n" + " control_fd = int(sys.argv[1])\n" + " os.set_inheritable(control_fd, False)\n" + " control = socket.socket(fileno=control_fd)\n" + " stage = 'ctty'\n" + " if hasattr(termios, 'TIOCSCTTY'):\n" + " fcntl.ioctl(0, termios.TIOCSCTTY, 0)\n" + " stage = 'signal'\n" + " signal.signal(signal.SIGPIPE, signal.SIG_DFL)\n" + " if hasattr(signal, 'SIGXFSZ'):\n" + " signal.signal(signal.SIGXFSZ, signal.SIG_DFL)\n" + " stage = 'exec'\n" + " child = subprocess.Popen(sys.argv[2:])\n" + " for sig in (signal.SIGINT, signal.SIGQUIT, signal.SIGTSTP):\n" + " signal.signal(sig, signal.SIG_IGN)\n" + " null_fd = os.open(os.devnull, os.O_RDWR)\n" + " try:\n" + " for fd in (0, 1, 2):\n" + " os.dup2(null_fd, fd)\n" + " finally:\n" + " if null_fd > 2:\n" + " os.close(null_fd)\n" + " def receive():\n" + " while True:\n" + " try:\n" + " command = control.recv(1)\n" + " except OSError:\n" + " command = b''\n" + " if command in (b'K', b''):\n" + " child.kill()\n" + " if not command:\n" + " return\n" + " control.sendall(f'pid {child.pid}\\n'.encode())\n" + " watcher = threading.Thread(target=receive, daemon=True)\n" + " watcher.start()\n" + " try:\n" + " control.sendall(f'exit {child.wait()}\\n'.encode())\n" + " except OSError:\n" + " pass\n" + " watcher.join()\n" + "except BaseException as exc:\n" + " if child is not None:\n" + " try:\n" + " child.kill()\n" + " child.wait()\n" + " except BaseException:\n" + " pass\n" + " try:\n" + " import errno as _e\n" + " if control is not None:\n" + " code = getattr(exc, 'errno', None)\n" + " if not isinstance(code, int):\n" + " code = _e.ENOEXEC\n" + " msg = (\n" + " (getattr(exc, 'strerror', None) or str(exc))\n" + " .replace('\\r', ' ')\n" + " .replace('\\n', ' ')[:360]\n" + " )\n" + " control.sendall(\n" + " f'error {stage} {code} {msg}\\n'.encode('utf-8', 'replace')\n" + " )\n" + " except BaseException:\n" + " pass\n" + " import os as _os\n" + " _os._exit(127)\n" + "finally:\n" + " if control is not None:\n" + " control.close()\n" +) + + +async def _read_message(reader: asyncio.StreamReader) -> tuple[bytes, bytes]: + line = await reader.readline() + tag, _, rest = line.rstrip(b"\r\n").partition(b" ") + if not tag: + msg = "PTY session leader exited before reporting child status" + raise RuntimeError(msg) + return tag, rest + + +def _raise_leader_error(payload: bytes, cmd: str) -> t.NoReturn: + parts = payload.decode("utf-8", "replace").split(" ", 2) + if len(parts) >= 2: + stage, code_s = parts[0], parts[1] + err_msg = parts[2] if len(parts) == 3 else "" + else: + stage, code_s, err_msg = "exec", "", payload.decode("utf-8", "replace") + parsed_err = _parse_ascii_uint(code_s, max_val=65_535) + err_no = errno.ENOEXEC if parsed_err is None else parsed_err + target = cmd if stage == "exec" else f"open_darwin_pty({stage})" + raise OSError(err_no, err_msg or os.strerror(err_no), target) + + +def _parse_child_pid(tag: bytes, rest: bytes) -> int: + if tag != b"pid": + msg = "PTY session leader did not report a child PID" + raise RuntimeError(msg) + child_pid = _parse_ascii_uint( + rest.decode("ascii", "replace"), max_val=2_147_483_647 + ) + if child_pid is None or child_pid <= 0: + msg = "PTY session leader reported an invalid child PID" + raise RuntimeError(msg) + return child_pid + + +class _Command: + def __init__( + self, pid: int, reader: asyncio.StreamReader, writer: asyncio.StreamWriter + ) -> None: + self.pid = pid + self._writer = writer + self._exit = asyncio.create_task(self._wait_child(reader)) + + @staticmethod + async def _wait_child(reader: asyncio.StreamReader) -> int: + kind, data = await _read_message(reader) + if kind != b"exit": + msg = "PTY session leader reported an unexpected child status" + raise RuntimeError(msg) + code = _parse_ascii_int( + data.decode("ascii", "replace"), min_val=-65_535, max_val=65_535 + ) + if code is None: + msg = "PTY session leader reported an invalid child exit status" + raise RuntimeError(msg) + return code + + @property + def returncode(self) -> int | None: + return self._exit.result() if self._exit.done() else None + + async def wait(self) -> int: + return await asyncio.shield(self._exit) + + def kill(self) -> None: + if not self._exit.done() and not self._writer.is_closing(): + self._writer.write(b"K") + + +@contextlib.asynccontextmanager +async def open_darwin_pty( + args: tuple[str, ...], options: VT, cwd: str | None, env: dict[str, str] | None +) -> collections.abc.AsyncGenerator[_Attachment]: + """Launch the command under a single-trampoline POSIX PTY session owner.""" + if sys.platform == "win32": + msg = "open_darwin_pty requires POSIX pty.openpty()" + raise NotImplementedError(msg) + + import pty + + py_bin = _resolve_python_executable(None, caller="open_darwin_pty") + limits = Limits(max_recorder_bytes=options.raw_limit) + terminal = _make_pty_terminal( + rows=options.rows, + cols=options.cols, + scrollback=options.scrollback, + profile=DEFAULT_PROFILE, + policy=DEFAULT_POLICY, + limits=limits, + ) + + loop = asyncio.get_running_loop() + master_fd, slave_fd = pty.openpty() + parent_sock: socket.socket | None = None + child_sock: socket.socket | None = None + writer: asyncio.StreamWriter | None = None + slave_closed = False + master_handed_off = False + proc: asyncio.subprocess.Process | None = None + try: + parent_sock, child_sock = socket.socketpair() + _prepare_pty_fds( + master_fd, + slave_fd, + rows=options.rows, + cols=options.cols, + profile=DEFAULT_PROFILE, + ) + child_env = _child_pty_env(env) + control_fd = child_sock.fileno() + proc = await asyncio.create_subprocess_exec( + py_bin, + "-I", + "-S", + "-c", + _DARWIN_LEADER, + str(control_fd), + *args, + stdin=slave_fd, + stdout=slave_fd, + stderr=slave_fd, + cwd=cwd, + env=child_env, + start_new_session=True, + pass_fds=(control_fd,), + close_fds=True, + ) + os.close(slave_fd) + slave_closed = True + child_sock.close() + child_sock = None + + reader, writer = await asyncio.open_connection(sock=parent_sock) + parent_sock = None + + tag, rest = await _read_message(reader) + if tag == b"error": + await proc.wait() + _raise_leader_error(rest, args[0]) + child_pid = _parse_child_pid(tag, rest) + + session = PtySession( + master_fd=master_fd, + process=proc, + terminal=terminal, + ) + session._loop = loop + master_handed_off = True + except BaseException: + if writer is not None: + writer.close() + with contextlib.suppress(OSError): + await writer.wait_closed() + writer = None + if proc is not None: + if proc.returncode is None: + with contextlib.suppress(ProcessLookupError, PermissionError): + os.killpg(proc.pid, signal.SIGKILL) + with contextlib.suppress(ProcessLookupError): + proc.kill() + await proc.wait() + raise + finally: + if not slave_closed: + with contextlib.suppress(OSError): + os.close(slave_fd) + if child_sock is not None: + child_sock.close() + if parent_sock is not None: + parent_sock.close() + if not master_handed_off: + with contextlib.suppress(OSError): + os.close(master_fd) + + try: + session._start_reading(loop) + child = _Command(child_pid, reader, writer) + try: + yield _Attachment(session, child, session.resize) + finally: + try: + child.kill() + await child.wait() + finally: + if not child._exit.done(): + child._exit.cancel() + with contextlib.suppress(BaseException): + await child._exit + writer.close() + with contextlib.suppress(OSError): + await writer.wait_closed() + finally: + await session.aclose() diff --git a/src/libvt/contrib/subprocess.py b/src/libvt/contrib/subprocess.py new file mode 100644 index 00000000..721b1a40 --- /dev/null +++ b/src/libvt/contrib/subprocess.py @@ -0,0 +1,620 @@ +"""Drive a child through a terminal from synchronous Python.""" + +from __future__ import annotations + +import asyncio +import collections.abc +import concurrent.futures +import contextlib +import math +import os +import subprocess +import sys +import threading +import time +import typing as t +from dataclasses import dataclass + +from libvt.aio import AsyncSession, open_pty +from libvt.config import Limits +from libvt.recorder import find_flight_recorder +from libvt.snapshot import Snapshot + +__all__ = [ + "VT", + "CalledTerminalError", + "Capture", + "CompletedTerminal", + "TerminalProcess", + "TerminalTimeoutExpired", + "open_terminal", + "run_terminal", +] + + +def _validate_size(rows: int, cols: int) -> None: + for name, value in (("rows", rows), ("cols", cols)): + if type(value) is not int or not 1 <= value <= 32767: + msg = f"{name} must be an integer from 1 to 32767" + raise ValueError(msg) + + +def _validate_timeout(timeout: float | None) -> None: + if timeout is not None and ( + isinstance(timeout, bool) or not math.isfinite(timeout) or timeout < 0 + ): + msg = "timeout must be finite and nonnegative" + raise ValueError(msg) + + +@dataclass(frozen=True, slots=True, kw_only=True) +class VT: + """Set initial geometry and retention limits for a terminal child. + + Attributes + ---------- + rows : int + Initial viewport height from 1 to 32767. + cols : int + Initial viewport width from 1 to 32767. + scrollback : int + Maximum retained scrollback rows. + raw_limit : int + Maximum retained output bytes (``0`` disables tail retention). + """ + + rows: int = 24 + cols: int = 80 + scrollback: int = 2000 + raw_limit: int = 4096 + + def __post_init__(self) -> None: + """Validate geometry and recorder limits.""" + _validate_size(self.rows, self.cols) + if type(self.scrollback) is not int or self.scrollback < 0: + msg = "scrollback must be a nonnegative integer" + raise ValueError(msg) + if type(self.raw_limit) is not int or self.raw_limit < 0: + msg = "raw_limit must be a nonnegative integer" + raise ValueError(msg) + + +@dataclass(frozen=True, slots=True) +class Capture: + """Hold the viewport and bounded tail of merged terminal output. + + Attributes + ---------- + snapshot : Snapshot + Last committed terminal frame. + raw_tail : bytes + Most recent recorded output bytes, including terminal sequences. + raw_total : int + Number of output bytes observed, including discarded bytes. + eof : bool + Whether the session observed terminal end-of-stream before teardown. + """ + + snapshot: Snapshot + raw_tail: bytes + raw_total: int + eof: bool + + def __vt_target__(self) -> tuple[Snapshot, frozenset[str]]: + """Return ``(snapshot, frozenset())`` for :mod:`libvt.testing`.""" + return self.snapshot, frozenset() + + @property + def truncated(self) -> bool: + """Return whether earlier output bytes were discarded.""" + return self.raw_total > len(self.raw_tail) + + +@dataclass(frozen=True, slots=True) +class CompletedTerminal(Capture): + """Hold the final capture and direct child's exit status. + + Attributes + ---------- + snapshot : Snapshot + Final committed terminal frame. + raw_tail : bytes + Most recent recorded output bytes, including terminal sequences. + raw_total : int + Number of output bytes observed, including discarded bytes. + eof : bool + Whether the session observed terminal end-of-stream before teardown. + args : tuple[str, ...] + Executable and arguments passed to the child. + returncode : int + Exit status of the direct child. + """ + + args: tuple[str, ...] + returncode: int + + def check_returncode(self) -> None: + """Raise :exc:`CalledTerminalError` for a nonzero child status.""" + if self.returncode: + raise CalledTerminalError(self) + + +class CalledTerminalError(subprocess.CalledProcessError): + """Expose the completed terminal capture on the ``result`` attribute.""" + + def __init__(self, result: CompletedTerminal) -> None: + super().__init__(result.returncode, result.args, output=result.raw_tail) + self.result = result + + +class TerminalTimeoutExpired(subprocess.TimeoutExpired): + """Expose a bounded ``capture`` and the timed-out ``phase``.""" + + def __init__( + self, + args: tuple[str, ...], + timeout: float, + capture: Capture, + phase: t.Literal["process", "eof"], + ) -> None: + super().__init__(args, timeout, output=capture.raw_tail) + self.capture = capture + self.phase = phase + + +class _Child(t.Protocol): + @property + def pid(self) -> int: ... + + @property + def returncode(self) -> int | None: ... + + async def wait(self) -> int: ... + + def kill(self) -> None: ... + + +class _Resize(t.Protocol): + def __call__(self, *, rows: int, cols: int) -> None: ... + + +@dataclass(frozen=True, slots=True) +class _Attachment: + io: AsyncSession + process: _Child + resize: _Resize + + +@contextlib.asynccontextmanager +async def _attach( + args: tuple[str, ...], options: VT, cwd: str | None, env: dict[str, str] | None +) -> collections.abc.AsyncGenerator[_Attachment]: + if sys.platform == "win32": + from ._conpty import open_conpty + + async with open_conpty(args, options, cwd, env) as attachment: + yield attachment + elif sys.platform == "darwin": + from ._darwin_pty import open_darwin_pty + + async with open_darwin_pty(args, options, cwd, env) as attachment: + yield attachment + else: + async with open_pty( + args, + rows=options.rows, + cols=options.cols, + scrollback=options.scrollback, + cwd=cwd, + env=env, + limits=Limits(max_recorder_bytes=options.raw_limit), + ) as pty: + yield _Attachment(pty, pty.process, pty.resize) + + +class TerminalProcess: + """Control a terminal child from the thread that opened it. + + Obtain a handle from :func:`open_terminal`. Use the context manager + or call :meth:`close` to shut down the terminal and reap the child. + """ + + def __init__( + self, + args: tuple[str, ...], + options: VT, + cwd: str | None, + env: dict[str, str] | None, + ) -> None: + self.args = args + self._raw_limit = options.raw_limit + self._controller = threading.current_thread() + self._ready = threading.Event() + self._worker = concurrent.futures.ThreadPoolExecutor( + 1, thread_name_prefix="libvt-terminal" + ) + self._done = self._worker.submit(self._run, _attach(args, options, cwd, env)) + self._done.add_done_callback(lambda _: self._ready.set()) + try: + self._ready.wait() + if self._done.done(): + self._done.result() + except BaseException: + self._ready.wait() + self._join() + raise + + def _run( + self, context: contextlib.AbstractAsyncContextManager[_Attachment] + ) -> CompletedTerminal: + loop_factory = ( + asyncio.ProactorEventLoop + if sys.platform == "win32" + else asyncio.SelectorEventLoop + ) + with asyncio.Runner(loop_factory=loop_factory) as runner: + return runner.run(self._own(context)) + + async def _own( + self, context: contextlib.AbstractAsyncContextManager[_Attachment] + ) -> CompletedTerminal: + async with context as attachment: + self._attachment = attachment + self.pid = attachment.process.pid + self._loop = asyncio.get_running_loop() + self._stop = asyncio.Event() + self._ready.set() + await self._stop.wait() + eof = attachment.io.eof + capture = self._capture() + status = attachment.process.returncode + if status is None: + msg = "terminal closed before its child was reaped" + raise RuntimeError(msg) + return CompletedTerminal( + capture.snapshot, + capture.raw_tail, + capture.raw_total, + eof, + self.args, + status, + ) + + def _controller_only(self) -> None: + if threading.current_thread() is not self._controller: + msg = "use the terminal handle from its creating thread" + raise RuntimeError(msg) + + def _block[T]( + self, + function: collections.abc.Callable[ + [], collections.abc.Coroutine[None, None, T] + ], + ) -> T: + self._controller_only() + if self._done.done(): + self._done.result() + msg = "terminal is closed" + raise ValueError(msg) + request = asyncio.run_coroutine_threadsafe(function(), self._loop) + try: + return request.result() + except BaseException: + request.cancel() + raise + + def _call[T](self, function: collections.abc.Callable[[], T]) -> T: + async def invoke() -> T: + return function() + + return self._block(invoke) + + def _capture(self) -> Capture: + term = self._attachment.io.terminal + recorder = find_flight_recorder(term.recorder) + if recorder is None: + msg = "terminal recorder is missing" + raise RuntimeError(msg) + return Capture( + term.committed, + recorder.tail(self._raw_limit), + recorder.total_bytes, + self._attachment.io.eof, + ) + + def __vt_target__(self) -> tuple[Snapshot, frozenset[str]]: + """Return ``(snapshot(), frozenset())`` for :mod:`libvt.testing`.""" + return self.snapshot(), frozenset() + + def snapshot(self) -> Snapshot: + """Return the last committed viewport.""" + if self._done.done(): + return self._done.result().snapshot + return self._call(lambda: self._attachment.io.terminal.committed) + + def capture(self) -> Capture: + """Return the viewport, raw tail, byte count, and EOF state.""" + if self._done.done(): + return self._done.result() + return self._call(self._capture) + + def wait_for( + self, + predicate: str | collections.abc.Callable[[Snapshot], bool], + *, + timeout: float = 2.0, + ) -> Snapshot: + """Wait for visible text or a predicate on a committed frame. + + The reader thread calls predicates. Use the supplied snapshot inside + a predicate. The underlying terminal wait raises + :exc:`~libvt.exc.TerminalTimeoutError` on timeout or EOF. + """ + return self._block( + lambda: self._attachment.io.wait_for(predicate, timeout=timeout) + ) + + def send(self, data: bytes, /) -> None: + """Queue raw input bytes for delivery to the terminal.""" + if not isinstance(data, bytes): + msg = "send requires bytes" + raise TypeError(msg) + self._call(lambda: self._attachment.io.send(data)) + + def send_key(self, chord: str, /) -> None: + """Queue a key chord encoded for the current terminal input modes.""" + self._call(lambda: self._attachment.io.send_key(chord)) + + def paste(self, text: str, /, *, sanitize: bool = False) -> None: + """Queue text using the active terminal paste mode.""" + self._call(lambda: self._attachment.io.paste(text, sanitize=sanitize)) + + def resize(self, *, rows: int, cols: int) -> None: + """Resize both the native terminal and the libvt viewport.""" + _validate_size(rows, cols) + self._call(lambda: self._attachment.resize(rows=rows, cols=cols)) + + def poll(self) -> int | None: + """Return the direct child's exit status, or ``None`` while it runs.""" + if self._done.done(): + return self._done.result().returncode + return self._call(lambda: self._attachment.process.returncode) + + @property + def returncode(self) -> int | None: + """Return the direct child's exit status, or ``None`` while it runs.""" + return self.poll() + + def wait(self, timeout: float | None = None) -> int: + """Wait for the direct child to exit while continuing to drain output. + + On timeout, raise :exc:`TerminalTimeoutExpired` and keep the handle + live for further interaction. + """ + _validate_timeout(timeout) + if self._done.done(): + return self._done.result().returncode + + return self._wait(self._attachment.process.wait, timeout, "process") + + def _wait[T]( + self, + operation: collections.abc.Callable[ + [], collections.abc.Coroutine[None, None, T] + ], + timeout: float | None, + phase: t.Literal["process", "eof"], + ) -> T: + async def wait_with_timeout() -> T: + scope = asyncio.timeout(timeout) + try: + async with scope: + return await operation() + except TimeoutError: + if timeout is None or not scope.expired(): + raise + raise TerminalTimeoutExpired( + self.args, timeout, self._capture(), phase + ) from None + + return self._block(wait_with_timeout) + + def wait_eof(self, timeout: float | None = None) -> Capture: + """Wait for terminal output to end, including output from descendants. + + On timeout, raise :exc:`TerminalTimeoutExpired` and keep the handle + live. A closed handle cannot wait for further output. + """ + _validate_timeout(timeout) + if self._done.done() and (capture := self._done.result()).eof: + return capture + + async def wait_output() -> Capture: + stream = self._attachment.io + # The session waiter wakes for EOF even if no frame changed. + # The outer wait owns the deadline, including an unbounded wait. + await stream.wait_for( + lambda _: stream.eof, timeout=sys.float_info.max, attach_note=False + ) + return self._capture() + + return self._wait(wait_output, timeout, "eof") + + def kill(self) -> None: + """Stop the direct child while keeping the terminal open.""" + + def deliver() -> None: + process = self._attachment.process + if process.returncode is None: + with contextlib.suppress(ProcessLookupError): + process.kill() + + self._call(deliver) + + def _join(self) -> None: + if not self._done.done(): + self._loop.call_soon_threadsafe(self._stop.set) + self._worker.shutdown() + + def close(self) -> CompletedTerminal: + """Shut down the terminal, reap the child, and return its final capture. + + Wait for :meth:`wait_eof` before closing when descendant output + matters. Repeated calls return the same result. A POSIX descendant + that ignores hangup can outlive the terminal after the direct + child has exited. + """ + self._controller_only() + self._join() + return self._done.result() + + def __enter__(self) -> t.Self: + """Return the open handle.""" + return self + + def __exit__(self, *_: object) -> None: + """Close the native terminal and reap the child.""" + self.close() + + +def open_terminal( + args: collections.abc.Sequence[str], + *, + vt: VT = VT(), + cwd: str | os.PathLike[str] | None = None, + env: collections.abc.Mapping[str, str] | None = None, +) -> TerminalProcess: + """Start a child with a POSIX PTY or Windows pseudoconsole. + + Parameters + ---------- + args : collections.abc.Sequence[str] + Executable and arguments as a nonempty sequence, such as a list. + vt : VT + Terminal geometry and retention limits. + cwd : str | os.PathLike[str] | None + Child working directory. Defaults to the parent's directory. + env : collections.abc.Mapping[str, str] | None + Replacement child environment. Defaults to the parent's environment. + POSIX supplies ``TERM=xterm-256color`` when missing. + + Returns + ------- + TerminalProcess + Open handle that owns merged output and must be closed. + + Raises + ------ + NotImplementedError + When native terminal allocation is unavailable. + OSError + When native terminal creation or child launch fails. + ValueError + When arguments contain invalid values. + """ + if not isinstance(vt, VT): + msg = "vt must be a VT configuration" + raise TypeError(msg) + if isinstance(args, str) or not isinstance(args, collections.abc.Sequence): + msg = "args must be a nonempty sequence of strings" + raise TypeError(msg) + argv = tuple(args) + if ( + not argv + or not argv[0] + or any(not isinstance(word, str) or "\0" in word for word in argv) + ): + msg = "args must contain an executable and NUL-free string arguments" + raise ValueError(msg) + path = os.fspath(cwd) if cwd is not None else None + if path is not None and (not isinstance(path, str) or "\0" in path): + msg = "cwd must be a text path without NUL" + raise ValueError(msg) + environment = None if env is None else dict(env) + if environment is not None: + for key, value in environment.items(): + if not isinstance(key, str) or not isinstance(value, str): + msg = "env keys and values must be strings" + raise TypeError(msg) + if not key or "=" in key or "\0" in key or "\0" in value: + msg = "invalid environment variable name or value" + raise ValueError(msg) + if sys.platform == "win32" and len({key.upper() for key in environment}) != len( + environment + ): + msg = "duplicate case-insensitive Windows environment variables" + raise ValueError(msg) + if os.name not in ("nt", "posix"): + msg = "terminal processes require POSIX or Windows" + raise NotImplementedError(msg) + return TerminalProcess(argv, vt, path, environment) + + +def run_terminal( + args: collections.abc.Sequence[str], + *, + vt: VT = VT(), + cwd: str | os.PathLike[str] | None = None, + env: collections.abc.Mapping[str, str] | None = None, + input: bytes | None = None, # noqa: A002 - match subprocess.run + timeout: float | None = None, + check: bool = False, +) -> CompletedTerminal: + """Run a command through a terminal and wait for exit and terminal EOF. + + Parameters + ---------- + args : collections.abc.Sequence[str] + Executable and arguments as a nonempty sequence, such as a list. + vt : VT + Terminal geometry and retention limits. + cwd : str | os.PathLike[str] | None + Child working directory. Defaults to the parent's directory. + env : collections.abc.Mapping[str, str] | None + Replacement child environment. Defaults to the parent's environment. + input : bytes | None + Bytes to queue after launch. Terminal input stays open. + timeout : float | None + Shared time budget after launch for child exit and terminal EOF. + Native cleanup may take longer. + check : bool + Raise for a nonzero exit status. + + Returns + ------- + CompletedTerminal + Final terminal capture and direct child's status. + + Raises + ------ + CalledTerminalError + If *check* is true and the direct child returns a nonzero status. + TerminalTimeoutExpired + If the timeout expires. The terminal closes and reaps the direct + child before raising. POSIX descendants that ignore hangup can + outlive the terminal. + """ + _validate_timeout(timeout) + if input is not None and not isinstance(input, bytes): + msg = "input must be bytes" + raise TypeError(msg) + child = open_terminal(args, vt=vt, cwd=cwd, env=env) + deadline = None if timeout is None else time.monotonic() + timeout + + def remaining() -> float | None: + return None if deadline is None else max(0.0, deadline - time.monotonic()) + + try: + try: + if input is not None: + child.send(input) + child.wait(remaining()) + child.wait_eof(remaining()) + finally: + result = child.close() + except TerminalTimeoutExpired as exc: + assert timeout is not None + raise TerminalTimeoutExpired(result.args, timeout, result, exc.phase) from None + if check: + result.check_returncode() + return result diff --git a/src/libvt/pytest_plugin.py b/src/libvt/pytest_plugin.py index 46448499..4e4f3191 100644 --- a/src/libvt/pytest_plugin.py +++ b/src/libvt/pytest_plugin.py @@ -9,14 +9,162 @@ if t.TYPE_CHECKING: import collections.abc + import contextlib import os + import pathlib + import weakref + from libvt._replay import _ReplayArtifact, _ReplayCapture from libvt.aio import PtySession, TtyMode from libvt.config import Limits, Policy, Profile from libvt.events import Event + from libvt.exc import ScreenAssertionError from libvt.parser import Parser, ParserEncoding from libvt.recorder import FlightRecorder, TerminalRecorder + from libvt.snapshot import Snapshot + from libvt.terminal import Terminal + + +_replay_terminals = pytest.StashKey[dict["Terminal", "_ReplayCapture"]]() +_replay_assertions = pytest.StashKey[ + "weakref.WeakKeyDictionary[ScreenAssertionError, _ReplayArtifact]" +]() + + +def pytest_addoption(parser: pytest.Parser) -> None: + """Register the opt-in terminal failure artifact directory.""" + parser.addoption( + "--vt-replay-dir", + metavar="DIR", + help="Write libvt terminal replay artifacts for failing tests to DIR", + ) + + +def _enable_replay( + request: pytest.FixtureRequest, + term: Terminal, + scrollback: int, + *, + supported: bool = True, +) -> Terminal: + if request.config.getoption("--vt-replay-dir", default=None): + from libvt._replay import _ReplayCapture + + capture = _ReplayCapture( + term.rows, + term.cols, + scrollback, + encoding=term.encoding, + supported=supported, + ) + if capture.incomplete is None: + term._attach_recorder(capture) + request.node.stash.setdefault(_replay_terminals, {})[term] = capture + return term + + +@pytest.hookimpl(wrapper=True) +def pytest_runtest_call( + item: pytest.Item, +) -> collections.abc.Generator[None, None, None]: + """Observe screen assertions during an opted-in test call.""" + if not item.config.getoption("--vt-replay-dir", default=None): + yield + return + + import weakref + from libvt.terminal import Terminal + from libvt.testing import _mismatch_observer + + terminals = item.stash.setdefault(_replay_terminals, {}) + assertions: weakref.WeakKeyDictionary[ScreenAssertionError, _ReplayArtifact] = ( + weakref.WeakKeyDictionary() + ) + item.stash[_replay_assertions] = assertions + + def observe( + error: ScreenAssertionError, + target: Terminal | Snapshot, + snap: Snapshot, + expected: list[str] | None, + difference: str | None, + ) -> None: + if ( + isinstance(target, Terminal) + and (capture := terminals.get(target)) is not None + ): + assertions[error] = capture.artifact(snap, expected, difference) + + token = _mismatch_observer.set(observe) + try: + yield + finally: + _mismatch_observer.reset(token) + + +def _write_replay(directory: pathlib.Path, artifact: _ReplayArtifact) -> pathlib.Path: + import json + import pathlib + import tempfile + + pending: pathlib.Path | None = None + try: + with tempfile.NamedTemporaryFile( + mode="w", + encoding="utf-8", + prefix="libvt-", + suffix=".part", + dir=directory, + delete=False, + ) as stream: + pending = pathlib.Path(stream.name) + json.dump(artifact, stream) + return pending.replace(pending.with_suffix(".json")) + finally: + if pending is not None: + pending.unlink(missing_ok=True) + + +@pytest.hookimpl(wrapper=True) +def pytest_runtest_makereport( + item: pytest.Item, call: pytest.CallInfo[None] +) -> collections.abc.Generator[None, pytest.TestReport, pytest.TestReport]: + """Write terminal traces after a failed test call.""" + report = yield + directory: str | None = item.config.getoption("--vt-replay-dir", default=None) + terminals = item.stash.get(_replay_terminals, None) + if not (directory and terminals and report.failed and call.when == "call"): + return report + + import pathlib + + from libvt._replay import _verify_capture + from libvt.exc import ScreenAssertionError + + assertions = item.stash.get(_replay_assertions, None) + error = call.excinfo.value if call.excinfo is not None else None + artifact = ( + assertions.get(error) + if assertions is not None and isinstance(error, ScreenAssertionError) + else None + ) + artifacts = ( + [artifact] + if artifact is not None + else [capture.artifact(term.snapshot()) for term, capture in terminals.items()] + ) + paths: list[str] = [] + try: + out = pathlib.Path(directory).resolve() + out.mkdir(parents=True, exist_ok=True) + for item_artifact in artifacts: + _verify_capture(item_artifact) + paths.append(str(_write_replay(out, item_artifact))) + except OSError as exc: + paths.append(f"Could not write replay: {exc}") + report.sections.append(("libvt replay", "\n".join(paths))) + return report class TerminalFactory(t.Protocol): @@ -65,10 +213,6 @@ def __call__( """Open a POSIX PTY subprocess session.""" -if t.TYPE_CHECKING: - import contextlib - - @pytest.fixture def vt_recorder() -> FlightRecorder: r"""Return a fresh 4 KiB :class:`~libvt.recorder.FlightRecorder`. @@ -93,7 +237,9 @@ def vt_recorder() -> FlightRecorder: @pytest.fixture -def vt_terminal(vt_recorder: FlightRecorder) -> Terminal: +def vt_terminal( + vt_recorder: FlightRecorder, request: pytest.FixtureRequest +) -> Terminal: r"""Return a fresh ``24x80`` :class:`~libvt.terminal.Terminal` with recorder. Returns @@ -111,11 +257,13 @@ def vt_terminal(vt_recorder: FlightRecorder) -> Terminal: """ from libvt.terminal import Terminal - return Terminal(rows=24, cols=80, recorder=vt_recorder) + return _enable_replay( + request, Terminal(rows=24, cols=80, recorder=vt_recorder), 2_000 + ) @pytest.fixture -def vt_factory() -> TerminalFactory: +def vt_factory(request: pytest.FixtureRequest) -> TerminalFactory: r"""Return a typed factory creating :class:`~libvt.terminal.Terminal` instances. Returns @@ -148,7 +296,7 @@ def _make( record_events: bool = False, recorder: TerminalRecorder | None = None, ) -> Terminal: - return Terminal( + term = Terminal( rows=rows, cols=cols, scrollback=scrollback, @@ -160,6 +308,17 @@ def _make( record_events=record_events, recorder=recorder, ) + return _enable_replay( + request, + term, + scrollback, + supported=( + profile == DEFAULT_PROFILE + and policy == DEFAULT_POLICY + and limits == DEFAULT_LIMITS + and on_event is None + ), + ) return _make @@ -185,7 +344,7 @@ def vt_parser() -> Parser: @pytest.fixture -def vt_pty() -> PtyFactory: +def vt_pty(request: pytest.FixtureRequest) -> PtyFactory: """Return a POSIX :func:`~libvt.aio.open_pty` factory (skips on Windows). Returns @@ -197,10 +356,13 @@ def vt_pty() -> PtyFactory: if sys.platform == "win32": pytest.skip("vt_pty requires POSIX pty.openpty()") + import contextlib + from libvt.aio import open_pty from libvt.config import DEFAULT_LIMITS, DEFAULT_POLICY, DEFAULT_PROFILE - def _spawn( + @contextlib.asynccontextmanager + async def _spawn( argv: collections.abc.Sequence[str], *, rows: int = 24, @@ -218,8 +380,8 @@ def _spawn( sync_timeout: float = 1.0, write_high_water: int | None = None, max_write_buffer: int = 16_777_216, - ) -> contextlib.AbstractAsyncContextManager[PtySession]: - return open_pty( + ) -> collections.abc.AsyncGenerator[PtySession]: + async with open_pty( argv, rows=rows, cols=cols, @@ -236,7 +398,19 @@ def _spawn( sync_timeout=sync_timeout, write_high_water=write_high_water, max_write_buffer=max_write_buffer, - ) + ) as session: + # The reader is registered; its first callback runs at the next yield. + _enable_replay( + request, + session.terminal, + scrollback, + supported=( + profile == DEFAULT_PROFILE + and policy == DEFAULT_POLICY + and limits == DEFAULT_LIMITS + ), + ) + yield session return _spawn diff --git a/src/libvt/snapshot.py b/src/libvt/snapshot.py index e50cb1df..f9770906 100644 --- a/src/libvt/snapshot.py +++ b/src/libvt/snapshot.py @@ -461,6 +461,24 @@ def _make_snapshot( return snap +class CellSpan(t.NamedTuple): + """Half-open cell range on one snapshot row. + + Attributes + ---------- + row : int + Zero-based viewport row. + start : int + Inclusive zero-based column. + stop : int + Exclusive zero-based column. + """ + + row: int + start: int + stop: int + + class Snapshot: r"""Immutable point-in-time capture of terminal screen, history, and metadata. @@ -807,6 +825,65 @@ def viewport(self, offset: int = 0) -> RegionView: out_rows.extend(self._rows[: win_stop - h_len]) return RegionView(out_rows, range(cols), parent_cols=cols, live=False) + def find_cells(self, text: str, /) -> tuple[CellSpan, ...]: + r"""Find exact text matches by cell in the active viewport. + + Return zero-based, half-open spans in row and column order, including + overlaps. An empty tuple means no match. Search each row separately, + including soft-wrapped rows. Matches span complete stored graphemes + without normalization. Wide glyphs occupy two columns. Search skips + clipped wide glyphs, wrap spacers, and unwritten trailing padding. + Explicit trailing spaces and blanks before later text can match. + + Parameters + ---------- + text : str + Literal text to match within a single row. + + Returns + ------- + tuple[CellSpan, ...] + Matching row and column spans in the active viewport. + + Raises + ------ + ValueError + If *text* is empty or contains a carriage return or newline. + """ + if not text or "\r" in text or "\n" in text: + msg = "text must be nonempty and contain no carriage returns or newlines" + raise ValueError(msg) + + matches: list[CellSpan] = [] + for row_idx, row in enumerate(self._rows): + line = row.rstrip_text() + at = line.find(text) + if at < 0: + continue + + columns = {0: 0} + col = offset = 0 + limit = row.text_used + while col < limit: + grapheme = row.char_at(col) + if not grapheme: + # Wide continuations are skipped. A wrap spacer ends the row. + break + role = raw_width_bits(row.attr_at(col)) + col += 2 if role == WidthRole.WIDE else 1 + if col > limit: + break + offset += len(grapheme) + columns[offset] = col + + while at >= 0: + end = at + len(text) + if at in columns and end in columns: + matches.append(CellSpan(row_idx, columns[at], columns[end])) + at = line.find(text, at + 1) + + return tuple(matches) + @property def lines(self) -> tuple[str, ...]: r"""Return visible row text with unwritten trailing blank cells omitted. @@ -1041,6 +1118,7 @@ def to_dict(self) -> SnapshotDict: __all__ = [ + "CellSpan", "ResyncReason", "ScreenDelta", "Snapshot", diff --git a/src/libvt/terminal.py b/src/libvt/terminal.py index 44d08dc7..d76d2690 100644 --- a/src/libvt/terminal.py +++ b/src/libvt/terminal.py @@ -105,6 +105,7 @@ from libvt.recorder import CompositeRecorder, FlightRecorder, TerminalRecorder from libvt.screen import Screen, ScreenSet, ScrollRegion from libvt.snapshot import ( + CellSpan, ResyncReason, ScreenDelta, Snapshot, @@ -4289,6 +4290,7 @@ def strip(data: collections.abc.Buffer | str, /) -> str: __all__ = [ + "CellSpan", "FlightRecorder", "Formatter", "OutputFormat", diff --git a/src/libvt/testing.py b/src/libvt/testing.py index 6973a63e..b859bd33 100644 --- a/src/libvt/testing.py +++ b/src/libvt/testing.py @@ -2,7 +2,9 @@ from __future__ import annotations +import bisect import collections.abc +import contextvars import difflib import inspect import itertools @@ -17,8 +19,10 @@ from libvt._ucd import ( WidthRole, display_width, + init_cluster_state, sanitize_terminal_text, segment_graphemes, + step_cluster, ) from libvt.codec import format_explain from libvt.config import DEFAULT_PROFILE, Profile, UnicodeBehavior @@ -57,6 +61,29 @@ def _box_row_cells(row: RowView) -> list[str]: return cells +def _segment_expected(text: str, *, mode_2027: bool = True) -> list[str]: + """Segment *text* into UAX #29 clusters or legacy-mode glyphs.""" + if not text: + return [] + if mode_2027: + return segment_graphemes(text) + clusters: list[str] = [] + buf: list[str] = [text[0]] + state = init_cluster_state(ord(text[0]), mode_2027=False) + for ch in text[1:]: + cp = ord(ch) + extends, next_state, _ = step_cluster(state, cp, mode_2027=False) + if extends: + buf.append(ch) + state = next_state + else: + clusters.append("".join(buf)) + buf = [ch] + state = init_cluster_state(cp, mode_2027=False) + clusters.append("".join(buf)) + return clusters + + def _pad_expected_line( line: str, width: int, @@ -102,7 +129,7 @@ def _pad_expected_line( sanitized = sanitize_terminal_text(line) out: list[str] = [] cols_used = 0 - for cluster in segment_graphemes(sanitized): + for cluster in _segment_expected(sanitized, mode_2027=mode_2027): cw = display_width(cluster, mode_2027=mode_2027, profile=profile) if cols_used + cw > width: break @@ -187,25 +214,111 @@ def format_flight_recorder(target: Terminal) -> str: return "\n".join(lines) +type _MismatchObserver = collections.abc.Callable[ + [ScreenAssertionError, Terminal | Snapshot, Snapshot, list[str] | None, str | None], + None, +] +_mismatch_observer: contextvars.ContextVar[_MismatchObserver | None] = ( + contextvars.ContextVar("_mismatch_observer", default=None) +) + + def _raise_mismatch( target: Terminal | Snapshot, snap: Snapshot, expected_box: str, actual_box: str, cursor: tuple[int, int] | None, + *, + expected: list[str] | None = None, + difference: str | None = None, ) -> None: details = [ "Screen state mismatch:", f"cursor actual=({snap.cursor.row}, {snap.cursor.col})" + (f" expected={cursor}" if cursor is not None else ""), - "Expected:", - expected_box, - "Actual:", - actual_box, ] + if difference is not None: + details.append(difference) + details.extend(("Expected:", expected_box, "Actual:", actual_box)) if isinstance(target, Terminal): details.append(format_flight_recorder(target)) - raise ScreenAssertionError("\n".join(details)) + error = ScreenAssertionError("\n".join(details)) + observer = _mismatch_observer.get() + if observer is not None: + observer(error, target, snap, expected, difference) + raise error + + +def _first_screen_difference( + snap: Snapshot, + expected: list[str], + actual: list[str], + cursor: tuple[int, int] | None, +) -> str | None: + for row, (exp, act) in enumerate(itertools.zip_longest(expected, actual)): + if exp == act: + continue + if exp is None or act is None: + boundary = " beyond the viewport" if row >= snap.rows else "" + return ( + f"First difference at row {row}{boundary}: " + f"expected {exp!r}, actual {act!r}" + ) + + offset = next( + index + for index, (left, right) in enumerate(itertools.zip_longest(exp, act)) + if left != right + ) + expected_glyphs = _segment_expected( + exp, mode_2027=Mode.GRAPHEME_CLUSTERING in snap.modes + ) + row_view = snap[row] + actual_cells = [ + (column, glyph) + for column in range(row_view.text_used) + if (glyph := row_view[column].text) + ] + expected_starts = list( + itertools.accumulate(map(len, expected_glyphs), initial=0) + ) + actual_starts = list( + itertools.accumulate((len(glyph) for _, glyph in actual_cells), initial=0) + ) + # A difference inside either glyph starts at its first character. + # Look up both labels at that shared position in the literal prefix. + start = min( + expected_starts[bisect.bisect_right(expected_starts, offset) - 1], + actual_starts[bisect.bisect_right(actual_starts, offset) - 1], + ) + expected_index = bisect.bisect_right(expected_starts, start) - 1 + actual_index = bisect.bisect_right(actual_starts, start) - 1 + expected_cell = ( + repr(expected_glyphs[expected_index]) + if expected_index < len(expected_glyphs) + else "padding" + ) + if actual_index < len(actual_cells): + column, glyph = actual_cells[actual_index] + actual_cell = repr(glyph) + else: + column = row_view.text_used + if column and row_view[column - 1].width_role == WidthRole.SPACER_HEAD: + column -= 1 + actual_cell = "outside the viewport" if column >= snap.cols else "padding" + + return ( + f"First difference at row {row}, column {column}: " + f"expected {expected_cell}, actual {actual_cell}" + ) + + if cursor is not None: + return ( + f"Cursor differs: expected {cursor}, " + f"actual ({snap.cursor.row}, {snap.cursor.col})" + ) + return None def assert_screen( @@ -226,7 +339,7 @@ def assert_screen( Live terminal or immutable snapshot under test. expected : str | Sequence[str] Expected visible text (dedented when passed as a multi-line string) - or explicit sequence of right-trimmed row strings. + or a sequence of row strings. Include spaces written by the program. cursor : tuple[int, int] | None, optional Expected zero-based ``(row, col)`` cursor coordinates, if checked. @@ -283,7 +396,15 @@ def assert_screen( ) exp_box_lines.append(f"│{padded}│") exp_box_lines.append(f"└{exp_border}┘") - _raise_mismatch(target, snap, "\n".join(exp_box_lines), actual_box, cursor) + _raise_mismatch( + target, + snap, + "\n".join(exp_box_lines), + actual_box, + cursor, + expected=exp_lines, + difference=_first_screen_difference(snap, exp_lines, act_lines, cursor), + ) def assert_screen_box( diff --git a/tests/test_aio.py b/tests/test_aio.py index 25a07a4b..dcfd90de 100644 --- a/tests/test_aio.py +++ b/tests/test_aio.py @@ -1836,3 +1836,44 @@ async def test_aio_sessions_support_vt_target_and_strided_buffers() -> None: assert isinstance(pty_sess, SupportsVtTarget) await pty_sess.wait_for("PTY_OK", timeout=3.0) assert "│PTY_OK │" in serialize_vt_snapshot(pty_sess) + + +@pytest.mark.skipif(sys.platform == "win32", reason="POSIX pty required") +async def test_snapshot_find_cells_clicks_child_target() -> None: + """The child observes a different selection from a string-index click.""" + child = r""" +import sys + +out = sys.stdout.buffer +out.write("\x1b[?1000;1006h\x1b[2;1H界界e\u0301界·Go".encode()) +for _ in range(2): + packet = bytearray() + while (byte := sys.stdin.buffer.read(1)) != b"M": + if not byte: + raise EOFError("incomplete mouse event") + packet.extend(byte) + button, column, row = map(int, packet.removeprefix(b"\x1b[<").split(b";")) + assert button == 0 + choice = "Ferry" if (row, column) == (2, 9) else "Harbor" + out.write(f"\x1b[3;1HACK {choice} row={row} col={column}\r\nDONE".encode()) +""" + async with open_pty( + (sys.executable, "-u", "-c", child), tty_mode="raw", rows=5, cols=32 + ) as session: + snap = await session.wait_for("Go", timeout=5) + (hit,) = snap.find_cells("Go") + + session.send_event( + MouseEvent(MouseButton.LEFT, MouseAction.PRESS, hit.row, hit.start) + ) + selected = await session.wait_for( + lambda view: view.lines[2].startswith("ACK ") and view.lines[3] == "DONE", + timeout=5, + ) + assert selected.lines[2] == "ACK Ferry row=2 col=9" + + text_index = snap.lines[hit.row].index("Go") + session.send_event( + MouseEvent(MouseButton.LEFT, MouseAction.PRESS, hit.row, text_index) + ) + await session.wait_for("ACK Harbor row=2 col=7", timeout=5) diff --git a/tests/test_codec.py b/tests/test_codec.py index c238e47d..362cbaec 100644 --- a/tests/test_codec.py +++ b/tests/test_codec.py @@ -85,7 +85,7 @@ def test_codec_conformance_tables_cover_all_modes_and_documented_osc() -> None: assert {"CUP", "SGR", "DECSTBM", "XTWINOPS", "REP"} <= set(_CSI_NAMES.values()) -@pytest.mark.parametrize("command", ["render", "strip", "explain"]) +@pytest.mark.parametrize("command", ["render", "strip", "explain", "replay"]) def test_cli_reports_missing_input( command: str, tmp_path: pathlib.Path, capsys: pytest.CaptureFixture[str] ) -> None: @@ -100,15 +100,26 @@ def test_cli_reports_missing_input( @pytest.mark.parametrize( - ("flag", "value"), [("--rows", "0"), ("--cols", "-1"), ("--cols", "bad-width")] + ("command", "flag", "value"), + [ + ("render", "--rows", "0"), + ("render", "--cols", "-1"), + ("render", "--cols", "bad-width"), + ("replay", "--chunk-size", "0"), + ("replay", "--chunk-size", "-1"), + ], ) def test_cli_rejects_geometry_before_opening_input( - flag: str, value: str, tmp_path: pathlib.Path, capsys: pytest.CaptureFixture[str] + command: str, + flag: str, + value: str, + tmp_path: pathlib.Path, + capsys: pytest.CaptureFixture[str], ) -> None: """Point to the invalid dimension even when the input path is missing.""" missing = tmp_path / "missing.vt" with pytest.raises(SystemExit) as exit_info: - main(["render", flag, value, str(missing)]) + main([command, flag, value, str(missing)]) assert exit_info.value.code == 2 out, err = capsys.readouterr() assert not out diff --git a/tests/test_fzf_cookbook.py b/tests/test_fzf_cookbook.py new file mode 100644 index 00000000..daf41cd0 --- /dev/null +++ b/tests/test_fzf_cookbook.py @@ -0,0 +1,69 @@ +"""Drive fzf through its terminal and inspect its separate selection output.""" + +from __future__ import annotations + +import asyncio +import os +import pathlib +import shutil +import sys + +import pytest + +from libvt.aio import open_pty + + +@pytest.fixture(scope="module", autouse=True) +def available_pty() -> None: + """Skip the picker if the host cannot allocate a terminal.""" + if sys.platform == "win32": + pytest.skip("requires a POSIX terminal") + + import pty + + try: + master, slave = pty.openpty() + except OSError as error: + pytest.skip(f"cannot allocate a POSIX terminal: {error}") + os.close(master) + os.close(slave) + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("key", "status", "output"), + [("enter", 0, b"Cedar / invoice\n"), ("escape", 130, b"")], +) +async def test_select_or_cancel( + tmp_path: pathlib.Path, key: str, status: int, output: bytes +) -> None: + """Follow the pointer to an invoice, then check what fzf returned.""" + fzf = shutil.which("fzf") + if fzf is None: + pytest.skip("install fzf to run the picker example") + (tmp_path / "jobs").write_text( + "Birch / crate\nCedar / manifest\nCedar / invoice\n", encoding="ascii" + ) + command = 'exec "$1" --sync --no-sort --layout=reverse --pointer=+ choice' + argv = ["/bin/sh", "-c", command, "sh", str(pathlib.Path(fzf).resolve())] + env = {"HOME": str(tmp_path), "TMPDIR": str(tmp_path), "TERM": "xterm-256color"} + async with open_pty(argv, rows=8, cols=40, cwd=tmp_path, env=env) as picker: + await picker.wait_for("Birch / crate", timeout=5) + picker.paste("cedar") + await picker.wait_for( + lambda s: "Cedar / invoice" in s.text and "Birch / crate" not in s.text, + timeout=5, + ) + picker.send_key("down") + await picker.wait_for( + lambda s: any( + row.startswith("+") and "Cedar / invoice" in row for row in s.lines + ), + timeout=5, + ) + picker.send_key(key) + assert await asyncio.wait_for(picker.process.wait(), timeout=5) == status + assert (tmp_path / "choice").read_bytes() == output + + +pytestmark = pytest.mark.integration diff --git a/tests/test_libvt.py b/tests/test_libvt.py index e59a2ce1..116a0b17 100644 --- a/tests/test_libvt.py +++ b/tests/test_libvt.py @@ -398,6 +398,7 @@ def test_core_split_has_no_screen_to_terminal_cycle_and_keeps_reexports() -> Non ): assert getattr(screen_mod, name) is getattr(views_mod, name) for name in ( + "CellSpan", "ResyncReason", "ScreenDelta", "Snapshot", diff --git a/tests/test_subprocess.py b/tests/test_subprocess.py new file mode 100644 index 00000000..b1218906 --- /dev/null +++ b/tests/test_subprocess.py @@ -0,0 +1,404 @@ +"""Exercise real child processes through the synchronous terminal controller.""" + +from __future__ import annotations + +import asyncio +import ctypes +import os +import pathlib +import signal +import sys +import tempfile +import threading +import typing as t + +import pytest + +from libvt.contrib import subprocess as sp +from libvt.contrib._darwin_pty import open_darwin_pty +from libvt.recorder import CompositeRecorder +from libvt.testing import SupportsVtTarget, serialize_vt_snapshot, vt_screen + + +def _command(script: str) -> list[str]: + return [sys.executable, "-u", "-c", script] + + +def test_public_exports_omit_stdlib_aliases() -> None: + """Expose only terminal subprocess symbols without stdlib re-exports.""" + assert not hasattr(sp, "Popen") + assert not hasattr(sp, "run") + assert "Popen" not in sp.__all__ + assert "run" not in sp.__all__ + assert set(sp.__all__) == { + "VT", + "CalledTerminalError", + "Capture", + "CompletedTerminal", + "TerminalProcess", + "TerminalTimeoutExpired", + "open_terminal", + "run_terminal", + } + if t.TYPE_CHECKING: + command = [sys.executable] + proc = sp.open_terminal(command) + t.assert_type(proc, sp.TerminalProcess) + result = sp.run_terminal(command) + t.assert_type(result, sp.CompletedTerminal) + t.assert_type(serialize_vt_snapshot(proc), str) + t.assert_type(serialize_vt_snapshot(result), str) + + +def test_vt_raw_limit_validation() -> None: + """Allow any nonnegative integer raw_limit and reject negatives or bools.""" + assert sp.VT(raw_limit=0).raw_limit == 0 + assert sp.VT(raw_limit=1).raw_limit == 1 + assert sp.VT(raw_limit=63).raw_limit == 63 + for bad in (-1, -64, True): + with pytest.raises(ValueError, match="raw_limit"): + sp.VT(raw_limit=bad) + + +@pytest.fixture +def _terminal_platform() -> None: + if sys.platform == "win32" and not hasattr( + ctypes.WinDLL("kernel32"), "ReleasePseudoConsole" + ): + pytest.skip("ConPTY terminal EOF requires ReleasePseudoConsole") + if os.name not in ("nt", "posix"): + pytest.skip("native terminal unavailable") + + +@pytest.mark.usefixtures("_terminal_platform") +def test_terminal_interaction() -> None: + """Change the child geometry, drive input, and support VT snapshot targets.""" + script = ( + "import os, sys; print('TTY', *(os.isatty(fd) for fd in range(3)));" + "print('DATA', input()[::-1]);" + "print('SIZE', *os.get_terminal_size());" + "print('STDERR', file=sys.stderr); sys.exit(23)" + ) + with sp.open_terminal(_command(script), vt=sp.VT(rows=8, cols=38)) as child: + before = child.wait_for("TTY True True True", timeout=8) + assert isinstance(child, SupportsVtTarget) + assert "TTY True True True" in serialize_vt_snapshot(child) + child.resize(rows=10, cols=56) + child.paste("pear") + child.send_key("enter") + assert child.wait(8) == 23 + capture = child.wait_eof(8) + assert before.cols == 38 + assert capture.eof + assert isinstance(capture, SupportsVtTarget) + rendered_capture = serialize_vt_snapshot(vt_screen(capture)) + for expected in ("DATA raep", "SIZE 56 10", "STDERR"): + assert expected in capture.snapshot.text + assert expected in rendered_capture + result = child.close() + assert child.returncode == 23 + assert result is child.close() + assert isinstance(result, SupportsVtTarget) + assert "DATA raep" in serialize_vt_snapshot(result) + assert "DATA raep" in serialize_vt_snapshot(child) + with pytest.raises(sp.CalledTerminalError) as failure: + result.check_returncode() + assert failure.value.result is result + + +@pytest.fixture +def descendant_command(tmp_path: pathlib.Path) -> list[str]: + """Return a program whose descendant retains the terminal.""" + ready = str(tmp_path / "ready") + descendant = ( + "import os, pathlib, signal, sys, threading;\n" + "if sys.platform != 'win32': signal.signal(signal.SIGHUP, signal.SIG_IGN)\n" + "watchdog = threading.Timer(15, os._exit, (3,))\n" + "watchdog.daemon = True; watchdog.start()\n" + f"pathlib.Path({ready!r}).touch();" + "print('DESCENDANT READY'); print('LATE', input()[::-1])" + ) + main = ( + "import pathlib, subprocess, sys, time;\n" + f"worker = subprocess.Popen([sys.executable, '-u', '-c', {descendant!r}])\n" + "until = time.monotonic() + 5\n" + f"while not pathlib.Path({ready!r}).exists():\n" + " if worker.poll() is not None or time.monotonic() > until: sys.exit(2)\n" + " time.sleep(0.01)\n" + "sys.exit(17)" + ) + return _command(main) + + +@pytest.mark.usefixtures("_terminal_platform") +def test_terminal_eof_after_descendant_output(descendant_command: list[str]) -> None: + """Keep serving the terminal after the process that launched it exits.""" + with sp.open_terminal(descendant_command) as child: + assert child.wait(8) == 17 + child.wait_for("DESCENDANT READY", timeout=8) + with pytest.raises(sp.TerminalTimeoutExpired) as failure: + child.wait_eof(0) + assert failure.value.phase == "eof" + assert failure.value.capture.eof is False + child.paste("pine") + child.send_key("enter") + capture = child.wait_eof(8) + assert "LATE enip" in capture.snapshot.text + + +@pytest.mark.usefixtures("_terminal_platform") +def test_run_timeout_while_descendant_holds_terminal( + descendant_command: list[str], +) -> None: + """Apply the one-shot deadline to terminal EOF after the direct child exits.""" + with pytest.raises(sp.TerminalTimeoutExpired) as failure: + sp.run_terminal(descendant_command, timeout=3) + assert failure.value.phase == "eof" + assert failure.value.timeout == 3 + result = failure.value.capture + assert isinstance(result, sp.CompletedTerminal) + assert result.returncode == 17 + assert not result.eof + + +@pytest.mark.usefixtures("_terminal_platform") +def test_run_retains_bounded_tail() -> None: + """Drain large output with bounded tail retention including raw_limit=0.""" + result = sp.run_terminal( + _command("print('x' * 100_000); print('COMPLETE')"), + vt=sp.VT(rows=4, cols=40, scrollback=2, raw_limit=128), + check=True, + timeout=20, + ) + assert result.eof + assert len(result.raw_tail) == 128 < result.raw_total + assert result.truncated + assert "COMPLETE" in result.snapshot.text + + zero = sp.run_terminal( + _command("print('ZERO_TAIL')"), + vt=sp.VT(rows=4, cols=40, raw_limit=0), + check=True, + timeout=10, + ) + assert zero.eof + assert zero.raw_tail == b"" + assert zero.raw_total > 0 + assert zero.truncated + assert "ZERO_TAIL" in zero.snapshot.text + + +@pytest.mark.usefixtures("_terminal_platform") +def test_capture_unwraps_composite_recorder() -> None: + """Resolve the FlightRecorder through find_flight_recorder on wrapped terminals.""" + + class _NoopRecorder: + def on_feed(self, data: memoryview, /) -> None: + pass + + def on_resize(self, rows: int, cols: int, reflow: bool, /) -> None: + pass + + with sp.open_terminal(_command("print('WRAPPED'); input()")) as child: + child.wait_for("WRAPPED", timeout=8) + + def _wrap() -> None: + term = child._attachment.io.terminal + assert term.recorder is not None + term._recorder = CompositeRecorder(_NoopRecorder(), term.recorder) + + child._call(_wrap) + cap = child.capture() + assert b"WRAPPED" in cap.raw_tail + assert cap.raw_total >= len(b"WRAPPED") + child.send(b"\r") + assert child.wait(8) == 0 + + +@pytest.mark.usefixtures("_terminal_platform") +def test_timeout_leaves_wait_handle_live_and_run_reaps() -> None: + """Retry a live wait and report the phase of a one-shot timeout.""" + command = _command("print('WAITING'); input()") + with sp.open_terminal(command) as child: + child.wait_for("WAITING", timeout=8) + with pytest.raises(sp.TerminalTimeoutExpired) as failure: + child.wait(0) + assert failure.value.phase == "process" + assert child.poll() is None + child.send(b"\r") + assert child.wait(8) == 0 + with pytest.raises(sp.TerminalTimeoutExpired) as failure: + sp.run_terminal(command, timeout=0.5) + assert failure.value.phase == "process" + assert failure.value.timeout == 0.5 + assert failure.value.cmd == tuple(command) + + +@pytest.mark.usefixtures("_terminal_platform") +def test_run_with_input_and_launch_options(tmp_path: pathlib.Path) -> None: + """Pass quoted arguments, a working directory, and a replacement environment.""" + command = _command( + "import os, sys; print('INPUT', input()); print('ARG', sys.argv[1]);" + "print('CWD', os.path.basename(os.getcwd()));" + "print('ENV', os.environ['TEST_VALUE'])" + ) + command.append('space "quote"') + result = sp.run_terminal( + command, + cwd=tmp_path, + env={**os.environ, "TEST_VALUE": "example"}, + input=b"pear\r", + timeout=10, + check=True, + ) + for expected in ( + "INPUT pear", + 'ARG space "quote"', + f"CWD {tmp_path.name}", + "ENV example", + ): + assert expected in result.snapshot.text + + +@pytest.mark.usefixtures("_terminal_platform") +def test_invalid_executable_releases_worker(tmp_path: pathlib.Path) -> None: + """Propagate native exec failure without leaving a terminal worker running.""" + before = set(threading.enumerate()) + with pytest.raises(FileNotFoundError): + sp.open_terminal([str(tmp_path / "missing-executable")]) + assert not any( + thread.name.startswith("libvt-terminal") and thread not in before + for thread in threading.enumerate() + ) + + +@pytest.mark.skipif(os.name != "posix", reason="requires POSIX terminal job control") +def test_posix_foreground_and_signal_exit() -> None: + """Deliver a terminal interrupt to the foreground and reap its session owner.""" + script = ( + "import os, signal;\n" + "signal.signal(signal.SIGINT, signal.SIG_DFL)\n" + "if os.getpid() != os.getsid(0):\n" + " os.setpgid(0, 0)\n" + " signal.signal(signal.SIGTTOU, signal.SIG_IGN)\n" + " os.tcsetpgrp(0, os.getpgrp())\n" + "with open('/dev/tty', 'rb', buffering=0) as tty:\n" + " assert os.tcgetpgrp(tty.fileno()) == os.getpgrp()\n" + "print(f'FOREGROUND {os.getpid()} {os.getsid(0)}')\n" + "signal.pause()" + ) + with sp.open_terminal(_command(script)) as child: + frame = child.wait_for("FOREGROUND", timeout=8) + pid, sid = map(int, frame.lines[0].split()[1:]) + assert child.pid == pid + child.send_key("ctrl+c") + assert child.wait(8) == -signal.SIGINT + assert child.returncode == -signal.SIGINT + with pytest.raises(ProcessLookupError): + os.kill(sid, 0) + + +@pytest.mark.skipif( + sys.platform == "win32" or os.name != "posix", + reason="requires POSIX PTY and socketpair", +) +async def test_darwin_helper_uses_socketpair_without_temp_socket( + monkeypatch: pytest.MonkeyPatch, + tmp_path: pathlib.Path, +) -> None: + """Run the Darwin single-trampoline helper over socketpair with no Unix path.""" + + def _forbid(*_args: object, **_kwargs: object) -> t.NoReturn: + msg = "Darwin helper must use socketpair, not temp files or start_unix_server" + raise AssertionError(msg) + + long_tmp = tmp_path / ("x" * 120) + long_tmp.mkdir() + monkeypatch.setenv("TMPDIR", str(long_tmp)) + monkeypatch.setattr(tempfile, "TemporaryDirectory", _forbid) + if hasattr(asyncio, "start_unix_server"): + monkeypatch.setattr(asyncio, "start_unix_server", _forbid) + + command = ( + sys.executable, + "-u", + "-c", + ( + "import os; print('ready');" + "line = input();" + "print('done', line[::-1], *os.get_terminal_size())" + ), + ) + async with open_darwin_pty( + command, sp.VT(rows=6, cols=40, raw_limit=0), None, None + ) as attached: + await attached.io.wait_for("ready", timeout=5) + attached.resize(rows=9, cols=52) + attached.io.send(b"plum\n") + snap = await attached.io.wait_for("done mulp 52 9", timeout=5) + assert snap.cols == 52 + assert await attached.process.wait() == 0 + await attached.io.wait_for(lambda _: attached.io.eof, timeout=5) + + with pytest.raises(FileNotFoundError): + async with open_darwin_pty( + (str(tmp_path / "missing-darwin-exec"),), sp.VT(), None, None + ): + pass + + monkeypatch.setattr(sys, "platform", "darwin") + result = sp.run_terminal( + _command("print('DARWIN_DISPATCH')"), + vt=sp.VT(rows=4, cols=40, raw_limit=0), + check=True, + timeout=10, + ) + assert result.eof + assert result.raw_tail == b"" + assert result.raw_total > 0 + assert "DARWIN_DISPATCH" in result.snapshot.text + + +@pytest.mark.skipif( + sys.platform == "win32" or os.name != "posix", + reason="requires POSIX PTY and socketpair", +) +async def test_darwin_helper_preserves_session_for_descendant_and_sigint( + descendant_command: list[str], +) -> None: + """Keep the Darwin session leader alive for descendants and reap it on close.""" + async with open_darwin_pty( + tuple(descendant_command), sp.VT(), None, None + ) as attached: + assert await asyncio.wait_for(attached.process.wait(), timeout=8) == 17 + await attached.io.wait_for("DESCENDANT READY", timeout=8) + assert not attached.io.eof + attached.io.paste("fig") + attached.io.send_key("enter") + await attached.io.wait_for("LATE gif", timeout=8) + await attached.io.wait_for(lambda _: attached.io.eof, timeout=8) + + fg_script = ( + "import os, signal;\n" + "signal.signal(signal.SIGINT, signal.SIG_DFL)\n" + "os.setpgid(0, 0)\n" + "signal.signal(signal.SIGTTOU, signal.SIG_IGN)\n" + "os.tcsetpgrp(0, os.getpgrp())\n" + "with open('/dev/tty', 'rb', buffering=0) as tty:\n" + " assert os.tcgetpgrp(tty.fileno()) == os.getpgrp()\n" + "print(f'DARWIN_FG {os.getpid()} {os.getsid(0)}')\n" + "signal.pause()" + ) + async with open_darwin_pty( + tuple(_command(fg_script)), sp.VT(), None, None + ) as attached: + frame = await attached.io.wait_for("DARWIN_FG", timeout=8) + pid, sid = map(int, frame.lines[0].split()[1:]) + assert attached.process.pid == pid + assert pid != sid + attached.io.send_key("ctrl+c") + assert ( + await asyncio.wait_for(attached.process.wait(), timeout=8) == -signal.SIGINT + ) + with pytest.raises(ProcessLookupError): + os.kill(sid, 0) diff --git a/tests/test_terminal.py b/tests/test_terminal.py index bc00dbac..74d8550c 100644 --- a/tests/test_terminal.py +++ b/tests/test_terminal.py @@ -51,6 +51,7 @@ from libvt.screen import CursorShape, RowView, ScrollRegion, format_rows_text from libvt.style import AnsiColor, Hyperlink from libvt.terminal import ( + CellSpan, Formatter, OutputFormat, ResyncReason, @@ -2273,3 +2274,49 @@ def test_strided_memoryview_buffer_and_snapshot_format_profile_default() -> None vt_default = snap.format(OutputFormat.VT, profile=DEFAULT_PROFILE) assert "\x1b]10;rgb:0c0c/2222/3838\x1b\\" in vt_default assert "\x1b]11;rgb:c8c8/d2d2/dcdc\x1b\\" in vt_default + + +def test_snapshot_find_cells_matches_complete_graphemes_and_overlaps() -> None: + """Search the captured rows in order, with offsets at cell boundaries.""" + term = libvt.Terminal(rows=3, cols=12) + term.feed("界界界\r\ne\u0301👩\u200d🚀Go Go\r\nGo".encode()) + snap = term.committed + + hits = snap.find_cells("界界") + assert hits == (CellSpan(0, 0, 4), CellSpan(0, 2, 6)) + assert all(isinstance(hit, CellSpan) for hit in hits) + assert snap.find_cells("Go") == ((1, 3, 5), (1, 6, 8), (2, 0, 2)) + assert snap.find_cells("e\u0301👩\u200d🚀") == ((1, 0, 3),) + for text in ("e", "\u0301", "é", "👩", "🚀", "界e", "missing"): + assert snap.find_cells(text) == () + for text in ("", "Go\nGo", "Go\rGo"): + with pytest.raises(ValueError, match="nonempty"): + snap.find_cells(text) + + term.feed(b"\x1b[2J") + assert term.committed.find_cells("Go") == () + assert len(snap.find_cells("Go")) == 3 + + +def test_snapshot_find_cells_excludes_padding_and_split_wide_cells() -> None: + """Search written row extents across wrapping, resizing, and scrollback.""" + term = libvt.Terminal(rows=2, cols=4) + term.feed("abc界 ".encode()) + snap = term.committed + assert snap[0, 3].width_role is WidthRole.SPACER_HEAD + assert snap.find_cells(" ") == ((1, 2, 3),) + assert snap.find_cells("界 ") == ((1, 0, 3),) + assert snap.find_cells("c界") == () + + term.resize(rows=2, cols=1, reflow=False) + snap = term.committed + assert snap.find_cells("界") == () + assert snap.find_cells(" ") == () + + term = libvt.Terminal(rows=1, cols=8) + term.feed(b"past\r\n\x1b[3GGo\x1b[41m\x1b[K") + snap = term.committed + assert snap.history[0].text == "past" + assert snap.find_cells("past") == () + assert snap.find_cells(" Go") == ((0, 0, 4),) + assert snap.find_cells("Go ") == () diff --git a/tests/test_testing.py b/tests/test_testing.py index c53034b0..91940f9b 100644 --- a/tests/test_testing.py +++ b/tests/test_testing.py @@ -2,6 +2,7 @@ from __future__ import annotations +import json import os import pathlib import re @@ -18,6 +19,7 @@ decode_tmux_capture, ) from libvt.contrib.tmux.profile import tmux_profile +from libvt.exc import ScreenAssertionError from libvt.parser import Parser from libvt.pytest_plugin import TerminalFactory from libvt.terminal import FlightRecorder, Terminal, strip @@ -1807,3 +1809,562 @@ async def _check_stream_target() -> None: assert unescape_tmux_control_output(strided) == b"hello" ctrl_ev = TmuxControlParser().feed(memoryview(b"%XeYxZiWtW\n")[::2]) assert len(ctrl_ev) == 1 + + +@pytest.mark.parametrize( + ("cols", "actual", "expected", "cjk", "column", "shown_expected", "shown_actual"), + [ + (6, "ab", "a\u0301b", False, 0, "'a\u0301'", "'a'"), + (6, "a\u0301b", "ab", False, 0, "'a'", "'a\u0301'"), + (1, "a", "a\u0301", False, 0, "'a\u0301'", "'a'"), + (1, "a\u0301", "a", False, 0, "'a'", "'a\u0301'"), + (4, "Ωab", "Ωa\u0301b", True, 2, "'a\u0301'", "'a'"), + (4, "Ωa\u0301b", "Ωab", True, 2, "'a'", "'a\u0301'"), + (5, "\x1b[?2027l🇺🇬z", "🇺🇸z", False, 1, "'🇸'", "'🇬'"), + (5, "\x1b[?2027l🇺🇸a\u0301", "🇺🇸a", False, 2, "'a'", "'a\u0301'"), + (6, "\x1b[?2027l©️a\x1b[?2027h", "©️b", False, 1, "'b'", "'a'"), + (4, "日X ", "日X", False, 3, "padding", "' '"), + (4, "日X", "日X ", False, 3, "' '", "padding"), + (2, "日", "日 ", False, 2, "' '", "outside the viewport"), + ], +) +def test_screen_difference_uses_complete_glyphs_and_stored_columns( + cols: int, + actual: str, + expected: str, + cjk: bool, + column: int, + shown_expected: str, + shown_actual: str, +) -> None: + """Locate the difference at the captured cell's physical column.""" + term = Terminal( + rows=1, + cols=cols, + profile=Profile(unicode=UnicodeBehavior(ambiguous_width=2 if cjk else 1)), + ) + term.feed_str(actual) + snap = term.snapshot() + with pytest.raises(ScreenAssertionError) as error: + assert_screen(snap, [expected]) + assert str(error.value).splitlines()[2] == ( + f"First difference at row 0, column {column}: " + f"expected {shown_expected}, actual {shown_actual}" + ) + + +def test_screen_difference_uses_padding_column_before_wide_wrap() -> None: + """A wide-wrap spacer leaves room for the expected last cell in the preview.""" + term = Terminal(rows=2, cols=4) + term.feed_str("abc日") + snap = term.snapshot() + assert snap[0].wrapped + assert snap[0:2, 2:4].lines == ("c", "") + with pytest.raises(ScreenAssertionError) as error: + assert_screen(snap, ["abcX", "日"]) + assert str(error.value).splitlines()[2] == ( + "First difference at row 0, column 3: expected 'X', actual padding" + ) + + +def test_pytest_failure_replays_ordered_resize_and_written_space( + tmp_path: pathlib.Path, +) -> None: + """Replay a failing assertion from outside the original working directory.""" + script = tmp_path / "test_example.py" + example = pathlib.Path(__file__).resolve().parents[1] / "examples/replay_prompt.py" + shutil.copyfile(example, script) + outdir = tmp_path / "artifacts" + config = tmp_path / "pytest.ini" + config.write_text("[pytest]\n", encoding="utf-8") + env = {**os.environ, "PYTHONIOENCODING": "utf-8"} + result = subprocess.run( + [ + sys.executable, + "-m", + "pytest", + "-q", + "-c", + str(config), + f"--vt-replay-dir={outdir}", + str(script), + ], + cwd=tmp_path, + env=env, + capture_output=True, + text=True, + encoding="utf-8", + check=False, + ) + assert result.returncode == 1, result.stdout + result.stderr + assert "row 0, column 4" in result.stdout, result.stdout + assert "actual ' '" in result.stdout + (artifact,) = outdir.glob("*.json") + record = json.loads(artifact.read_text(encoding="utf-8")) + assert record["expected"] == [" X"] + assert record["actual"] == [" X ", ""] + assert record["encoding"] == "utf-8" + assert record["events"][:5] == [ + ["resize", 2, 4, False], + ["feed", "1b5b313b37"], + ["feed", "4858"], + ["resize", 2, 8, False], + ["feed", "1b5b313b354820"], + ] + replay_cwd = tmp_path / "elsewhere" + replay_cwd.mkdir() + replay_args = [ + sys.executable, + "-m", + "libvt", + "replay", + "--chunk-size", + "1", + str(artifact), + ] + offline = subprocess.run( + replay_args, + cwd=replay_cwd, + env=env, + capture_output=True, + text=True, + encoding="utf-8", + check=False, + ) + assert offline.returncode == 0, offline.stderr + assert "' X '" in offline.stdout + + record["events"] = [event for event in record["events"] if event[0] != "resize"] + artifact.write_text(json.dumps(record), encoding="utf-8") + without_resize = subprocess.run( + replay_args, + cwd=replay_cwd, + env=env, + capture_output=True, + text=True, + encoding="utf-8", + check=False, + ) + assert without_resize.returncode == 1 + assert "differs from the artifact" in without_resize.stdout + + +@pytest.mark.skipif(os.name != "posix", reason="requires a POSIX terminal") +def test_pytest_replays_a_real_pty_failure(tmp_path: pathlib.Path) -> None: + """Capture startup output, a resize, and the child's acknowledgement.""" + script = tmp_path / "test_child.py" + script.write_text( + "import os\n" + "import sys\n" + "import pytest\n" + "from libvt.testing import assert_screen\n" + "@pytest.mark.asyncio\n" + "async def test_child(vt_pty, tmp_path):\n" + " root = tmp_path / 'child'\n" + " root.mkdir()\n" + " code = (\n" + " 'import os, tempfile; '\n" + " 'assert tempfile.gettempdir() == os.environ[\"TMPDIR\"]; '\n" + " \"print('Ready'); print('Taken: ' + input())\"\n" + " )\n" + " env = {**os.environ, 'TMPDIR': str(root)}\n" + " async with vt_pty([sys.executable, '-u', '-c', code], " + "rows=4, cols=16, env=env) as session:\n" + " await session.wait_for('Ready', timeout=5)\n" + " session.resize(rows=5, cols=20)\n" + " session.paste('lime')\n" + " session.send_key('enter')\n" + " await session.wait_for('Taken: lime', timeout=5)\n" + " assert_screen(session.terminal, ['wrong'])\n", + encoding="utf-8", + ) + outdir = tmp_path / "artifacts" + result = subprocess.run( + [ + sys.executable, + "-m", + "pytest", + "-q", + f"--vt-replay-dir={outdir}", + str(script), + ], + cwd=tmp_path, + capture_output=True, + text=True, + check=False, + ) + assert result.returncode == 1 and "actual 'R'" in result.stdout, result.stdout + (path,) = outdir.glob("*.json") + artifact = json.loads(path.read_text(encoding="utf-8")) + assert (artifact["rows"], artifact["cols"]) == (4, 16) + assert artifact["incomplete"] is None + assert artifact["expected"] == ["wrong"] + resized = next( + i for i, event in enumerate(artifact["events"]) if event[0] == "resize" + ) + before = b"".join(bytes.fromhex(data) for _, data in artifact["events"][:resized]) + after = b"".join( + bytes.fromhex(data) for _, data in artifact["events"][resized + 1 :] + ) + assert b"Ready" in before and b"Taken: lime" in after + replay = subprocess.run( + [sys.executable, "-m", "libvt", "replay", "--chunk-size", "1", str(path)], + cwd=tmp_path, + capture_output=True, + text=True, + check=True, + ) + assert "'Taken: lime'" in replay.stdout and "actual 'R'" in replay.stdout + + +def test_pytest_replay_fallback_and_incomplete_capture(tmp_path: pathlib.Path) -> None: + """Keep actual rows for plain failures and explain incomplete replay.""" + script = tmp_path / "test_example.py" + script.write_text( + "from libvt.config import Profile, UnicodeBehavior\n" + "from libvt.testing import assert_screen\n" + "def test_plain(vt_terminal):\n" + " vt_terminal.feed(b'actual')\n" + " assert vt_terminal.lines[0] == 'expected'\n" + "def test_unsupported(vt_factory):\n" + " profile = Profile(unicode=UnicodeBehavior(ambiguous_width=2))\n" + " term = vt_factory(rows=1, cols=8, profile=profile)\n" + " term.feed(b'actual ')\n" + " assert_screen(term, ['actual'])\n" + "def test_truncated(vt_terminal):\n" + " for _ in range(10_001):\n" + " vt_terminal.feed(b'\\x00')\n" + " vt_terminal.feed(b'late')\n" + " assert_screen(vt_terminal, ['early'])\n" + "def test_snapshot(vt_terminal):\n" + " vt_terminal.feed(b'original')\n" + " snap = vt_terminal.committed\n" + " vt_terminal.feed(b' later')\n" + " assert_screen(snap, ['expected'])\n" + "def test_pass(vt_terminal):\n" + " vt_terminal.feed(b'ok')\n" + " assert_screen(vt_terminal, ['ok'])\n", + encoding="utf-8", + ) + (tmp_path / "pytest.ini").write_text("[pytest]\n", encoding="utf-8") + outdir = tmp_path / "artifacts" + env = {**os.environ, "PYTHONIOENCODING": "utf-8"} + pytest_args = [sys.executable, "-m", "pytest", "-q", str(script)] + for options in ([], [f"--vt-replay-dir={outdir}"]): + result = subprocess.run( + [*pytest_args, *options], + cwd=tmp_path, + env=env, + capture_output=True, + text=True, + encoding="utf-8", + check=False, + ) + assert result.returncode == 1, result.stdout + result.stderr + assert "4 failed, 1 passed" in result.stdout, result.stdout + if not options: + assert not outdir.exists() + artifacts = { + record["actual"][0]: (record, path) + for path in outdir.glob("*.json") + if (record := json.loads(path.read_text(encoding="utf-8"))) + } + assert set(artifacts) == {"actual", "actual ", "late", "original later"} + assert artifacts["actual"][0]["expected"] is None + assert artifacts["original later"][0]["expected"] is None + assert artifacts["actual "][0]["expected"] == ["actual"] + assert "default profile" in artifacts["actual "][0]["incomplete"] + record, path = artifacts["late"] + assert "byte or event limit" in record["incomplete"] + assert record["expected"] == ["early"] + assert len(record["events"]) == 10_000 + offline = subprocess.run( + [sys.executable, "-m", "libvt", "replay", str(path)], + cwd=tmp_path, + env=env, + capture_output=True, + text=True, + encoding="utf-8", + check=False, + ) + assert offline.returncode == 1, offline.stderr + assert "Replay unavailable" in offline.stdout + assert "row 0: 'late'" in offline.stdout + assert "expected 'e', actual 'l'" in offline.stdout + + +@pytest.mark.parametrize( + ("cols", "payload", "expected", "diagnostic"), + [ + (8, "\x1b[?2027le\u0301Y", ["XY"], "column 0: expected 'X', actual 'e\u0301'"), + (8, "ready>", ["ready> "], "column 6: expected ' ', actual padding"), + (8, "ready> ", ["ready>"], "column 6: expected padding, actual ' '"), + (8, "日X", ["日Y"], "column 2: expected 'Y', actual 'X'"), + (2, "OK", ["OK!"], "column 2: expected '!', actual outside the viewport"), + (2, "OK", ["OK", "extra"], "row 1 beyond the viewport"), + ], +) +def test_assert_screen_identifies_exact_cell_or_boundary( + cols: int, payload: str, expected: list[str], diagnostic: str +) -> None: + """Describe the stored cell or exact viewport boundary on mismatch.""" + term = Terminal(rows=1, cols=cols) + term.feed(payload.encode()) + with pytest.raises(AssertionError) as caught: + assert_screen(term, expected) + assert diagnostic in str(caught.value) + + +def _record_failure( + tmp_path: pathlib.Path, + body: str, + *, + plugins: tuple[str, ...] = ("libvt.pytest_plugin",), +) -> tuple[pathlib.Path, str]: + root = tmp_path / "owned" + root.mkdir(exist_ok=True) + script = root / "test_example.py" + script.write_text(body, encoding="utf-8") + config = root / "pytest.ini" + config.write_text("[pytest]\n", encoding="utf-8") + out = root / "replay" + plugin_args: list[str] = [] + for plugin in plugins: + plugin_args.extend(("-p", plugin)) + result = subprocess.run( + [ + sys.executable, + "-m", + "pytest", + *plugin_args, + "-q", + "-c", + str(config), + f"--vt-replay-dir={out}", + str(script), + ], + cwd=root, + env={**os.environ, "PYTEST_DISABLE_PLUGIN_AUTOLOAD": "1", "PYTHONUTF8": "1"}, + capture_output=True, + text=True, + encoding="utf-8", + timeout=15, + check=False, + ) + assert result.returncode == 1, result.stdout + result.stderr + (path,) = out.glob("*.json") + assert str(path) in result.stdout + return path, result.stdout + + +def _replay(path: pathlib.Path) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, "-m", "libvt", "replay", "--chunk-size", "1", str(path)], + cwd=path.parent, + env={**os.environ, "PYTHONUTF8": "1"}, + capture_output=True, + text=True, + encoding="utf-8", + timeout=10, + check=False, + ) + + +def test_replay_rejects_style_only_change(tmp_path: pathlib.Path) -> None: + """Verify that an unchanged line can still differ in style.""" + path, _stdout = _record_failure( + tmp_path, + "from libvt.testing import assert_screen\n" + "def test_example(vt_factory):\n" + " term = vt_factory(rows=2, cols=6)\n" + " term.feed(b'\\x1b[31mQ')\n" + " assert_screen(term, ['wrong'])\n", + ) + original = json.loads(path.read_text(encoding="utf-8")) + assert original["actual"] == ["Q", ""] + assert original["events"] == [["feed", "1b5b33316d51"]] + match = _replay(path) + assert match.returncode == 0, match.stdout + match.stderr + original["events"][0] = ["feed", "1b5b33326d51"] + path.write_text(json.dumps(original), encoding="utf-8") + result = _replay(path) + assert result.returncode == 1, result.stdout + result.stderr + assert "differs from the artifact" in result.stdout + + +def test_replay_preserves_exact_assertion_prefix(tmp_path: pathlib.Path) -> None: + """Capture the frame before failure cleanup mutates the terminal.""" + path, _stdout = _record_failure( + tmp_path, + "from libvt.testing import assert_screen\n" + "def test_example(vt_factory):\n" + " term = vt_factory(rows=2, cols=6)\n" + " term.feed(b'before')\n" + " try:\n" + " assert_screen(term, ['before\u0301'])\n" + " finally:\n" + " term.feed(b'late')\n", + ) + record = json.loads(path.read_text(encoding="utf-8")) + assert record["actual"] == ["before", ""] + assert record["events"] == [["feed", "6265666f7265"]] + assert record["expected"] == ["before\u0301"] + difference = "First difference at row 0, column 5: expected 'e\u0301', actual 'e'" + assert record["difference"] == difference + replay = _replay(path) + assert replay.returncode == 0, replay.stderr + assert difference in replay.stdout + + +def test_replay_requires_only_bytes_consumed_by_feed_until( + tmp_path: pathlib.Path, +) -> None: + """Capture the reported input slice and keep the fixture's raw recorder.""" + path, _stdout = _record_failure( + tmp_path, + "from libvt.terminal import StopOn\n" + "from libvt.testing import assert_screen\n" + "def test_example(vt_factory, vt_recorder):\n" + " term = vt_factory(rows=2, cols=8, recorder=vt_recorder)\n" + " assert term.recorder is vt_recorder\n" + " data = b'ignored\\x1b[?2026hframe\\x1b[?2026lunused'\n" + " step = term.feed_until(data, offset=7, stop=StopOn.SYNC_END)\n" + " assert data[step.offset:] == b'unused'\n" + " assert_screen(term, ['wrong'])\n", + ) + record = json.loads(path.read_text(encoding="utf-8")) + assert record["actual"] == ["frame", ""] + capture = b"".join( + bytes.fromhex(data) for kind, data in record["events"] if kind == "feed" + ) + assert capture == b"\x1b[?2026hframe\x1b[?2026l" + assert _replay(path).returncode == 0 + + +def test_replay_distinguishes_wire_resize_from_external_resize( + tmp_path: pathlib.Path, +) -> None: + """Replay DECCOLM from its bytes and record the external resize separately.""" + path, _stdout = _record_failure( + tmp_path, + "from libvt.testing import assert_screen\n" + "def test_example(vt_factory, vt_recorder):\n" + " term = vt_factory(rows=2, cols=8, recorder=vt_recorder)\n" + " assert term.recorder is vt_recorder\n" + " term.feed(b'\\x1b[?40h\\x1b[?3hX')\n" + " assert term.cols == 132\n" + " term.resize(rows=2, cols=6, reflow=False)\n" + " assert_screen(term, ['wrong'])\n", + ) + artifact = json.loads(path.read_text(encoding="utf-8")) + assert artifact["actual"] == ["X", ""] + assert artifact["events"] == [ + ["feed", "1b5b3f3430681b5b3f336858"], + ["resize", 2, 6, False], + ] + assert _replay(path).returncode == 0 + + +def test_replay_slotted_terminal_strided_buffers_and_deccolm( + tmp_path: pathlib.Path, +) -> None: + """Slotted Terminal, strided feeds, DECCOLM, and FlightRecorder coexist.""" + path, stdout = _record_failure( + tmp_path, + "from libvt.terminal import StopOn\n" + "from libvt.testing import assert_screen\n" + "def test_example(vt_terminal, vt_recorder):\n" + " assert not hasattr(vt_terminal, '__dict__')\n" + " assert vt_terminal.recorder is vt_recorder\n" + " raw1 = b'\\x1b[?40h\\x1b[?3hAB'\n" + " b1 = bytearray(len(raw1) * 2)\n" + " b1[::2] = raw1[::-1]\n" + " strided_rev = memoryview(b1)[::2][::-1]\n" + " vt_terminal.feed(strided_rev)\n" + " assert vt_terminal.cols == 132\n" + " vt_terminal.resize(rows=2, cols=8, reflow=False)\n" + " raw2 = b'skip\\x1b[?2026hCD\\x1b[?2026lrest'\n" + " b2 = bytearray(len(raw2) * 2)\n" + " b2[::2] = raw2\n" + " strided2 = memoryview(b2)[::2]\n" + " step = vt_terminal.feed_until(strided2, offset=4, stop=StopOn.SYNC_END)\n" + " assert bytes(strided2[step.offset:]) == b'rest'\n" + " assert vt_recorder.tail().endswith(b'\\x1b[?2026hCD\\x1b[?2026l')\n" + " assert_screen(vt_terminal, ['wrong'])\n", + ) + assert "recent_bytes (" in stdout + record = json.loads(path.read_text(encoding="utf-8")) + assert record["incomplete"] is None + assert record["encoding"] == "utf-8" + assert record["actual"] == ["ABCD", ""] + assert record["events"] == [ + ["feed", b"\x1b[?40h\x1b[?3hAB".hex()], + ["resize", 2, 8, False], + ["feed", b"\x1b[?2026hCD\x1b[?2026l".hex()], + ] + replay = _replay(path) + assert replay.returncode == 0, replay.stdout + replay.stderr + assert "'ABCD'" in replay.stdout + + +def test_replay_latin1_encoding_roundtrip(tmp_path: pathlib.Path) -> None: + """Record and replay ``encoding='latin-1'`` and reject invalid encodings.""" + path, _stdout = _record_failure( + tmp_path, + "from libvt.testing import assert_screen\n" + "def test_latin1(vt_factory):\n" + " term = vt_factory(rows=2, cols=8, encoding='latin-1')\n" + " assert not hasattr(term, '__dict__')\n" + " term.feed(b'caf\\xe9')\n" + " assert_screen(term, ['cafe'])\n", + ) + record = json.loads(path.read_text(encoding="utf-8")) + assert record["incomplete"] is None + assert record["encoding"] == "latin-1" + assert record["actual"] == ["café", ""] + assert record["events"] == [["feed", b"caf\xe9".hex()]] + replay = _replay(path) + assert replay.returncode == 0, replay.stdout + replay.stderr + assert "'café'" in replay.stdout + + record["encoding"] = "ascii" + path.write_text(json.dumps(record), encoding="utf-8") + invalid = _replay(path) + assert invalid.returncode == 2 + assert "Invalid encoding" in invalid.stderr + + +@pytest.mark.skipif(os.name != "posix", reason="requires a POSIX terminal") +def test_replay_pty_slotted_and_latin1(tmp_path: pathlib.Path) -> None: + """``vt_pty`` attaches replay onto slotted ``Terminal`` with latin-1 encoding.""" + path, stdout = _record_failure( + tmp_path, + "import sys\n" + "import pytest\n" + "from libvt.testing import assert_screen\n" + "@pytest.mark.asyncio\n" + "async def test_pty_replay(vt_pty):\n" + " code = (\n" + " \"import sys; sys.stdout.buffer.write(b'caf\\\\xe9\\\\n'); \"\n" + " \"sys.stdout.buffer.flush(); print('got:' + input())\"\n" + " )\n" + " argv = [sys.executable, '-u', '-c', code]\n" + " async with vt_pty(argv, rows=4, cols=16, encoding='latin-1') as session:\n" + " assert not hasattr(session.terminal, '__dict__')\n" + " await session.wait_for('café', timeout=5)\n" + " session.resize(rows=5, cols=20)\n" + " session.paste('ok')\n" + " session.send_key('enter')\n" + " await session.wait_for('got:ok', timeout=5)\n" + " assert_screen(session.terminal, ['wrong'])\n", + plugins=("pytest_asyncio.plugin", "libvt.pytest_plugin"), + ) + assert "recent_bytes (" in stdout + record = json.loads(path.read_text(encoding="utf-8")) + assert record["incomplete"] is None + assert record["encoding"] == "latin-1" + assert (record["rows"], record["cols"]) == (4, 16) + assert any(ev[0] == "resize" and ev[1:3] == [5, 20] for ev in record["events"]) + replay = _replay(path) + assert replay.returncode == 0, replay.stdout + replay.stderr + assert "'café'" in replay.stdout and "'got:ok'" in replay.stdout diff --git a/tests/test_tmux.py b/tests/test_tmux.py index dfbbacdf..5e2e20a1 100644 --- a/tests/test_tmux.py +++ b/tests/test_tmux.py @@ -2,11 +2,13 @@ from __future__ import annotations +import asyncio import os import pathlib import selectors import shutil import subprocess +import sys import tempfile import time @@ -24,6 +26,7 @@ build_tmux_capture_command, decode_tmux_capture, parse_flagged_line, + parse_tmux_version, tmux_profile, unescape_tmux_control_output, ) @@ -2078,3 +2081,81 @@ def begin_capture(locate: str) -> list[TmuxCommandBlock]: with pytest.raises(ProtocolError, match=r"3\.2"): TmuxPaneSync("%0", tmux_version="3.1c").watch_process() + + +@pytest.mark.skipif(os.name != "posix", reason="attached tmux requires a POSIX PTY") +@pytest.mark.parametrize( + ("stale", "optimized"), [(False, False), (True, False), (True, True)] +) +def test_attached_tmux_screen_example( + tmp_path: pathlib.Path, stale: bool, optimized: bool +) -> None: + """Exercise the guide against a real attached client and a stale origin.""" + binary = shutil.which(os.environ.get("TMUX_BIN", "tmux")) + if binary is None: + pytest.skip("tmux binary not installed") + version = subprocess.check_output([binary, "-V"], text=True, timeout=5).strip() + if parse_tmux_version(version) < (3, 1): + pytest.skip("The example requires tmux 3.1 or newer") + commands = subprocess.check_output( + [binary, "-S", str(tmp_path / "s"), "list-commands", "capture-pane"], + text=True, + timeout=5, + ) + flags = commands.partition("[")[2].partition("]")[0] + if "N" not in flags: + pytest.skip("tmux capture-pane -N is unavailable") + script = pathlib.Path(__file__).resolve().parents[1] / "examples/tmux_screens.py" + args = [sys.executable, str(script), "--tmux", binary] + if optimized: + args.insert(1, "-O") + if stale: + args.append("--stale-origin") + result = subprocess.run( + args, capture_output=True, text=True, timeout=30, check=False + ) + if stale: + assert result.returncode == 1, result.stdout + result.stderr + assert "Picker reported release row=2 col=11" in result.stderr + else: + assert result.returncode == 0, result.stdout + result.stderr + assert "app pane: ARCHIVE LIVE" in result.stdout + assert "attached copy mode: Ledger entry 00" in result.stdout + assert "Picker received press, release and key at (2, 3)" in result.stdout + + assert ("mode capture at scroll offset: Ledger entry 00" in result.stdout) == ( + "M" in flags + ) + + +@pytest.mark.asyncio +async def test_tmux_example_reaps_cancelled_command(tmp_path: pathlib.Path) -> None: + """Drain full command pipes and reap the child when the caller cancels.""" + if sys.platform == "win32": + pytest.skip("the tmux guide runs on a POSIX terminal") + from examples.tmux_screens import _run + + ready = tmp_path / "ready" + script = ( + "import os, pathlib, sys, time\n" + "sys.stdout.buffer.write(b'O' * 262144)\n" + "sys.stderr.buffer.write(b'E' * 262144)\n" + "ready = pathlib.Path(sys.argv[1])\n" + "pending = ready.with_suffix('.tmp')\n" + "pending.write_text(str(os.getpid()))\n" + "pending.rename(ready)\n" + "time.sleep(30)\n" + ) + task = asyncio.create_task( + _run(sys.executable, "-c", script, str(ready), env=dict(os.environ)) + ) + try: + async with asyncio.timeout(4): + while not ready.exists(): + await asyncio.sleep(0.01) + finally: + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + with pytest.raises(ProcessLookupError): + os.kill(int(ready.read_text()), 0)