Testing Terminal Programs

libvt’s testing stack builds on top of Terminal and immutable Snapshots (Snapshot / committed), organized into three independent systems so test suites only install what they use:

  1. libvt.testing ships in core libvt with zero third-party dependencies (unittest, plain assert, inline-snapshot, pytest-regressions, or custom golden files).

  2. libvt.pytest_plugin (libvt[pytest]) provides import-light vt_* fixtures (vt_terminal, vt_factory, vt_recorder, vt_parser, vt_pty) with no snapshot-tool coupling.

  3. libvt.contrib.syrupy (libvt[syrupy]) adapts libvt.testing into VtSnapshotExtension for syrupy and registers vt_snapshot only when syrupy is active.


Testing utilities (libvt.testing)

Core libvt.testing requires neither pytest nor syrupy.

Inline assertions and FlightRecorder diagnostics

When expected text fits in a few lines, check screens inline with assert_screen() or assert_screen_box(). Attaching a FlightRecorder appends a disassembled trace of recent VT sequences to ScreenAssertionError when an assertion fails:

>>> from libvt.exc import ScreenAssertionError
>>> from libvt.terminal import FlightRecorder, Terminal
>>> from libvt.testing import assert_screen_box
>>> rec = FlightRecorder()
>>> term = Terminal(rows=2, cols=10, recorder=rec)
>>> term.feed(b"\x1b[1;31mERR\x1b[0m: disk\r\nretry?")
>>> assert_screen_box(
...     term,
...     """
...     ┌──────────┐
...     │ERR: disk │
...     │retry?    │
...     └──────────┘
...     """,
...     cursor=(1, 6),
... )
>>> try:
...     assert_screen_box(term, "┌──────────┐\n│OK        │\n│retry?    │\n└──────────┘")
... except ScreenAssertionError as err:
...     "Flight Recorder:" in str(err)
True

Boxed VT + SGR serialization

Raw ANSI strings inside golden files are hard to review and break character diff highlighters when ESC bytes split across color spans. serialize_vt_snapshot() serializes terminals, snapshots, Screen grids, region() slices, TmuxCaptureResult bundles, and duck-typed pane objects into three plain-text sections:

  1. A canonical metadata header (size, cursor, alt, non-default modes).

  2. A column-exact Unicode ┌──┐ viewport box read from committed.

  3. Run-length styles: spans recording SGR attributes, 16/256/RGB colors, underline colors, and OSC 8 hyperlinks.

>>> import libvt
>>> from libvt.testing import serialize_vt_snapshot
>>> term = libvt.Terminal(rows=2, cols=20)
>>> term.feed(
...     b"\x1b]8;;https://example.com\x07\x1b[4;34mdocs\x1b[0m\x1b]8;;\x07  "
...     b"\x1b[38;2;255;140;0mWARN\x1b[0m"
... )
>>> print(serialize_vt_snapshot(term))
size=20x2 cursor=(0,10,vis=True) alt=False modes=[]
┌────────────────────┐
│docs  WARN          │
│                    │
└────────────────────┘
styles:
  r0[0..4]: underline fg=blue link=https://example.com
  r0[6..10]: fg=#ff8c00

Scrubbing dynamic values without breaking box borders

Naive string replacement shifts right-hand │ borders whenever a PID, port, or duration changes character length. vt_screen() adapts scrubbing to the active screen regime:

  • Fixed-row 2D screens (alt=True or !DECAWM) absorb width deltas between a matched token and its replacement into adjacent whitespace slack inside the same │-delimited cell before shifting right-hand dividers.

  • Primary autowrap streams (alt=False and DECAWM) coalesce contiguous soft-wrapped row chains before regex matching and re-wrap to terminal width without pulling cleared scrollback (CSI 2 J / Ctrl-L) back onscreen.

>>> import libvt
>>> from libvt.testing import serialize_vt_snapshot, vt_screen
>>> tui = libvt.Terminal(rows=3, cols=24)
>>> tui.feed(
...     "\x1b[?1049h\x1b[H"
...     "┌──────────────────────┐\r\n"
...     "│ worker  pid=9     OK │\r\n"
...     "└──────────────────────┘".encode()
... )
>>> tui_wide_pid = libvt.Terminal(rows=3, cols=24)
>>> tui_wide_pid.feed(
...     "\x1b[?1049h\x1b[H"
...     "┌──────────────────────┐\r\n"
...     "│ worker  pid=48291 OK │\r\n"
...     "└──────────────────────┘".encode()
... )
>>> scrub = [(r"pid=\d+", "pid=<PID>")]
>>> serialize_vt_snapshot(vt_screen(tui, scrubbers=scrub)) == serialize_vt_snapshot(
...     vt_screen(tui_wide_pid, scrubbers=scrub)
... )
True

Region slices and step-by-step TUI deltas

Pass region=(start_row, end_row, start_col, end_col) to serialize one toolbar or modal, or pass diff=previous_state to record only the header, row, and style transitions between two steps of an interactive session:

>>> import libvt
>>> from libvt.testing import serialize_vt_snapshot, vt_screen
>>> step1 = libvt.Terminal(rows=2, cols=16)
>>> step1.feed(b"[x] api   [ ] db\r\n1 selected")
>>> snap1 = step1.committed
>>> step1.feed(b"\x1b[1;11H[x]\r\n2 selected")
>>> print(serialize_vt_snapshot(vt_screen(step1, diff=snap1)))
row 0 cols 11..12: ' ' -> 'x'
row 1 cols 0..1: '1' -> '2'
  size=16x2 cursor=(1,10,vis=True) alt=False modes=[]
  ┌────────────────┐
- │[x] api   [ ] db│
+ │[x] api   [x] db│
  │           ^    │
- │1 selected      │
+ │2 selected      │
  │^               │
  └────────────────┘

Compact failure diffs

format_vt_diff_lines() leads with header:, row R cols C0..C1:, and styles: summaries ahead of column-aligned ^ carets (or ANSI-styled lines when callbacks are supplied):

>>> import libvt
>>> from libvt.testing import format_vt_diff_lines, serialize_vt_snapshot
>>> expected = libvt.Terminal(rows=1, cols=12)
>>> expected.feed(b"\x1b[32mBUILD PASS\x1b[0m")
>>> received = libvt.Terminal(rows=1, cols=12)
>>> received.feed(b"\x1b[31mBUILD FAIL\x1b[0m")
>>> diff = format_vt_diff_lines(
...     serialize_vt_snapshot(received),
...     serialize_vt_snapshot(expected),
... )
>>> print("\n".join(diff[:3]))
row 0 cols 6..10: 'PASS' -> 'FAIL'
styles: ['  r0[0..10]: fg=green'] -> ['  r0[0..10]: fg=red']
  size=12x1 cursor=(0,10,vis=True) alt=False modes=[]

Pytest plugin (libvt.pytest_plugin)

Install libvt[pytest] when running under pytest:

$ uv add --dev "libvt[pytest]>=0.0.1a5,<0.1"

libvt.pytest_plugin registers vt_terminal (24x80 terminal pre-wired to vt_recorder), vt_factory (for custom (rows, cols) or profiles), vt_parser, and POSIX vt_pty, with no dependency on syrupy or any other snapshot tool:

>>> from libvt.pytest_plugin import TerminalFactory
>>> from libvt.testing import assert_screen
>>> def test_dialog(vt_factory: TerminalFactory) -> None:
...     term = vt_factory(rows=2, cols=12)
...     term.feed(b"Save? [y/n]")
...     assert_screen(term, "Save? [y/n]", cursor=(0, 11))
>>> test_dialog(vt_factory)
>>> from libvt.parser import Parser
>>> def test_parser_actions(vt_parser: Parser) -> None:
...     actions = vt_parser.feed(b"\x1b[1mok")
...     assert [type(a).__name__ for a in actions] == ["CsiDispatch", "Print"]
>>> test_parser_actions(vt_parser)

Syrupy .ambr adapter (libvt.contrib.syrupy)

Install the optional syrupy extra when storing golden snapshots in .ambr files managed by pytest --snapshot-update:

$ uv add --dev "libvt[syrupy]>=0.0.1a5,<0.1"

When syrupy is active in pytest, libvt.contrib.syrupy’s conditional libvt_syrupy hook automatically registers vt_snapshot (while leaving libvt.pytest_plugin syrupy-free and omitting vt_snapshot from pytest --fixtures when syrupy is uninstalled or disabled via -p no:syrupy):

>>> import libvt
>>> from libvt.testing import vt_screen
>>> def test_worker_row(vt_snapshot):
...     term = libvt.Terminal(rows=2, cols=18)
...     term.feed(b"\x1b[1;32mREADY\x1b[0m  pid=48210\r\nok")
...     assert vt_screen(term, scrubbers=[(r"pid=\d+", "pid=<PID>")]) == vt_snapshot
>>> class _CheckAmbr:
...     def __eq__(self, other: object) -> bool:
...         out = vt_snapshot.extension.serialize(other)
...         return "│READY  pid=<PID>  │" in out and "bold fg=green" in out
>>> test_worker_row(_CheckAmbr())

Project-wide .ambr scrubbers

To share scrubbers across every .ambr test in a repository, build a memoized subclass with VtSnapshotExtension.configure and bind it with snapshot.use_extension(...) inside a conftest.py fixture:

>>> import libvt
>>> from libvt.contrib.syrupy import VtSnapshotExtension
>>> AppVtSnapshot = VtSnapshotExtension.configure(
...     scrubbers=[
...         (r"pid=\d+", "pid=<PID>"),
...         (r"\b\d+\.\d+s\b", "<DUR>"),
...     ],
... )
>>> term = libvt.Terminal(rows=1, cols=26)
>>> term.feed(b"pid=812 done in 0.42s")
>>> print(AppVtSnapshot().serialize(term))
size=26x1 cursor=(0,23,vis=True) alt=False modes=[]
┌──────────────────────────┐
│pid=<PID> done in <DUR>   │
└──────────────────────────┘