Skip to content

Commit c33aee3

Browse files
authored
docs(testing): Add fzf cookbook (#138)
why: Interactive pickers like fzf separate candidate stdin, controlling TTY UI (?1049/?2026), and selected stdout, so testing them requires redirecting I/O files while driving a private PTY. what: Add a standalone fzf selection and cancellation cookbook in docs/topics/testing.md linked from README.md and CHANGES, plus tests/test_fzf_cookbook.py with real fzf integration tests (Enter, Escape, Ctrl-C, alt-screen restore) and a deterministic pure-Python POSIX PTY picker companion. Fixes #132
2 parents 4530d88 + 22c9357 commit c33aee3

4 files changed

Lines changed: 255 additions & 1 deletion

File tree

‎CHANGES‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,12 @@ Deleting an attribute on {class}`~libvt.snapshot.Snapshot` now raises
6666

6767
### Documentation
6868

69+
#### Test selection and cancellation in fzf (#138)
70+
71+
The {ref}`fzf recipe <topics-testing-fzf>` drives a live picker in a private
72+
PTY and verifies the highlighted item, alternate-screen restore, selected
73+
output, and exit status for Enter, Escape, and Ctrl-C.
74+
6975
#### Document lazy root imports and module boundaries
7076

7177
{ref}`topics-architecture` documents PEP 562 lazy root resolution on

‎README.md‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -208,7 +208,9 @@ styles:
208208
(`?2026`).
209209
- Encode keyboard, mouse, focus, and paste events according to the active
210210
terminal modes.
211-
- Run terminal programs on POSIX PTYs or connect to `asyncio` streams.
211+
- Run terminal programs on POSIX PTYs or connect to `asyncio` streams (see the
212+
[fzf cookbook][fzf_cookbook] for driving a live picker and verifying Enter,
213+
Escape, and Ctrl-C outcomes).
212214

213215
Read `tmux` captures as screen cells and decode control-mode output with
214216
[`libvt.contrib.tmux`](https://libvt.git-pull.com/api/contrib/tmux/). Full
@@ -231,3 +233,4 @@ MIT License. See [LICENSE](LICENSE).
231233
[render]: https://libvt.git-pull.com/api/terminal/#libvt.terminal.render
232234
[strip]: https://libvt.git-pull.com/api/terminal/#libvt.terminal.strip
233235
[explain]: https://libvt.git-pull.com/api/codec/#libvt.codec.explain
236+
[fzf_cookbook]: https://libvt.git-pull.com/topics/testing/#topics-testing-fzf

‎docs/topics/testing.md‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -519,6 +519,42 @@ with no dependency on `syrupy` or any other snapshot tool:
519519

520520
---
521521

522+
(topics-testing-fzf)=
523+
524+
## Select or cancel in fzf
525+
526+
[fzf](https://github.com/junegunn/fzf) reads candidates from standard input,
527+
draws its picker on the controlling terminal, and writes the accepted record
528+
to standard output. Use {func}`~libvt.aio.open_pty` for the screen and redirect
529+
the records to files in the test directory. The picker gets an 8-row,
530+
40-column PTY and uses that directory for temporary files.
531+
532+
{meth}`~libvt.aio.PtySession.wait_for` evaluates committed frames across
533+
`fzf`'s `?2026` synchronized redraws; see
534+
{ref}`testing-working-and-committed-frames`. Passing the returned
535+
{class}`~libvt.snapshot.Snapshot` (or `picker.terminal.committed` after exit)
536+
to {func}`~libvt.testing.assert_screen` checks that exact committed frame,
537+
including `?1049` alternate-screen entry and primary-screen restoration.
538+
539+
The test uses [pytest-asyncio](https://pytest-asyncio.readthedocs.io/).
540+
Install `fzf` on a POSIX host, then run all outcomes from the repository root.
541+
542+
```console
543+
$ uv run pytest tests/test_fzf_cookbook.py
544+
```
545+
546+
```{literalinclude} ../../tests/test_fzf_cookbook.py
547+
:language: python
548+
:start-at: import asyncio
549+
:end-before: test_select_or_cancel =
550+
```
551+
552+
Down highlights the second Cedar record on the alternate screen. Enter returns
553+
that line with a newline. Escape and Ctrl-C exit with status 130 and leave the
554+
selection file empty, restoring the primary screen on exit.
555+
556+
---
557+
522558
## Syrupy `.ambr` adapter (`libvt.contrib.syrupy`)
523559

524560
Install the optional `syrupy` extra when storing golden snapshots in `.ambr`

‎tests/test_fzf_cookbook.py‎

Lines changed: 209 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,209 @@
1+
"""Drive fzf through its terminal and inspect its separate selection output."""
2+
3+
from __future__ import annotations
4+
5+
import asyncio
6+
import os
7+
import pathlib
8+
import shutil
9+
import sys
10+
11+
import pytest
12+
13+
from libvt.aio import open_pty
14+
from libvt.testing import assert_screen
15+
16+
17+
@pytest.fixture(scope="module", autouse=True)
18+
def available_pty() -> None:
19+
"""Skip the picker if the host cannot allocate a terminal."""
20+
if sys.platform == "win32":
21+
pytest.skip("requires a POSIX terminal")
22+
23+
import pty
24+
25+
try:
26+
master, slave = pty.openpty()
27+
except OSError as error:
28+
pytest.skip(f"cannot allocate a POSIX terminal: {error}")
29+
os.close(master)
30+
os.close(slave)
31+
32+
33+
@pytest.mark.asyncio
34+
@pytest.mark.parametrize(
35+
("key", "status", "output"),
36+
[
37+
("enter", 0, b"Cedar / invoice\n"),
38+
("escape", 130, b""),
39+
("ctrl+c", 130, b""),
40+
],
41+
)
42+
async def test_select_or_cancel(
43+
tmp_path: pathlib.Path, key: str, status: int, output: bytes
44+
) -> None:
45+
"""Follow the pointer to an invoice, then check what fzf returned."""
46+
fzf = shutil.which("fzf")
47+
if fzf is None:
48+
pytest.skip("install fzf to run the picker example")
49+
(tmp_path / "jobs").write_text(
50+
"Birch / crate\nCedar / manifest\nCedar / invoice\n", encoding="ascii"
51+
)
52+
command = (
53+
"printf 'primary-before\\n' >/dev/tty; "
54+
'exec "$1" --sync --no-sort --layout=reverse --pointer=+ <jobs >choice'
55+
)
56+
argv = ["/bin/sh", "-c", command, "sh", str(pathlib.Path(fzf).absolute())]
57+
env = {"HOME": str(tmp_path), "TMPDIR": str(tmp_path), "TERM": "xterm-256color"}
58+
async with open_pty(argv, rows=8, cols=40, cwd=tmp_path, env=env) as picker:
59+
await picker.wait_for("Birch / crate", timeout=5)
60+
picker.paste("cedar")
61+
await picker.wait_for(
62+
lambda s: "Cedar / invoice" in s.text and "Birch / crate" not in s.text,
63+
timeout=5,
64+
)
65+
picker.send_key("down")
66+
highlighted = await picker.wait_for(
67+
lambda s: any(
68+
row.startswith("+") and "Cedar / invoice" in row for row in s.lines
69+
),
70+
timeout=5,
71+
)
72+
assert highlighted.active_is_alt is True
73+
assert highlighted.lines[0].rstrip() == "> cedar"
74+
assert (highlighted.cursor.row, highlighted.cursor.col) == (0, 7)
75+
assert any(
76+
"Cedar / manifest" in row and not row.startswith("+")
77+
for row in highlighted.lines
78+
)
79+
picker.send_key(key)
80+
assert await asyncio.wait_for(picker.process.wait(), timeout=5) == status
81+
final = picker.terminal.committed
82+
assert final.active_is_alt is False
83+
assert_screen(final, ["primary-before"])
84+
assert (tmp_path / "choice").read_bytes() == output
85+
86+
87+
test_select_or_cancel = pytest.mark.integration(test_select_or_cancel)
88+
89+
_PYTHON_PICKER = r"""
90+
import os, sys, termios, tty
91+
92+
items = [line.rstrip("\r\n") for line in sys.stdin if line.strip()]
93+
tty_fd = os.open("/dev/tty", os.O_RDWR)
94+
old = termios.tcgetattr(tty_fd)
95+
query = ""
96+
selected = 0
97+
98+
def filtered() -> list[str]:
99+
q = query.lower()
100+
return [item for item in items if q in item.lower()]
101+
102+
def draw() -> None:
103+
shown = filtered()
104+
lines = [f"> {query}", f" {len(shown)}/{len(items)}"]
105+
for idx, item in enumerate(shown):
106+
prefix = "+ " if idx == selected else " "
107+
lines.append(f"{prefix}{item}")
108+
frame = (
109+
"\x1b[?2026h\x1b[2J\x1b[H"
110+
+ "\r\n".join(lines)
111+
+ f"\x1b[1;{len(query) + 3}H\x1b[?2026l"
112+
)
113+
os.write(tty_fd, frame.encode("utf-8"))
114+
115+
code = 130
116+
try:
117+
tty.setraw(tty_fd)
118+
os.write(tty_fd, b"\x1b[?1049h\x1b[?2004h")
119+
draw()
120+
while True:
121+
# Handle bare Escape without blocking when no trailing CSI bytes arrive.
122+
ch = os.read(tty_fd, 1)
123+
if ch == b"\r" or ch == b"\n":
124+
shown = filtered()
125+
if shown:
126+
sys.stdout.write(shown[selected] + "\n")
127+
sys.stdout.flush()
128+
code = 0
129+
break
130+
if ch == b"\x03":
131+
code = 130
132+
break
133+
if ch == b"\x1b":
134+
import select
135+
if not select.select([tty_fd], [], [], 0.05)[0]:
136+
code = 130
137+
break
138+
seq = os.read(tty_fd, 2)
139+
if seq == b"[B":
140+
shown = filtered()
141+
if selected + 1 < len(shown):
142+
selected += 1
143+
elif seq == b"[2":
144+
buf = bytearray(b"\x1b[2")
145+
while not buf.endswith(b"\x1b[201~"):
146+
buf.extend(os.read(tty_fd, 1))
147+
query += buf[6:-6].decode("utf-8")
148+
selected = 0
149+
draw()
150+
finally:
151+
os.write(tty_fd, b"\x1b[?2004l\x1b[?1049l")
152+
termios.tcsetattr(tty_fd, termios.TCSADRAIN, old)
153+
os.close(tty_fd)
154+
sys.exit(code)
155+
"""
156+
157+
158+
@pytest.mark.asyncio
159+
@pytest.mark.parametrize(
160+
("key", "status", "output"),
161+
[
162+
("enter", 0, b"Cedar / invoice\n"),
163+
("escape", 130, b""),
164+
("ctrl+c", 130, b""),
165+
],
166+
)
167+
async def test_tty_picker_protocol_select_and_cancel(
168+
tmp_path: pathlib.Path, key: str, status: int, output: bytes
169+
) -> None:
170+
"""Exercise stdin/TTY/stdout separation, ?1049, and ?2026 on every POSIX host."""
171+
(tmp_path / "jobs").write_text(
172+
"Birch / crate\nCedar / manifest\nCedar / invoice\n", encoding="ascii"
173+
)
174+
picker_py = tmp_path / "picker.py"
175+
picker_py.write_text(_PYTHON_PICKER, encoding="utf-8")
176+
command = 'printf \'primary-before\\n\' >/dev/tty; exec "$1" -u "$2" <jobs >choice'
177+
argv = ["/bin/sh", "-c", command, "sh", sys.executable, str(picker_py)]
178+
env = {"HOME": str(tmp_path), "TMPDIR": str(tmp_path), "TERM": "xterm-256color"}
179+
async with open_pty(argv, rows=8, cols=40, cwd=tmp_path, env=env) as picker:
180+
await picker.wait_for("Birch / crate", timeout=5)
181+
picker.paste("cedar")
182+
await picker.wait_for(
183+
lambda s: "Cedar / invoice" in s.text and "Birch / crate" not in s.text,
184+
timeout=5,
185+
)
186+
picker.send_key("down")
187+
highlighted = await picker.wait_for(
188+
lambda s: any(
189+
row.startswith("+ ") and "Cedar / invoice" in row for row in s.lines
190+
),
191+
timeout=5,
192+
)
193+
assert highlighted.active_is_alt is True
194+
assert_screen(
195+
highlighted,
196+
[
197+
"> cedar",
198+
" 2/3",
199+
" Cedar / manifest",
200+
"+ Cedar / invoice",
201+
],
202+
cursor=(0, 7),
203+
)
204+
picker.send_key(key)
205+
assert await asyncio.wait_for(picker.process.wait(), timeout=5) == status
206+
final = picker.terminal.committed
207+
assert final.active_is_alt is False
208+
assert_screen(final, ["primary-before"])
209+
assert (tmp_path / "choice").read_bytes() == output

0 commit comments

Comments
 (0)