(topics-testing)=

# Testing Terminal Programs

`libvt`'s testing stack builds on top of {class}`~libvt.terminal.Terminal` and
immutable {doc}`snapshots` ({class}`~libvt.terminal.Snapshot` /
{attr}`~libvt.terminal.Terminal.committed`), organized into three independent
systems so test suites only install what they use:

1. {mod}`libvt.testing` ships in core `libvt` with zero third-party
   dependencies (`unittest`, plain `assert`, `inline-snapshot`,
   `pytest-regressions`, or custom golden files).
2. {mod}`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. {mod}`libvt.contrib.syrupy` (`libvt[syrupy]`) adapts {mod}`libvt.testing`
   into {class}`~libvt.contrib.syrupy.VtSnapshotExtension` for
   [syrupy](https://syrupy-project.github.io/syrupy/) and registers
   {fixture}`vt_snapshot` only when `syrupy` is active.

---

## Testing utilities (`libvt.testing`)

Core {mod}`libvt.testing` requires neither `pytest` nor `syrupy`.

### Inline assertions and `FlightRecorder` diagnostics

When expected text fits in a few lines, check screens inline with
{func}`~libvt.testing.assert_screen` or
{func}`~libvt.testing.assert_screen_box`. Attaching a
{class}`~libvt.terminal.FlightRecorder` appends a disassembled trace of recent
VT sequences to {exc}`~libvt.exc.ScreenAssertionError` when an assertion fails:

```python
>>> 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.
{func}`~libvt.testing.serialize_vt_snapshot` serializes terminals, snapshots,
{class}`~libvt.screen.Screen` grids, {meth}`~libvt.screen.Screen.region`
slices, {class}`~libvt.contrib.tmux.capture.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
   {attr}`~libvt.terminal.Terminal.committed`.
3. Run-length `styles:` spans recording `SGR` attributes, 16/256/RGB colors,
   underline colors, and `OSC 8` hyperlinks.

```python
>>> 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. {func}`~libvt.testing.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.

```python
>>> 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:

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

{func}`~libvt.testing.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):

```python
>>> 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](https://docs.pytest.org/en/stable/):

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

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

```python
>>> 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)  # doctest: +HIDE
```

```python
>>> 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)  # doctest: +HIDE
```

---

## Syrupy `.ambr` adapter (`libvt.contrib.syrupy`)

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

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

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

```python
>>> 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:  # doctest: +HIDE
...     def __eq__(self, other: object) -> bool:  # doctest: +HIDE
...         out = vt_snapshot.extension.serialize(other)  # doctest: +HIDE
...         return "│READY  pid=<PID>  │" in out and "bold fg=green" in out  # doctest: +HIDE
>>> test_worker_row(_CheckAmbr())  # doctest: +HIDE
```

### Project-wide `.ambr` scrubbers

To share scrubbers across every `.ambr` test in a repository, build a memoized
subclass with
{meth}`VtSnapshotExtension.configure <libvt.contrib.syrupy.VtSnapshotExtension.configure>`
and bind it with `snapshot.use_extension(...)` inside a `conftest.py` fixture:

```python
>>> 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>   │
└──────────────────────────┘
```
