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
11 changes: 11 additions & 0 deletions CHANGES
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,17 @@ returned by {meth}`~libvt.snapshot.Snapshot.to_dict`.

### Documentation

#### Document working and committed assertion frames

Clarify that {func}`~libvt.testing.assert_screen`,
{func}`~libvt.testing.assert_screen_box`, and
{func}`~libvt.testing.format_screen_box` capture
{meth}`~libvt.terminal.Terminal.snapshot` when given a
{class}`~libvt.terminal.Terminal`, while {func}`~libvt.testing.vt_screen` and
{func}`~libvt.testing.serialize_vt_snapshot` read
{attr}`~libvt.terminal.Terminal.committed`, and add an executable `?2026`
synchronized-output example in {ref}`testing-working-and-committed-frames`.

#### Split API reference into per-module pages

Add dedicated API reference pages for {mod}`libvt.views`,
Expand Down
12 changes: 11 additions & 1 deletion docs/api/testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,16 @@ styles:
r0[0..2]: bold fg=green
```

Given a {class}`~libvt.terminal.Terminal`, {func}`~libvt.testing.assert_screen`,
{func}`~libvt.testing.assert_screen_box`, and
{func}`~libvt.testing.format_screen_box` capture the live working buffer via
{meth}`~libvt.terminal.Terminal.snapshot`, while
{func}`~libvt.testing.vt_screen` and
{func}`~libvt.testing.serialize_vt_snapshot` read
{attr}`~libvt.terminal.Terminal.committed`. Pass `term.snapshot()` or
`term.committed` explicitly to inspect the same frame across both families (see
{ref}`testing-working-and-committed-frames`).

See {doc}`../topics/snapshots` and {doc}`../topics/testing` for choosing between
immutable {class}`~libvt.snapshot.Snapshot` objects, inline
{func}`~libvt.testing.assert_screen_box` checks, and
Expand All @@ -45,5 +55,5 @@ immutable {class}`~libvt.snapshot.Snapshot` objects, inline
:module: libvt.testing
:canonical: Terminal | Snapshot | Screen | RegionView | SupportsVtTarget

Terminal, snapshot, screen, region slice, :class:`~libvt.testing.SupportsVtTarget` provider (such as :class:`~libvt.contrib.tmux.capture.TmuxCaptureResult`, :class:`~libvt.aio.AsyncTerminalStream`, or :class:`~libvt.aio.PtySession`), or pane wrapper exposing ``.terminal``, ``.snapshot``, or ``.capture_vt()`` accepted by :func:`~libvt.testing.vt_screen` and :func:`~libvt.testing.serialize_vt_snapshot`.
Terminal, snapshot, screen, region slice, :class:`~libvt.testing.SupportsVtTarget` provider (such as :class:`~libvt.contrib.tmux.capture.TmuxCaptureResult`, :class:`~libvt.aio.AsyncTerminalStream`, or :class:`~libvt.aio.PtySession`), or pane wrapper exposing ``.terminal``, ``.snapshot``, or ``.capture_vt()`` accepted by :func:`~libvt.testing.vt_screen` and :func:`~libvt.testing.serialize_vt_snapshot`. A :class:`~libvt.terminal.Terminal` or wrapper exposing ``.terminal`` supplies :attr:`~libvt.terminal.Terminal.committed`; pass :meth:`~libvt.terminal.Terminal.snapshot` for the working buffer.
```
7 changes: 7 additions & 0 deletions docs/topics/snapshots.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,13 @@ frames or raw in-flight buffer state:
└────────────────┘
```

When passed a `Terminal`, {func}`~libvt.testing.assert_screen`,
{func}`~libvt.testing.assert_screen_box`, and `format_screen_box` read
`term.snapshot()`, while {func}`~libvt.testing.vt_screen` and
`serialize_vt_snapshot` read `term.committed`. See
{ref}`testing-working-and-committed-frames` for matching frames across both
helpers.

## Cells, 2D region slices, and `display_lines`

A `Snapshot` supports the same zero-based `(row, col)` indexing and slicing as
Expand Down
44 changes: 41 additions & 3 deletions docs/topics/testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,12 @@ Core {mod}`libvt.testing` requires neither `pytest` nor `syrupy`.

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.recorder.FlightRecorder` appends a disassembled trace of recent
VT sequences to {exc}`~libvt.exc.ScreenAssertionError` when an assertion fails:
{func}`~libvt.testing.assert_screen_box`. Given a `Terminal`, both helpers and
{func}`~libvt.testing.format_screen_box` read the live working buffer via
{meth}`~libvt.terminal.Terminal.snapshot`; pass `term.committed` to check the
last committed frame. Attaching a {class}`~libvt.recorder.FlightRecorder`
appends a disassembled trace of recent VT sequences to
{exc}`~libvt.exc.ScreenAssertionError` when a `Terminal` assertion fails:

```python
>>> from libvt.exc import ScreenAssertionError
Expand Down Expand Up @@ -92,6 +95,41 @@ styles:
r0[6..10]: fg=#ff8c00
```

(testing-working-and-committed-frames)=

### Working and committed frames

During a synchronized redraw (`CSI ? 2026 h` … `CSI ? 2026 l`), the working
buffer changes immediately while `term.committed` holds the previous frame (see
{ref}`topics-sync-and-asyncio`). Passing a `Terminal` directly reads different
capture points across the two helper families:

| Helper | Default frame for `Terminal` | Same frame across both |
| --- | --- | --- |
| `assert_screen`, `assert_screen_box`, `format_screen_box` | Live working buffer (`term.snapshot()`) | Pass `term.committed` for the committed frame |
| {func}`~libvt.testing.vt_screen`, `serialize_vt_snapshot` | Last committed frame (`term.committed`) | Pass `term.snapshot()` for the working frame |

Between `CSI ? 2026 h` and `CSI ? 2026 l`, `assert_screen(term, "NEW")` checks
the in-flight update while `serialize_vt_snapshot(term)` still emits `"OLD"`.
Pass `term.committed` or `term.snapshot()` explicitly when both calls must
inspect the same frame:

```python
>>> from libvt import Terminal
>>> from libvt.testing import assert_screen, serialize_vt_snapshot
>>> term = Terminal(rows=1, cols=6)
>>> term.feed(b"OLD\x1b[?2026h\rNEW")
>>> assert_screen(term, "NEW")
>>> assert_screen(term.committed, "OLD")
>>> "OLD" in serialize_vt_snapshot(term)
True
>>> "NEW" in serialize_vt_snapshot(term.snapshot())
True
>>> term.feed(b"\x1b[?2026l")
>>> "NEW" in serialize_vt_snapshot(term)
True
```

### Assert a palette change

A boxed golden records the cell's color token, such as `fg=red`. To test
Expand Down
101 changes: 78 additions & 23 deletions src/libvt/testing.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,8 +121,28 @@ def format_screen_box(
) -> str:
"""Render *target* inside a column-aligned Unicode ``┌──┐`` / ``│..│`` frame.

Soft-wrapped rows display a ``W`` marker immediately right of the right
border, and C0/C1/BiDi override codepoints are escaped safely.
A :class:`~libvt.terminal.Terminal` is captured from the live working
buffer via :meth:`~libvt.terminal.Terminal.snapshot`, including uncommitted
writes inside an open ``?2026`` synchronized update. Pass
:attr:`~libvt.terminal.Terminal.committed` to render the last committed
frame. Soft-wrapped rows display a ``W`` marker immediately right of the
right border, and C0/C1/BiDi override codepoints are escaped safely.

Parameters
----------
target : Terminal | Snapshot
Live terminal (read via :meth:`~libvt.terminal.Terminal.snapshot`) or
an immutable :class:`~libvt.snapshot.Snapshot` such as
``term.committed``.
rows : int | None, optional
Maximum viewport rows to include. Defaults to all rows.
cols : int | None, optional
Maximum viewport columns to include. Defaults to all columns.

Returns
-------
str
Column-aligned box text with optional trailing ``W`` wrap markers.

Examples
--------
Expand Down Expand Up @@ -216,14 +236,21 @@ def assert_screen(
) -> None:
r"""Assert that *target*'s literal visible text (and *cursor*) matches *expected*.

Unlike :func:`assert_screen_box`, ``assert_screen`` never strips ``┌──┐``
border glyphs, so applications drawing literal box-drawing borders match
verbatim.
A :class:`~libvt.terminal.Terminal` is captured from the live working
buffer via :meth:`~libvt.terminal.Terminal.snapshot`, including uncommitted
writes inside an open ``?2026`` synchronized update. Pass
:attr:`~libvt.terminal.Terminal.committed` to assert the last committed
frame (matching :func:`serialize_vt_snapshot`'s default for a
``Terminal``). Unlike :func:`assert_screen_box`, ``assert_screen`` never
strips ``┌──┐`` border glyphs, so applications drawing literal box-drawing
borders match verbatim.

Parameters
----------
target : Terminal | Snapshot
Live terminal or immutable snapshot under test.
Live terminal (read via :meth:`~libvt.terminal.Terminal.snapshot`, with
:class:`~libvt.recorder.FlightRecorder` diagnostics on mismatch) or an
immutable :class:`~libvt.snapshot.Snapshot` such as ``term.committed``.
expected : str | Sequence[str]
Expected visible text (dedented when passed as a multi-line string)
or explicit sequence of right-trimmed row strings.
Expand Down Expand Up @@ -294,14 +321,21 @@ def assert_screen_box(
) -> None:
r"""Assert that *target* matches a ``┌──┐`` / ``│..│`` boxed diagram.

Validates exact display-column width across every row, preserves interior
and trailing spaces as well as blank rows, and checks soft-wrap flags via
trailing ``│W`` markers outside the right pipe.
A :class:`~libvt.terminal.Terminal` is captured from the live working
buffer via :meth:`~libvt.terminal.Terminal.snapshot`, including uncommitted
writes inside an open ``?2026`` synchronized update. Pass
:attr:`~libvt.terminal.Terminal.committed` to assert the last committed
frame (matching :func:`serialize_vt_snapshot`'s default for a
``Terminal``). Validates exact display-column width across every row,
preserves interior and trailing spaces as well as blank rows, and checks
soft-wrap flags via trailing ``│W`` markers outside the right pipe.

Parameters
----------
target : Terminal | Snapshot
Live terminal or immutable snapshot under test.
Live terminal (read via :meth:`~libvt.terminal.Terminal.snapshot`, with
:class:`~libvt.recorder.FlightRecorder` diagnostics on mismatch) or an
immutable :class:`~libvt.snapshot.Snapshot` such as ``term.committed``.
expected : str
Boxed diagram matching :func:`format_screen_box` layout.
cursor : tuple[int, int] | None, optional
Expand Down Expand Up @@ -476,13 +510,22 @@ class _UriContext:
class VtScreenView:
r"""Configured VT screen wrapper for boxed snapshot serialization.

When *target* (or *diff*) is a :class:`~libvt.terminal.Terminal`, an
:class:`~libvt.aio.AsyncTerminalStream`, a :class:`~libvt.aio.PtySession`,
or a wrapper exposing ``.terminal``, serialization reads
:attr:`~libvt.terminal.Terminal.committed`. Pass
:meth:`~libvt.terminal.Terminal.snapshot` to serialize the live working
buffer during an open ``?2026`` synchronized update.

Attributes
----------
target : VtTarget
:class:`~libvt.terminal.Terminal`, :class:`~libvt.snapshot.Snapshot`,
:class:`~libvt.screen.Screen`, :class:`~libvt.views.RegionView`,
:class:`SupportsVtTarget` provider, or pane handle exposing
``.terminal``, ``.snapshot``, or ``.capture_vt()``.
:class:`~libvt.terminal.Terminal` (read via
:attr:`~libvt.terminal.Terminal.committed`),
:class:`~libvt.snapshot.Snapshot`, :class:`~libvt.screen.Screen`,
:class:`~libvt.views.RegionView`, :class:`SupportsVtTarget` provider,
or pane handle exposing ``.terminal``, ``.snapshot``, or
``.capture_vt()``.
diff : VtTarget | VtScreenView | None
Baseline frame for a contextual diff. A prepared view inherits this
view's region and display options, with its own explicit values taking
Expand Down Expand Up @@ -541,10 +584,16 @@ def vt_screen(
) -> VtScreenView:
r"""Wrap *target* with scrubbing, slicing, or step-diff options.

A :class:`~libvt.terminal.Terminal` (or a wrapper exposing ``.terminal``)
supplies its :attr:`~libvt.terminal.Terminal.committed` frame when
serialized. Pass :meth:`~libvt.terminal.Terminal.snapshot` to capture the
live working buffer during an open ``?2026`` synchronized update.

Parameters
----------
target : VtTarget
Terminal, screen, snapshot, capture result, or duck-typed pane handle.
Terminal (read via :attr:`~libvt.terminal.Terminal.committed`),
snapshot, screen, region, capture result, or duck-typed pane handle.
diff : VtTarget | VtScreenView | None, optional
Previous frame or prepared single-frame view. Its explicit region and
display options override the current view for the baseline. Its
Expand Down Expand Up @@ -1144,18 +1193,24 @@ def serialize_vt_snapshot(
) -> str:
r"""Serialize one captured viewport as an escape-free box.

A terminal supplies its committed frame. Visible row order and soft-wrap
markers come from the captured grid. A standalone
:class:`~libvt.views.RegionView` uses the default profile and grapheme
mode for replacement glyphs.
A :class:`~libvt.terminal.Terminal` (or a wrapper exposing ``.terminal``)
supplies its :attr:`~libvt.terminal.Terminal.committed` frame, holding the
previous frame while ``?2026`` synchronized output is open. Pass
:meth:`~libvt.terminal.Terminal.snapshot` (matching :func:`assert_screen`
and :func:`assert_screen_box`) to serialize the live working buffer
instead. Visible row order and soft-wrap markers come from the captured
grid. A standalone :class:`~libvt.views.RegionView` uses the default
profile and grapheme mode for replacement glyphs.

Parameters
----------
target : VtTarget | VtScreenView
:class:`~libvt.terminal.Terminal`, :class:`~libvt.snapshot.Snapshot`,
:class:`~libvt.screen.Screen`, :class:`~libvt.views.RegionView`,
:class:`SupportsVtTarget` provider, :class:`VtScreenView`, or pane
wrapper exposing ``.terminal``, ``.snapshot``, or ``.capture_vt()``.
:class:`~libvt.terminal.Terminal` (read via
:attr:`~libvt.terminal.Terminal.committed`),
:class:`~libvt.snapshot.Snapshot`, :class:`~libvt.screen.Screen`,
:class:`~libvt.views.RegionView`, :class:`SupportsVtTarget` provider,
:class:`VtScreenView`, or pane wrapper exposing ``.terminal``,
``.snapshot``, or ``.capture_vt()``.
scrubbers : Sequence[ScrubberSpec], optional
Regex or literal path pairs applied to each visible row.
See :type:`ScrubberSpec` for path matching rules.
Expand Down
76 changes: 76 additions & 0 deletions tests/test_testing.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
decode_tmux_capture,
)
from libvt.contrib.tmux.profile import tmux_profile
from libvt.exc import ScreenAssertionError
from libvt.parser import Parser
from libvt.pytest_plugin import TerminalFactory
from libvt.terminal import FlightRecorder, Terminal, strip
Expand Down Expand Up @@ -1807,3 +1808,78 @@ async def _check_stream_target() -> None:
assert unescape_tmux_control_output(strided) == b"hello"
ctrl_ev = TmuxControlParser().feed(memoryview(b"%XeYxZiWtW\n")[::2])
assert len(ctrl_ev) == 1


@pytest.mark.parametrize(
("open_chunks", "close_chunks"),
[
((b"OLD\x1b[?2026h\rNEW",), (b"\x1b[?2026l",)),
(
(b"OLD\x1b[?", b"2026", b"h\rNE", b"W"),
(b"\x1b[?20", b"26l"),
),
(
tuple(bytes([byte]) for byte in b"OLD\x1b[?2026h\rNEW"),
tuple(bytes([byte]) for byte in b"\x1b[?2026l"),
),
],
ids=["whole", "split-control", "one-byte"],
)
def test_testing_helpers_working_and_committed_frames_during_sync_output(
open_chunks: tuple[bytes, ...],
close_chunks: tuple[bytes, ...],
) -> None:
"""Assertion helpers read working frames while serializers read committed frames."""
term = Terminal(rows=1, cols=6)
for chunk in open_chunks:
term.feed(chunk)

expected_old_box = "┌──────┐\n│OLD │\n└──────┘"
expected_new_box = "┌──────┐\n│NEW │\n└──────┘"
expected_old_snap = (
"size=6x1 cursor=(0,3,vis=True) alt=False modes=[]\n" + expected_old_box
)
expected_new_snap = (
"size=6x1 cursor=(0,3,vis=True) alt=False modes=[]\n" + expected_new_box
)

assert_screen(term, "NEW", cursor=(0, 3))
assert_screen(term.snapshot(), "NEW", cursor=(0, 3))
assert_screen(term.committed, "OLD", cursor=(0, 3))
with pytest.raises(ScreenAssertionError):
assert_screen(term, "OLD")
with pytest.raises(ScreenAssertionError):
assert_screen(term.committed, "NEW")

assert_screen_box(term, expected_new_box, cursor=(0, 3))
assert_screen_box(term.snapshot(), expected_new_box, cursor=(0, 3))
assert_screen_box(term.committed, expected_old_box, cursor=(0, 3))
with pytest.raises(ScreenAssertionError):
assert_screen_box(term, expected_old_box)
with pytest.raises(ScreenAssertionError):
assert_screen_box(term.committed, expected_new_box)

assert format_screen_box(term) == expected_new_box
assert format_screen_box(term.snapshot()) == expected_new_box
assert format_screen_box(term.committed) == expected_old_box

assert serialize_vt_snapshot(term) == expected_old_snap
assert serialize_vt_snapshot(vt_screen(term)) == expected_old_snap
assert serialize_vt_snapshot(term.committed) == expected_old_snap
assert serialize_vt_snapshot(vt_screen(term.committed)) == expected_old_snap
assert serialize_vt_snapshot(term.snapshot()) == expected_new_snap
assert serialize_vt_snapshot(vt_screen(term.snapshot())) == expected_new_snap
assert (
"row 0 cols 0..3: 'OLD' -> 'NEW'"
in serialize_vt_snapshot(vt_screen(term.snapshot(), diff=term)).splitlines()[0]
)

for chunk in close_chunks:
term.feed(chunk)

assert_screen(term, "NEW", cursor=(0, 3))
assert_screen(term.committed, "NEW", cursor=(0, 3))
assert_screen_box(term.committed, expected_new_box, cursor=(0, 3))
assert format_screen_box(term.committed) == expected_new_box
assert serialize_vt_snapshot(term) == expected_new_snap
assert serialize_vt_snapshot(vt_screen(term)) == expected_new_snap
Loading