|
| 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