diff --git a/CHANGES b/CHANGES index 06d60e7..2a10109 100644 --- a/CHANGES +++ b/CHANGES @@ -66,6 +66,12 @@ Deleting an attribute on {class}`~libvt.snapshot.Snapshot` now raises ### Documentation +#### Test selection and cancellation in fzf (#138) + +The {ref}`fzf recipe ` drives a live picker in a private +PTY and verifies the highlighted item, alternate-screen restore, selected +output, and exit status for Enter, Escape, and Ctrl-C. + #### Document lazy root imports and module boundaries {ref}`topics-architecture` documents PEP 562 lazy root resolution on diff --git a/README.md b/README.md index 0f266db..3c4d7e0 100644 --- a/README.md +++ b/README.md @@ -208,7 +208,9 @@ styles: (`?2026`). - Encode keyboard, mouse, focus, and paste events according to the active terminal modes. -- Run terminal programs on POSIX PTYs or connect to `asyncio` streams. +- Run terminal programs on POSIX PTYs or connect to `asyncio` streams (see the + [fzf cookbook][fzf_cookbook] for driving a live picker and verifying Enter, + Escape, and Ctrl-C outcomes). Read `tmux` captures as screen cells and decode control-mode output with [`libvt.contrib.tmux`](https://libvt.git-pull.com/api/contrib/tmux/). Full @@ -231,3 +233,4 @@ MIT License. See [LICENSE](LICENSE). [render]: https://libvt.git-pull.com/api/terminal/#libvt.terminal.render [strip]: https://libvt.git-pull.com/api/terminal/#libvt.terminal.strip [explain]: https://libvt.git-pull.com/api/codec/#libvt.codec.explain +[fzf_cookbook]: https://libvt.git-pull.com/topics/testing/#topics-testing-fzf diff --git a/docs/topics/testing.md b/docs/topics/testing.md index dc031a1..79f53df 100644 --- a/docs/topics/testing.md +++ b/docs/topics/testing.md @@ -519,6 +519,42 @@ with no dependency on `syrupy` or any other snapshot tool: --- +(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. + +{meth}`~libvt.aio.PtySession.wait_for` evaluates committed frames across +`fzf`'s `?2026` synchronized redraws; see +{ref}`testing-working-and-committed-frames`. Passing the returned +{class}`~libvt.snapshot.Snapshot` (or `picker.terminal.committed` after exit) +to {func}`~libvt.testing.assert_screen` checks that exact committed frame, +including `?1049` alternate-screen entry and primary-screen restoration. + +The test uses [pytest-asyncio](https://pytest-asyncio.readthedocs.io/). +Install `fzf` on a POSIX host, then run all 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: test_select_or_cancel = +``` + +Down highlights the second Cedar record on the alternate screen. Enter returns +that line with a newline. Escape and Ctrl-C exit with status 130 and leave the +selection file empty, restoring the primary screen on exit. + +--- + ## Syrupy `.ambr` adapter (`libvt.contrib.syrupy`) Install the optional `syrupy` extra when storing golden snapshots in `.ambr` diff --git a/tests/test_fzf_cookbook.py b/tests/test_fzf_cookbook.py new file mode 100644 index 0000000..19e802d --- /dev/null +++ b/tests/test_fzf_cookbook.py @@ -0,0 +1,209 @@ +"""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 +from libvt.testing import assert_screen + + +@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""), + ("ctrl+c", 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 = ( + "printf 'primary-before\\n' >/dev/tty; " + 'exec "$1" --sync --no-sort --layout=reverse --pointer=+ choice' + ) + argv = ["/bin/sh", "-c", command, "sh", str(pathlib.Path(fzf).absolute())] + 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") + highlighted = await picker.wait_for( + lambda s: any( + row.startswith("+") and "Cedar / invoice" in row for row in s.lines + ), + timeout=5, + ) + assert highlighted.active_is_alt is True + assert highlighted.lines[0].rstrip() == "> cedar" + assert (highlighted.cursor.row, highlighted.cursor.col) == (0, 7) + assert any( + "Cedar / manifest" in row and not row.startswith("+") + for row in highlighted.lines + ) + picker.send_key(key) + assert await asyncio.wait_for(picker.process.wait(), timeout=5) == status + final = picker.terminal.committed + assert final.active_is_alt is False + assert_screen(final, ["primary-before"]) + assert (tmp_path / "choice").read_bytes() == output + + +test_select_or_cancel = pytest.mark.integration(test_select_or_cancel) + +_PYTHON_PICKER = r""" +import os, sys, termios, tty + +items = [line.rstrip("\r\n") for line in sys.stdin if line.strip()] +tty_fd = os.open("/dev/tty", os.O_RDWR) +old = termios.tcgetattr(tty_fd) +query = "" +selected = 0 + +def filtered() -> list[str]: + q = query.lower() + return [item for item in items if q in item.lower()] + +def draw() -> None: + shown = filtered() + lines = [f"> {query}", f" {len(shown)}/{len(items)}"] + for idx, item in enumerate(shown): + prefix = "+ " if idx == selected else " " + lines.append(f"{prefix}{item}") + frame = ( + "\x1b[?2026h\x1b[2J\x1b[H" + + "\r\n".join(lines) + + f"\x1b[1;{len(query) + 3}H\x1b[?2026l" + ) + os.write(tty_fd, frame.encode("utf-8")) + +code = 130 +try: + tty.setraw(tty_fd) + os.write(tty_fd, b"\x1b[?1049h\x1b[?2004h") + draw() + while True: + # Handle bare Escape without blocking when no trailing CSI bytes arrive. + ch = os.read(tty_fd, 1) + if ch == b"\r" or ch == b"\n": + shown = filtered() + if shown: + sys.stdout.write(shown[selected] + "\n") + sys.stdout.flush() + code = 0 + break + if ch == b"\x03": + code = 130 + break + if ch == b"\x1b": + import select + if not select.select([tty_fd], [], [], 0.05)[0]: + code = 130 + break + seq = os.read(tty_fd, 2) + if seq == b"[B": + shown = filtered() + if selected + 1 < len(shown): + selected += 1 + elif seq == b"[2": + buf = bytearray(b"\x1b[2") + while not buf.endswith(b"\x1b[201~"): + buf.extend(os.read(tty_fd, 1)) + query += buf[6:-6].decode("utf-8") + selected = 0 + draw() +finally: + os.write(tty_fd, b"\x1b[?2004l\x1b[?1049l") + termios.tcsetattr(tty_fd, termios.TCSADRAIN, old) + os.close(tty_fd) +sys.exit(code) +""" + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("key", "status", "output"), + [ + ("enter", 0, b"Cedar / invoice\n"), + ("escape", 130, b""), + ("ctrl+c", 130, b""), + ], +) +async def test_tty_picker_protocol_select_and_cancel( + tmp_path: pathlib.Path, key: str, status: int, output: bytes +) -> None: + """Exercise stdin/TTY/stdout separation, ?1049, and ?2026 on every POSIX host.""" + (tmp_path / "jobs").write_text( + "Birch / crate\nCedar / manifest\nCedar / invoice\n", encoding="ascii" + ) + picker_py = tmp_path / "picker.py" + picker_py.write_text(_PYTHON_PICKER, encoding="utf-8") + command = 'printf \'primary-before\\n\' >/dev/tty; exec "$1" -u "$2" choice' + argv = ["/bin/sh", "-c", command, "sh", sys.executable, str(picker_py)] + 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") + highlighted = await picker.wait_for( + lambda s: any( + row.startswith("+ ") and "Cedar / invoice" in row for row in s.lines + ), + timeout=5, + ) + assert highlighted.active_is_alt is True + assert_screen( + highlighted, + [ + "> cedar", + " 2/3", + " Cedar / manifest", + "+ Cedar / invoice", + ], + cursor=(0, 7), + ) + picker.send_key(key) + assert await asyncio.wait_for(picker.process.wait(), timeout=5) == status + final = picker.terminal.committed + assert final.active_is_alt is False + assert_screen(final, ["primary-before"]) + assert (tmp_path / "choice").read_bytes() == output