From 6a2d032eba14a0654aecca803ce2a3ae8a2b62d8 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sun, 29 Nov 2026 19:18:51 -0600 Subject: [PATCH] tests(vt): Exercise interactive picker lifecycle why: Verify that live VtSessionObserver tracking, mode-aware input, window resizing, and syrupy .ambr snapshots cover an end-to-end TUI lifecycle across tmux 3.3a through master while skipping cleanly on Python 3.11. what: - Add libvt[syrupy]>=0.0.1a4,<0.1 and syrupy to dev and testing dependency groups on Python 3.12+ and allowlist syrupy in ty. - Add test_vt_interactive_picker_lifecycle exercising pre-launch attachment, Down highlight navigation, bracketed PasteEvent filtering, capture_vt vs observe_vt parity (gated on tmux 3.7 for #{bracket_paste_flag}), SIGWINCH resize redraws, and primary-screen restoration on exit. --- pyproject.toml | 8 +- tests/__snapshots__/test_vt.ambr | 43 ++++++ tests/test_vt.py | 231 ++++++++++++++++++++++++++++++- uv.lock | 26 ++++ 4 files changed, 304 insertions(+), 4 deletions(-) create mode 100644 tests/__snapshots__/test_vt.ambr diff --git a/pyproject.toml b/pyproject.toml index 51cff539a7..62e4698213 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -68,6 +68,8 @@ dev = [ "pytest-mock", "pytest-watcher", "pytest-xdist", + "libvt[syrupy]>=0.0.1a4,<0.1; python_version >= '3.12'", + "syrupy>=7.0.3; python_version >= '3.12'", # Coverage "codecov", "coverage", @@ -89,6 +91,8 @@ testing = [ "pytest-rerunfailures", "pytest-mock", "pytest-watcher", + "libvt[syrupy]>=0.0.1a4,<0.1; python_version >= '3.12'", + "syrupy>=7.0.3; python_version >= '3.12'", ] coverage =[ "codecov", @@ -148,8 +152,8 @@ ty = false python-version = "3.11" [tool.ty.analysis] -# libvt is an optional Python 3.12+ extra (`libtmux[vt]`), absent in 3.11 and core environments -allowed-unresolved-imports = ["libvt", "libvt.**"] +# libvt and syrupy are Python 3.12+ optional/dev dependencies, absent in 3.11 and core environments +allowed-unresolved-imports = ["libvt", "libvt.**", "syrupy", "syrupy.**"] [tool.ty.src] include = [ diff --git a/tests/__snapshots__/test_vt.ambr b/tests/__snapshots__/test_vt.ambr new file mode 100644 index 0000000000..658d167868 --- /dev/null +++ b/tests/__snapshots__/test_vt.ambr @@ -0,0 +1,43 @@ +# serializer version: 1 +# name: test_vt_interactive_picker_lifecycle[picker_filtered_resized] + size=34x6 cursor=(5,33,vis=False) alt=True modes=[BRACKETED_PASTE] + ┌──────────────────────────────────┐ + │┌────────────────────────────────┐│ + ││ Filter: work PID= ││ + ││ > worker ││ + ││ ││ + ││ ││ + │└────────────────────────────────┘│ + └──────────────────────────────────┘ + styles: + r1[2..9]: bold fg=cyan + r2[2..32]: bold reverse +# --- +# name: test_vt_interactive_picker_lifecycle[picker_initial] + size=28x6 cursor=(5,27,vis=False) alt=True modes=[BRACKETED_PASTE] + ┌────────────────────────────┐ + │┌──────────────────────────┐│ + ││ Filter: PID= ││ + ││ > api ││ + ││ worker ││ + ││ scheduler ││ + │└──────────────────────────┘│ + └────────────────────────────┘ + styles: + r1[2..9]: bold fg=cyan + r2[2..26]: bold reverse +# --- +# name: test_vt_interactive_picker_lifecycle[picker_navigated] + size=28x6 cursor=(5,27,vis=False) alt=True modes=[BRACKETED_PASTE] + ┌────────────────────────────┐ + │┌──────────────────────────┐│ + ││ Filter: PID= ││ + ││ api ││ + ││ > worker ││ + ││ scheduler ││ + │└──────────────────────────┘│ + └────────────────────────────┘ + styles: + r1[2..9]: bold fg=cyan + r3[2..26]: bold reverse +# --- diff --git a/tests/test_vt.py b/tests/test_vt.py index 50c6e6b589..9bbfe07c48 100644 --- a/tests/test_vt.py +++ b/tests/test_vt.py @@ -3,6 +3,7 @@ from __future__ import annotations import asyncio +import importlib.util import logging import shlex import subprocess @@ -12,6 +13,7 @@ import pytest from libtmux import exc +from libtmux.common import has_gte_version from libtmux.test.retry import retry_until from libtmux.vt import ( VtSessionObserver, @@ -21,6 +23,8 @@ ) if t.TYPE_CHECKING: + from syrupy.assertion import SnapshotAssertion + from libtmux.pane import Pane from libtmux.pytest_plugin import VtObserverFactory from libtmux.server import Server @@ -244,8 +248,6 @@ def test_send_vt_input_mode_aware_keys_paste_and_mouse( ) from libvt.modes import Mode - from libtmux.common import has_gte_version - reader_script = ( "import os, sys, tty; " "fd = sys.stdin.fileno(); " @@ -474,3 +476,228 @@ async def _exercise() -> None: await w2 asyncio.run(_exercise()) + + +_HAS_VT_SYRUPY = ( + importlib.util.find_spec("libvt") is not None + and importlib.util.find_spec("syrupy") is not None +) + + +_PICKER_APP_SCRIPT = """ +import os, selectors, signal, sys, termios, tty + +fd = sys.stdin.fileno() +old_attrs = termios.tcgetattr(fd) +tty.setraw(fd, termios.TCSANOW) +sys.stdout.buffer.write(b"BOOT_GATE") +sys.stdout.buffer.flush() +os.read(fd, 1) + +items = ["api", "worker", "scheduler"] +query = "" +sel = 0 +pid = os.getpid() + +r_sig, w_sig = os.pipe() +os.set_blocking(r_sig, False) +os.set_blocking(w_sig, False) +signal.set_wakeup_fd(w_sig) +signal.signal(signal.SIGWINCH, lambda *_: None) + +def current_items(): + return [it for it in items if query.lower() in it.lower()] + +def draw(): + cols, _ = os.get_terminal_size(fd) + inner = max(10, cols - 4) + filtered = current_items() + left_vis = f"Filter: {query}" + right_vis = f"PID={pid}" + gap = max(1, inner - len(left_vis) - len(right_vis)) + lines = [ + "┌" + "─" * (cols - 2) + "┐", + f"│ \\x1b[1;36mFilter:\\x1b[0m {query}{' ' * gap}{right_vis} │", + ] + for idx in range(3): + if idx < len(filtered): + marker = ">" if idx == sel else " " + cell = f"{marker} {filtered[idx]:<{inner - 2}}"[:inner] + if idx == sel: + lines.append(f"│ \\x1b[1;7m{cell}\\x1b[0m │") + else: + lines.append(f"│ {cell} │") + else: + lines.append(f"│ {' ' * inner} │") + lines.append("└" + "─" * (cols - 2) + "┘") + frame = "\\x1b[?2026h\\x1b[2J\\x1b[H" + "\\r\\n".join(lines) + "\\x1b[?2026l" + sys.stdout.buffer.write(frame.encode("utf-8")) + sys.stdout.buffer.flush() + +sys.stdout.buffer.write(b"\\x1b[?1049h\\x1b[?2004h\\x1b[?25l") +sys.stdout.buffer.flush() +draw() + +mux = selectors.DefaultSelector() +mux.register(fd, selectors.EVENT_READ) +mux.register(r_sig, selectors.EVENT_READ) +buf = bytearray() +running = True +while running: + for key, _ in mux.select(): + if key.fd == r_sig: + try: + os.read(r_sig, 64) + except BlockingIOError: + pass + draw() + continue + chunk = os.read(fd, 128) + if not chunk: + running = False + break + buf.extend(chunk) + while buf: + if buf.startswith(b"\\x1b[200~"): + end = buf.find(b"\\x1b[201~") + if end == -1: + break + pasted = bytes(buf[6:end]).decode("utf-8", errors="replace") + del buf[: end + 6] + query += pasted + filtered = current_items() + sel = min(sel, max(0, len(filtered) - 1)) + draw() + elif buf.startswith((b"\\x1b[", b"\\x1bO")): + if len(buf) < 3: + break + seq = bytes(buf[:3]) + del buf[:3] + filtered = current_items() + if filtered and seq in (b"\\x1b[B", b"\\x1bOB"): + sel = (sel + 1) % len(filtered) + draw() + elif filtered and seq in (b"\\x1b[A", b"\\x1bOA"): + sel = (sel - 1) % len(filtered) + draw() + elif buf[0] in (10, 13): + del buf[:1] + filtered = current_items() + chosen = filtered[sel] if filtered else "none" + termios.tcsetattr(fd, termios.TCSADRAIN, old_attrs) + out = f"\\x1b[?2004l\\x1b[?25h\\x1b[?1049lselected={chosen}\\r\\n" + sys.stdout.buffer.write(out.encode("utf-8")) + sys.stdout.buffer.flush() + os.read(fd, 1) + running = False + break + else: + ch = chr(buf[0]) + del buf[:1] + if ch.isprintable(): + query += ch + filtered = current_items() + sel = min(sel, max(0, len(filtered) - 1)) + draw() +""" + + +@pytest.mark.skipif( + not _HAS_VT_SYRUPY, + reason="requires libvt[syrupy] on Python >= 3.12", +) +def test_vt_interactive_picker_lifecycle( + session: Session, + vt_observer: VtObserverFactory, + vt_snapshot: SnapshotAssertion, +) -> None: + """Interactive TUI lifecycle: attach, navigate, paste, resize, and exit.""" + from libvt.input import KeyEvent, PasteEvent + from libvt.modes import Mode + from libvt.testing import serialize_vt_snapshot, vt_screen + + scrubs = [(r"PID=\d+", "PID=")] + win = session.new_window( + window_name="vt-picker", + window_shell=( + f"{shlex.quote(sys.executable)} -u -c {shlex.quote(_PICKER_APP_SCRIPT)}" + ), + ) + pane = win.active_pane + assert pane is not None + retry_until(lambda: "BOOT_GATE" in "\n".join(pane.capture_pane())) + win.resize(height=6, width=28) + + async def _exercise() -> None: + async with vt_observer(history_lines=0) as observer: + handle = await observer.watch_pane(pane) + pre_launch = handle.snapshot() + assert pre_launch.active_is_alt is False + + await handle.send_input("g") + start_snap = await handle.wait_until( + lambda snap: snap.active_is_alt and "scheduler" in snap.text + ) + assert start_snap.active_is_alt is True + assert start_snap.cursor.visible is False + assert start_snap[2, 2].style.reverse is True + assert start_snap[3, 2].style.reverse is False + assert vt_screen(start_snap, scrubbers=scrubs) == vt_snapshot( + name="picker_initial" + ) + + await handle.send_input(KeyEvent("down")) + nav_snap = await handle.wait_until(lambda snap: snap[3, 2].style.reverse) + assert nav_snap[2, 2].style.reverse is False + assert nav_snap[3, 2].style.reverse is True + assert vt_screen(nav_snap, scrubbers=scrubs) == vt_snapshot( + name="picker_navigated" + ) + + await handle.send_input(PasteEvent("work")) + filtered_snap = await handle.wait_until( + lambda snap: ( + "Filter: work" in snap.text and "scheduler" not in snap.text + ) + ) + assert filtered_snap[2, 2].style.reverse is True + assert Mode.BRACKETED_PASTE in filtered_snap.modes + observed_serialized = serialize_vt_snapshot( + filtered_snap, + scrubbers=scrubs, + ) + captured_serialized = serialize_vt_snapshot(pane, scrubbers=scrubs) + if has_gte_version("3.7", tmux_bin=session.server.tmux_bin): + assert observed_serialized == captured_serialized + else: + # tmux < 3.7 lacks #{bracket_paste_flag}; live observation retains + # ?2004h while capture_vt matches geometry, cursor, cells, and styles. + assert ( + observed_serialized.replace( + "modes=[BRACKETED_PASTE]", + "modes=[]", + 1, + ) + == captured_serialized + ) + + win.resize(height=6, width=34) + resized_snap = await handle.wait_until( + lambda snap: snap.cols == 34 and snap[0, 33].text == "┐" + ) + assert resized_snap.cols == 34 + assert resized_snap[2, 2].style.reverse is True + assert vt_screen(resized_snap, scrubbers=scrubs) == vt_snapshot( + name="picker_filtered_resized" + ) + + await handle.send_input(KeyEvent("enter")) + finish_snap = await handle.wait_until( + lambda snap: not snap.active_is_alt and "selected=worker" in snap.text + ) + assert finish_snap.active_is_alt is False + assert finish_snap.cursor.visible is True + assert Mode.BRACKETED_PASTE not in finish_snap.modes + assert "selected=worker" in finish_snap.text + + asyncio.run(_exercise()) diff --git a/uv.lock b/uv.lock index a6d7ecde9a..6a12da30df 100644 --- a/uv.lock +++ b/uv.lock @@ -545,6 +545,7 @@ dev = [ { name = "coverage" }, { name = "gp-libs" }, { name = "gp-sphinx" }, + { name = "libvt", extra = ["syrupy"], marker = "python_full_version >= '3.12'" }, { name = "pytest" }, { name = "pytest-cov" }, { name = "pytest-mock" }, @@ -555,6 +556,7 @@ dev = [ { name = "sphinx-autobuild" }, { name = "sphinx-autodoc-api-style" }, { name = "sphinx-autodoc-pytest-fixtures" }, + { name = "syrupy", marker = "python_full_version >= '3.12'" }, { name = "ty" }, { name = "types-docutils" }, ] @@ -570,10 +572,12 @@ lint = [ ] testing = [ { name = "gp-libs" }, + { name = "libvt", extra = ["syrupy"], marker = "python_full_version >= '3.12'" }, { name = "pytest" }, { name = "pytest-mock" }, { name = "pytest-rerunfailures" }, { name = "pytest-watcher" }, + { name = "syrupy", marker = "python_full_version >= '3.12'" }, ] [package.metadata] @@ -591,6 +595,7 @@ dev = [ { name = "coverage" }, { name = "gp-libs", specifier = ">=0.0.19" }, { name = "gp-sphinx", specifier = "==0.1.0a39" }, + { name = "libvt", extras = ["syrupy"], marker = "python_full_version >= '3.12'", specifier = ">=0.0.1a4,<0.1" }, { name = "pytest" }, { name = "pytest-cov" }, { name = "pytest-mock" }, @@ -601,6 +606,7 @@ dev = [ { name = "sphinx-autobuild" }, { name = "sphinx-autodoc-api-style", specifier = "==0.1.0a39" }, { name = "sphinx-autodoc-pytest-fixtures", specifier = "==0.1.0a39" }, + { name = "syrupy", marker = "python_full_version >= '3.12'", specifier = ">=7.0.3" }, { name = "ty", specifier = "==0.0.113" }, { name = "types-docutils" }, ] @@ -616,10 +622,12 @@ lint = [ ] testing = [ { name = "gp-libs", specifier = ">=0.0.19" }, + { name = "libvt", extras = ["syrupy"], marker = "python_full_version >= '3.12'", specifier = ">=0.0.1a4,<0.1" }, { name = "pytest" }, { name = "pytest-mock" }, { name = "pytest-rerunfailures" }, { name = "pytest-watcher" }, + { name = "syrupy", marker = "python_full_version >= '3.12'", specifier = ">=7.0.3" }, ] [[package]] @@ -631,6 +639,12 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/0f/3e/94566d78ca6923f4d8a8de31b64bfff9c9bc716c51e6a1ebd1f496d883bb/libvt-0.0.1a4-py3-none-any.whl", hash = "sha256:ede0a8484b3d617d8dd75f22ab3e0f479d1086ae5beebd63c68c77223f42ce90", size = 217260, upload-time = "2026-11-29T22:17:38.109Z" }, ] +[package.optional-dependencies] +syrupy = [ + { name = "pytest" }, + { name = "syrupy" }, +] + [[package]] name = "linkify-it-py" version = "2.2.0" @@ -1393,6 +1407,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/88/2e/947cfe02def9371c07cd5bf5b6b61c829e9aecb9904db02a66cfafbc1eec/starlette-1.10.0-py3-none-any.whl", hash = "sha256:478c0ab3b4ced6e82719849c118fa406f0278a3499c1a898cd15cd31bdc38ce4", size = 80571, upload-time = "2026-10-24T15:04:10.371Z" }, ] +[[package]] +name = "syrupy" +version = "7.0.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pytest" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/99/01/37beb5207de6b94d65feadb611b8b52c535d5de3f090e6775c0da5324072/syrupy-7.0.3.tar.gz", hash = "sha256:91f8b02111c3094a9a6a7eb80b6807f35a298f9d3c3d3cbf27d4e2c4c3ff8b1e", size = 123374, upload-time = "2026-11-21T16:07:03.001Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/98/e0/83f27009f6c99a6b61d99c2d311cab080f43917bdad5d0bf974edf754b70/syrupy-7.0.3-py3-none-any.whl", hash = "sha256:020b4688b46887accb7365fdef7983e6a157f1e6984d1e00571d3d40cfebce51", size = 69112, upload-time = "2026-11-21T16:07:01.582Z" }, +] + [[package]] name = "ty" version = "0.0.113"