Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,10 @@ what was asked for.
| `src/libvt/_ucd.py`, `_grid.py`, `screen.py`, `terminal.py` | Unicode 17 width/clustering tables, packed viewport & RLE scrollback rows, `Screen` / `ScreenSet`, `Terminal`, `Snapshot`, and `Formatter` |
| `src/libvt/status.py`, `events.py`, `input.py`, `codec.py` | Rex `OSC 7501` program status store, open `Event` hierarchy, mode-aware input encoders, and cold-path VT sequence explainer |
| `src/libvt/graphics.py`, `contrib/tmux/` | Zero-dependency `SIXEL` / Kitty `APC G` placement tracker and decoupled `tmux` `profile` / `capture` / `control` modules |
| `src/libvt/aio.py`, `__main__.py` | `AsyncTerminalStream`, POSIX `open_pty()`, and `python -m libvt` CLI (`explain`, `render`, `strip`) |
| `src/libvt/testing.py`, `pytest_plugin.py`, `exc.py` | Boxed `assert_screen`, `FlightRecorder` diagnostics, `vt_*` pytest fixtures, and exceptions |
| `src/libvt/aio.py`, `__main__.py`, `exc.py` | `AsyncTerminalStream`, POSIX `open_pty()`, `python -m libvt` CLI (`explain`, `render`, `strip`), and exceptions |
| `src/libvt/testing.py` | Zero-dependency `assert_screen`, `assert_screen_box`, `FlightRecorder` diagnostics, and boxed VT + `SGR` `vt_screen` / `serialize_vt_snapshot` / `format_vt_diff_lines` utilities |
| `src/libvt/pytest_plugin.py` | Import-light `pytest11` plugin (`libvt[pytest]`): `vt_terminal`, `vt_factory`, `vt_recorder`, `vt_parser`, and `vt_pty` |
| `src/libvt/contrib/syrupy.py` | Optional `syrupy` `.ambr` adapter (`libvt[syrupy]`): `VtSnapshotExtension` and conditional `vt_snapshot` `pytest11` hook |
| `tests/` | Functional, property-fuzz, PTY, CLI, and fixture tests organized by module under test |
| `docs/` | Sphinx/MyST site: `topics/` (concepts), `api/` (autodoc), `project/` (contributing, releasing, ADRs `0001`–`0010`) |
| `scripts/` | Unicode table generator (`generate_ucd.py`) and VT throughput benchmarks (`bench_vt.py`, `benchmark.py`) |
Expand Down
38 changes: 26 additions & 12 deletions CHANGES
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,32 @@ _Notes on the upcoming release will go here._

### What's new

#### `libvt.contrib.syrupy`: Boxed VT and `SGR` snapshots (#66)

Install `libvt[syrupy]` (or `libvt[pytest]` for `pytest`-only helpers) while
keeping core `libvt` runtime `dependencies` empty.
{class}`~libvt.contrib.syrupy.VtSnapshotExtension`,
{func}`~libvt.contrib.syrupy.serialize_vt_snapshot`, and
{func}`~libvt.contrib.syrupy.vt_screen` serialize terminal screens, snapshots,
`tmux` captures, and duck-typed pane objects into escape-free Unicode viewport
boxes with run-length `styles:` spans, regime-aware regex scrubbing, and TTY or
ASCII-caret failure diffs via
{func}`~libvt.contrib.syrupy.format_vt_diff_lines`. See
{ref}`topics-testing-and-snapshots` for details. (#66)
#### `libvt.testing`: Boxed VT and `SGR` snapshot serialization (#66, #67)

{func}`~libvt.testing.serialize_vt_snapshot`,
{func}`~libvt.testing.vt_screen` ({class}`~libvt.testing.VtScreenView`), and
{func}`~libvt.testing.format_vt_diff_lines` serialize terminal screens,
snapshots, region slices, `tmux` captures, and duck-typed pane objects into
escape-free Unicode viewport boxes with run-length `styles:` spans,
regime-aware regex scrubbing, and TTY or ASCII-caret failure diffs with no
runtime or snapshot-tool dependencies. See {ref}`topics-snapshots` and
{ref}`topics-testing` for details.

#### `libvt.pytest_plugin`: Fixture documentation and `libvt[pytest]` extra (#66, #67)

Install `libvt[pytest]` for {mod}`libvt.pytest_plugin`'s {fixture}`vt_terminal`,
{fixture}`vt_factory`, {fixture}`vt_recorder`, {fixture}`vt_parser`, and
{fixture}`vt_pty` fixtures while keeping core `libvt` runtime `dependencies`
empty and {mod}`libvt.pytest_plugin` free of third-party snapshot-tool
dependencies.

#### `libvt.contrib.syrupy`: Optional `.ambr` adapter and conditional `vt_snapshot` fixture (#66, #67)

Install `libvt[syrupy]` for `.ambr` golden-file testing.
{class}`~libvt.contrib.syrupy.VtSnapshotExtension` adapts {mod}`libvt.testing`
to `syrupy`, and `libvt_syrupy` registers {fixture}`vt_snapshot` automatically
when `syrupy` is active in `pytest` while omitting it from `pytest --fixtures`
when `syrupy` is uninstalled or disabled (`-p no:syrupy`).

### Development

Expand Down
77 changes: 65 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,12 @@ Install with `pip`:
$ pip install "libvt>=0.0.1a3,<0.1"
```

Optional test extras add `vt_*` [pytest fixtures][pytest_plugin] (`libvt[pytest]`)
or boxed `.ambr` and `SGR` snapshot testing with [syrupy][contrib_syrupy]
(`libvt[syrupy]`):
Optional extras install the `pytest` fixture plugin (`libvt[pytest]`) or the
`syrupy` `.ambr` snapshot adapter (`libvt[syrupy]`):

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

```console
$ uv add --dev "libvt[syrupy]>=0.0.1a3,<0.1"
Expand Down Expand Up @@ -66,6 +69,7 @@ checks visible text, wide-character column alignment, and cursor coordinates
inline without extra dependencies or snapshot files:

```python
>>> import libvt
>>> from libvt.testing import assert_screen_box
>>> t = libvt.Terminal(rows=2, cols=8)
>>> t.feed("日本ok\r\ndone".encode())
Expand All @@ -81,16 +85,17 @@ inline without extra dependencies or snapshot files:
... )
```

### Snapshot multi-row TUIs and `SGR` styles with `syrupy`
### Serialize and scrub multi-row TUIs (`libvt.testing`)

Reach for [`libvt.contrib.syrupy`][contrib_syrupy] (`libvt[syrupy]`) when a TUI,
progress panel, or `tmux` layout spans many styled rows or dynamic IDs.
[`vt_screen()`][vt_screen] and [`serialize_vt_snapshot()`][serialize_vt_snapshot]
emit escape-free `.ambr` boxes with run-length `styles:` spans while absorbing
regex scrubber width changes inside `│` borders:
When a TUI, progress panel, or `tmux` layout spans many styled rows or dynamic
IDs, [`vt_screen()`][vt_screen] and [`serialize_vt_snapshot()`][serialize_vt_snapshot]
in `libvt.testing` emit escape-free boxes with run-length `styles:` spans while
absorbing regex scrubber width changes inside `│` borders with no extra
dependencies (`unittest`, `assert`, `inline-snapshot`, or `pytest-regressions`):

```python
>>> from libvt.contrib.syrupy import serialize_vt_snapshot, vt_screen
>>> import libvt
>>> from libvt.testing import serialize_vt_snapshot, vt_screen
>>> ui = libvt.Terminal(rows=3, cols=22)
>>> ui.feed(
... b"\x1b[?1049h\x1b[H"
Expand All @@ -117,13 +122,60 @@ styles:
r1[2..7]: bold fg=green
```

### Test with `pytest` fixtures (`libvt[pytest]`)

[`libvt.pytest_plugin`][pytest_plugin] (`libvt[pytest]`) provides `vt_terminal`
(wired to a 4 KiB `FlightRecorder`), `vt_factory`, `vt_recorder`, `vt_parser`,
and POSIX `vt_pty` fixtures with no snapshot-tool dependencies:

```python
>>> import libvt
>>> from libvt.pytest_plugin import TerminalFactory
>>> from libvt.testing import assert_screen_box
>>> def test_prompt(vt_factory: TerminalFactory) -> None:
... term = vt_factory(rows=2, cols=10)
... term.feed(b"\x1b[1;32mOK\x1b[0m\r\nready> ")
... assert_screen_box(
... term,
... """
... ┌──────────┐
... │OK │
... │ready> │
... └──────────┘
... """,
... cursor=(1, 7),
... )
>>> test_prompt(libvt.Terminal)
```

### Persist `.ambr` snapshots (`libvt[syrupy]`)

[`libvt.contrib.syrupy`][contrib_syrupy] (`libvt[syrupy]`) adapts
`libvt.testing` into `VtSnapshotExtension` for `syrupy` `.ambr` golden files and
conditionally registers [`vt_snapshot`][vt_snapshot] when `syrupy` is active:

```python
>>> import libvt
>>> from libvt.contrib.syrupy import VtSnapshotExtension
>>> term = libvt.Terminal(rows=1, cols=12)
>>> term.feed(b"\x1b[1;32mPASS\x1b[0m")
>>> print(VtSnapshotExtension().serialize(term))
size=12x1 cursor=(0,4,vis=True) alt=False modes=[]
┌────────────┐
│PASS │
└────────────┘
styles:
r0[0..4]: bold fg=green
```

### Render, strip, and explain VT byte streams

[`render()`][render] returns screen text after processing terminal output.
[`strip()`][strip] removes control sequences without applying cursor movements.
[`explain()`][explain] identifies the sequences in a byte stream:

```python
>>> import libvt
>>> from libvt.codec import explain
>>> libvt.render(b"\x1b[1;32mready\x1b[0m\r\nitem 1", rows=4, cols=20)
'ready\nitem 1'
Expand Down Expand Up @@ -160,8 +212,9 @@ MIT License. See [LICENSE](LICENSE).
[assert_screen_box]: https://libvt.git-pull.com/api/testing/#libvt.testing.assert_screen_box
[contrib_syrupy]: https://libvt.git-pull.com/api/contrib_syrupy/
[pytest_plugin]: https://libvt.git-pull.com/api/pytest_plugin/
[vt_screen]: https://libvt.git-pull.com/api/contrib_syrupy/#libvt.contrib.syrupy.vt_screen
[serialize_vt_snapshot]: https://libvt.git-pull.com/api/contrib_syrupy/#libvt.contrib.syrupy.serialize_vt_snapshot
[vt_snapshot]: https://libvt.git-pull.com/api/contrib_syrupy/#libvt.contrib.syrupy.vt_snapshot
[vt_screen]: https://libvt.git-pull.com/api/testing/#libvt.testing.vt_screen
[serialize_vt_snapshot]: https://libvt.git-pull.com/api/testing/#libvt.testing.serialize_vt_snapshot
[render]: https://libvt.git-pull.com/api/terminal/#libvt.terminal.render
[strip]: https://libvt.git-pull.com/api/terminal/#libvt.terminal.strip
[explain]: https://libvt.git-pull.com/api/codec/#libvt.codec.explain
25 changes: 23 additions & 2 deletions conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from __future__ import annotations

import importlib.util
import typing as t

import pytest
Expand All @@ -10,12 +11,32 @@
from libvt.style import AnsiColor
from libvt.testing import assert_screen, assert_screen_box

if t.TYPE_CHECKING:
from libvt.parser import Parser
from libvt.pytest_plugin import TerminalFactory
from libvt.terminal import FlightRecorder, Terminal


@pytest.fixture(autouse=True)
def _seed_doctest_namespace(doctest_namespace: dict[str, t.Any]) -> None:
"""Populate doctest globals with common ``libvt`` entry points."""
def _seed_doctest_namespace(
request: pytest.FixtureRequest,
doctest_namespace: dict[str, t.Any],
vt_recorder: FlightRecorder,
vt_terminal: Terminal,
vt_factory: TerminalFactory,
vt_parser: Parser,
) -> None:
"""Populate doctest globals with common ``libvt`` entry points and fixtures."""
doctest_namespace["libvt"] = libvt
doctest_namespace["Terminal"] = libvt.Terminal
doctest_namespace["AnsiColor"] = AnsiColor
doctest_namespace["assert_screen"] = assert_screen
doctest_namespace["assert_screen_box"] = assert_screen_box
doctest_namespace["vt_recorder"] = vt_recorder
doctest_namespace["vt_terminal"] = vt_terminal
doctest_namespace["vt_factory"] = vt_factory
doctest_namespace["vt_parser"] = vt_parser
if importlib.util.find_spec(
"syrupy"
) is not None and request.config.pluginmanager.hasplugin("syrupy"):
doctest_namespace["vt_snapshot"] = request.getfixturevalue("vt_snapshot")
63 changes: 33 additions & 30 deletions docs/api/contrib_syrupy.md
Original file line number Diff line number Diff line change
@@ -1,48 +1,51 @@
# `libvt.contrib.syrupy`

Optional [syrupy](https://syrupy-project.github.io/syrupy/) `.ambr` snapshot
serializer and extension for boxed terminal screens, `SGR` style spans, and
`OSC 8` hyperlinks. Install with the `syrupy` extra:
Optional [syrupy](https://syrupy-project.github.io/syrupy/) `.ambr` adapter and
conditional `pytest11` fixture built on top of {mod}`libvt.testing`'s
tool-agnostic {func}`~libvt.testing.serialize_vt_snapshot`,
{func}`~libvt.testing.vt_screen`, and {func}`~libvt.testing.format_vt_diff_lines`
helpers. Install with the `syrupy` extra:

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

When `syrupy` is active in `pytest`, `libvt_syrupy` automatically registers
{fixture}`vt_snapshot` (and omits it from `pytest --fixtures` when `syrupy` is
uninstalled or disabled via `-p no:syrupy`):

```python
>>> import libvt
>>> from libvt.contrib.syrupy import serialize_vt_snapshot, vt_screen
>>> term = libvt.Terminal(rows=2, cols=18)
>>> term.feed(b"\x1b[1;32mOK\x1b[0m port=54192\r\nready")
>>> print(serialize_vt_snapshot(vt_screen(term, scrubbers=[(r"port=\d+", "port=<PORT>")])))
size=18x2 cursor=(1,5,vis=True) alt=False modes=[]
┌──────────────────┐
│OK port=<PORT> │
│ready │
└──────────────────┘
styles:
r0[0..2]: bold fg=green
>>> from libvt.testing import vt_screen
>>> def test_tui_banner(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 _VerifyAmbr: # 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_tui_banner(_VerifyAmbr()) # doctest: +HIDE
```

See {doc}`../topics/testing-and-snapshots` for choosing between immutable
{class}`~libvt.terminal.Snapshot` objects, inline
{func}`~libvt.testing.assert_screen_box` checks, and `.ambr` snapshots (including
2D border-preserving scrubbers, region slices, and `diff=` step deltas).
See {doc}`../topics/testing` for using
{func}`~libvt.testing.serialize_vt_snapshot` and {func}`~libvt.testing.vt_screen`
without `syrupy`, or configuring project-wide `.ambr` scrubbers with
{meth}`VtSnapshotExtension.configure <libvt.contrib.syrupy.VtSnapshotExtension.configure>`.

## Fixture

```{eval-rst}
.. automodule:: libvt.contrib.syrupy
:members:
:no-private-members:
:exclude-members: ScrubberSpec, VtTarget
.. py:module:: libvt.contrib.syrupy

.. py:type:: ScrubberSpec
:module: libvt.contrib.syrupy
:canonical: tuple[str | re.Pattern[str], str]
.. autofixture:: libvt.contrib.syrupy.vt_snapshot
```

Regex ``(pattern, replacement)`` pair accepted by :func:`~libvt.contrib.syrupy.serialize_vt_snapshot`, :func:`~libvt.contrib.syrupy.vt_screen`, and :meth:`~libvt.contrib.syrupy.VtSnapshotExtension.configure`.
## Extension

.. py:type:: VtTarget
:module: libvt.contrib.syrupy
:canonical: Terminal | Snapshot | Screen | RegionView | TmuxCaptureResult | Mapping[str, VtTarget] | Sequence[VtTarget]
```{eval-rst}
.. autoclass:: libvt.contrib.syrupy.VtSnapshotExtension
:members:

Terminal, snapshot, screen, region slice, ``tmux`` capture result, or duck-typed pane wrapper (``.terminal``, ``.snapshot()``, or ``.capture_vt()``) accepted by :func:`~libvt.contrib.syrupy.vt_screen` and :func:`~libvt.contrib.syrupy.serialize_vt_snapshot`.
.. autofunction:: libvt.contrib.syrupy.get_vt_snapshot_extension
```
22 changes: 18 additions & 4 deletions docs/api/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,10 +53,24 @@ Streaming VT500 `Parser`, `CsiParams`, `Action` records, and `parse_sgr`.
Mode-aware `KeyEvent`, `MouseEvent`, `PasteEvent`, and VT sequence `explain`.
:::

:::{grid-item-card} `libvt.aio`, `testing`, & `pytest_plugin`
:::{grid-item-card} `libvt.aio`
:link: aio
:link-type: doc
`AsyncTerminalStream`, POSIX `open_pty`, `assert_screen`, and `vt_*` fixtures.
`AsyncTerminalStream` and POSIX `open_pty` subprocess sessions.
:::

:::{grid-item-card} `libvt.testing`
:link: testing
:link-type: doc
Zero-dependency `assert_screen`, `assert_screen_box`, `vt_screen`,
`serialize_vt_snapshot`, and `format_vt_diff_lines`.
:::

:::{grid-item-card} `libvt.pytest_plugin`
:link: pytest_plugin
:link-type: doc
Import-light `vt_terminal`, `vt_factory`, `vt_recorder`, `vt_parser`, and
`vt_pty` fixtures (`libvt[pytest]`).
:::

:::{grid-item-card} `libvt.graphics`
Expand All @@ -75,8 +89,8 @@ Decoupled `tmux_profile`, `decode_tmux_capture`, `TmuxControlParser`, and
:::{grid-item-card} `libvt.contrib.syrupy`
:link: contrib_syrupy
:link-type: doc
Optional `syrupy` `VtSnapshotExtension`, `vt_screen`, and escape-free boxed VT
and `SGR` `.ambr` serialization.
Optional `syrupy` `VtSnapshotExtension` and conditional `vt_snapshot` fixture for
`.ambr` golden files (`libvt[syrupy]`).
:::

::::
Expand Down
Loading
Loading