libvt.testing

Tool-agnostic visual screen assertions, boxed VT + SGR snapshot serialization, row-local scrubbing, and diff formatting with no runtime dependencies:

>>> import libvt
>>> from libvt.testing 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

Given a Terminal, assert_screen(), assert_screen_box(), and format_screen_box() capture the live working buffer via snapshot(), while vt_screen() and serialize_vt_snapshot() read committed. Pass term.snapshot() or term.committed explicitly to inspect the same frame across both families (see Working and committed frames).

See Snapshots and Testing Terminal Programs for choosing between immutable Snapshot objects, inline assert_screen_box() checks, and serialize_vt_snapshot() strings.

Column-exact visual boxed screen formatting, serialization, and assertions.

class libvt.testing.SupportsVtTarget
class libvt.testing.SupportsVtTarget

Bases: Protocol

Protocol for objects projecting a snapshot target for libvt.testing.

class libvt.testing.VtScreenView
class libvt.testing.VtScreenView

Bases: object

Configured VT screen wrapper for boxed snapshot serialization.

When target (or diff) is a Terminal, an AsyncTerminalStream, a PtySession, or a wrapper exposing .terminal, serialization reads committed. Pass snapshot() to serialize the live working buffer during an open ?2026 synchronized update.

Examples

>>> from libvt import Terminal
>>> from libvt.testing import VtScreenView, serialize_vt_snapshot, vt_screen
>>> term = Terminal(rows=2, cols=14)
>>> term.feed(b"job=9482  OK")
>>> view = vt_screen(
...     term, scrubbers=[(r"job=\d+", "job=<ID>")], include_styles=False
... )
>>> isinstance(view, VtScreenView) and view.include_styles is False
True
>>> "│job=<ID>  OK  │" in serialize_vt_snapshot(view)
True
libvt.testing.assert_screen(target, expected, *, cursor=None)
function[source]
function[source]
libvt.testing.assert_screen(target, expected, *, cursor=None)

Assert that target’s literal visible text (and cursor) matches expected.

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

Parameters:
  • target (Terminal | Snapshot) – Live terminal (read via snapshot(), with FlightRecorder diagnostics on mismatch) or an immutable Snapshot such as term.committed.

  • expected (str | Sequence[str]) – Expected visible text (dedented when passed as a multi-line string) or a sequence of row strings. Include spaces written by the program.

  • cursor (tuple[int, int] | None, optional) – Expected zero-based (row, col) cursor coordinates, if checked.

Raises:

ScreenAssertionError – When visible lines or cursor coordinates differ from expected.

Return type:

None

Examples

>>> from libvt.terminal import Terminal
>>> from libvt.testing import assert_screen
>>> term = Terminal(rows=2, cols=10)
>>> term.feed(b"ready\r\ndone")
>>> assert_screen(term.committed, "ready\ndone", cursor=(1, 4))
libvt.testing.assert_screen_box(target, expected, *, cursor=None)
function[source]
function[source]
libvt.testing.assert_screen_box(target, expected, *, cursor=None)

Assert that target matches a ┌──┐ / │..│ boxed diagram.

A Terminal is captured from the live working buffer via snapshot(), including uncommitted writes inside an open ?2026 synchronized update. Pass committed to assert the last committed frame (matching 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:
Raises:
  • ValueError – When expected does not form a rectangular ┌──┐ / └──┘ frame.

  • ScreenAssertionError – When screen dimensions, cell contents, soft-wrap flags, or cursor coordinates differ from expected.

Return type:

None

Examples

>>> from libvt.terminal import Terminal
>>> from libvt.testing import assert_screen_box
>>> term = Terminal(rows=2, cols=8)
>>> term.feed("日本ok\r\ndone".encode())
>>> assert_screen_box(
...     term.committed,
...     '''
...     ┌────────┐
...     │日本ok  │
...     │done    │
...     └────────┘
...     ''',
...     cursor=(1, 4),
... )
libvt.testing.format_flight_recorder(target)
function[source]
function[source]
libvt.testing.format_flight_recorder(target)

Render compact flight-recorder state and recent disassembled VT bytes.

Examples

>>> from libvt.terminal import FlightRecorder, Terminal
>>> from libvt.testing import format_flight_recorder
>>> term = Terminal(rows=2, cols=8, recorder=FlightRecorder())
>>> term.feed(b"\x1b[1;32mOK\x1b[0m")
>>> "recent_bytes" in format_flight_recorder(term)
True
Parameters:

target (Terminal)

Return type:

str

libvt.testing.format_screen_box(target, *, rows=None, cols=None)
function[source]
function[source]
libvt.testing.format_screen_box(target, *, rows=None, cols=None)

Render target inside a column-aligned Unicode ┌──┐ / │..│ frame.

A Terminal is captured from the live working buffer via snapshot(), including uncommitted writes inside an open ?2026 synchronized update. Pass 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 snapshot()) or an immutable 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:

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

Return type:

str

Examples

>>> from libvt.terminal import Terminal
>>> from libvt.testing import format_screen_box
>>> term = Terminal(rows=2, cols=8)
>>> term.feed(b"wrapped_line")
>>> print(format_screen_box(term.committed))
┌────────┐
│wrapped_│W
│line    │
└────────┘
libvt.testing.format_vt_diff_lines(serialized_data, snapshot_data, *, color=False, context_lines=2, snapshot_style_fn=None, received_style_fn=None)
function[source]
function[source]
libvt.testing.format_vt_diff_lines(serialized_data, snapshot_data, *, color=False, context_lines=2, snapshot_style_fn=None, received_style_fn=None)

Compare two boxed VT frames by viewport row.

Other text, including a rendered step delta, receives a line diff.

Parameters:
  • serialized_data (str) – Received snapshot text from the current test run.

  • snapshot_data (str) – Stored expected snapshot text.

  • color (bool, optional) – When True and style callbacks are provided, emit ANSI-styled "- " and "+ " lines instead of ASCII ^ caret lines.

  • context_lines (int, optional) – Unchanged context lines retained around each changed hunk.

  • snapshot_style_fn (Callable[[str], str] | None, optional) – Line styling callback for expected "- " lines.

  • received_style_fn (Callable[[str], str] | None, optional) – Line styling callback for received "+ " lines.

Returns:

Frame diffs start with changed header, row and style summaries when context_lines is positive.

Return type:

list[str]

Examples

>>> from libvt import Terminal
>>> from libvt.testing import format_vt_diff_lines, serialize_vt_snapshot
>>> old = Terminal(rows=1, cols=8)
>>> old.feed(b"PASS")
>>> new = Terminal(rows=1, cols=8)
>>> new.feed(b"FAIL")
>>> lines = format_vt_diff_lines(
...     serialize_vt_snapshot(new),
...     serialize_vt_snapshot(old),
... )
>>> lines[0]
"row 0 cols 0..4: 'PASS' -> 'FAIL'"
libvt.testing.serialize_vt_snapshot(target, *, scrubbers=(), include_cursor_shape=False, include_styles=True)
function[source]
function[source]
libvt.testing.serialize_vt_snapshot(target, *, scrubbers=(), include_cursor_shape=False, include_styles=True)

Serialize one captured viewport as an escape-free box.

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

Parameters:
  • target (VtTarget | VtScreenView) – Terminal (read via committed), Snapshot, Screen, RegionView, SupportsVtTarget provider, 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 ScrubberSpec for path matching rules. Replacements shift the rest of that row and remap its cursor column. Insertions shift a cursor at the insertion point with its cell. Text is clipped to the captured width at glyph boundaries.

  • include_cursor_shape (bool, optional) – When True, include shape=<CursorShape> in the cursor header tuple unless marked unexposed by tmux capture completeness metadata.

  • include_styles (bool, optional) – When True, append run-length styles: spans below the viewport box.

Returns:

Escape-free boxed snapshot text with metadata header and styles: spans. A columns: footer records cell boundaries when needed.

Return type:

str

Raises:
  • TypeError – If target (or a VtScreenView’s inner target) is not a supported terminal, snapshot, screen, region, or pane wrapper, or if a pattern has an invalid type.

  • ValueError – If a path provider returns an empty string, or if a prepared baseline view itself specifies a diff.

Examples

>>> from libvt import Terminal
>>> from libvt.testing import serialize_vt_snapshot
>>> term = Terminal(rows=2, cols=12)
>>> term.feed(b"\x1b[1;32mREADY\x1b[0m")
>>> print(serialize_vt_snapshot(term))
size=12x2 cursor=(0,5,vis=True) alt=False modes=[]
┌────────────┐
│READY       │
│            │
└────────────┘
styles:
  r0[0..5]: bold fg=green
libvt.testing.vt_screen(target, *, diff=None, scrubbers=(), region=None, include_styles=None, include_cursor_shape=None)
function[source]
function[source]
libvt.testing.vt_screen(target, *, diff=None, scrubbers=(), region=None, include_styles=None, include_cursor_shape=None)

Wrap target with scrubbing, slicing, or step-diff options.

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

Parameters:
  • target (VtTarget) – Terminal (read via 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 scrubbers run after the current view’s scrubbers.

  • scrubbers (Sequence[ScrubberSpec], optional) – Additional ScrubberSpec pairs applied within each visible row.

  • region (tuple[int, int, int, int] | None, optional) – Half-open (start_row, end_row, start_col, end_col) viewport slice. Replacement glyphs use the source frame’s width settings.

  • include_styles (bool | None, optional) – Override whether the styles: footer is emitted.

  • include_cursor_shape (bool | None, optional) – Override whether cursor shape is included in the header.

Returns:

Immutable wrapper recognized by serialize_vt_snapshot().

Return type:

VtScreenView

Examples

>>> from libvt import Terminal
>>> from libvt.testing import serialize_vt_snapshot, vt_screen
>>> term = Terminal(rows=2, cols=16)
>>> term.feed(b"pid=4821  OK")
>>> view = vt_screen(term, scrubbers=[(r"pid=\d+", "pid=<PID>")])
>>> "│pid=<PID>  OK   │" in serialize_vt_snapshot(view)
True
type libvt.testing.ScrubberSpec = tuple[str | re.Pattern[str] | os.PathLike[str], str]
type
type
type libvt.testing.ScrubberSpec = tuple[str | re.Pattern[str] | os.PathLike[str], str]

(pattern, replacement) pair. Pass a str or re.Pattern for a regex, or an os.PathLike for a literal path substring outside a URI. pathlib.PureWindowsPath matches either slash and either case of a leading drive letter. A matching Windows drive path takes precedence over a one-letter scheme, as in c:/Temp. Supply a regex to match URI text. URI recognition follows captured soft wraps. Replacements stay within the visible row.

type libvt.testing.VtTarget = Terminal | Snapshot | Screen | RegionView | SupportsVtTarget
type
type
type libvt.testing.VtTarget = Terminal | Snapshot | Screen | RegionView | SupportsVtTarget

Terminal, snapshot, screen, region slice, SupportsVtTarget provider (such as TmuxCaptureResult, AsyncTerminalStream, or PtySession), or pane wrapper exposing .terminal, .snapshot, or .capture_vt() accepted by vt_screen() and serialize_vt_snapshot(). A Terminal or wrapper exposing .terminal supplies committed; pass snapshot() for the working buffer.