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:
ProtocolProtocol for objects projecting a snapshot target for
libvt.testing.
-
class libvt.testing.VtScreenView¶class libvt.testing.VtScreenView¶
Bases:
objectConfigured VT screen wrapper for boxed snapshot serialization.
When target (or diff) is a
Terminal, anAsyncTerminalStream, aPtySession, or a wrapper exposing.terminal, serialization readscommitted. Passsnapshot()to serialize the live working buffer during an open?2026synchronized 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)¶libvt.testing.assert_screen(target, expected, *, cursor=None)¶
Assert that target’s literal visible text (and cursor) matches expected.
A
Terminalis captured from the live working buffer viasnapshot(), including uncommitted writes inside an open?2026synchronized update. Passcommittedto assert the last committed frame (matchingserialize_vt_snapshot()’s default for aTerminal). Unlikeassert_screen_box(),assert_screennever strips┌──┐border glyphs, so applications drawing literal box-drawing borders match verbatim.- Parameters:
target (
Terminal|Snapshot) – Live terminal (read viasnapshot(), withFlightRecorderdiagnostics on mismatch) or an immutableSnapshotsuch asterm.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:
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)¶libvt.testing.assert_screen_box(target, expected, *, cursor=None)¶
Assert that target matches a
┌──┐/│..│boxed diagram.A
Terminalis captured from the live working buffer viasnapshot(), including uncommitted writes inside an open?2026synchronized update. Passcommittedto assert the last committed frame (matchingserialize_vt_snapshot()’s default for aTerminal). 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│Wmarkers outside the right pipe.- Parameters:
target (
Terminal|Snapshot) – Live terminal (read viasnapshot(), withFlightRecorderdiagnostics on mismatch) or an immutableSnapshotsuch asterm.committed.expected (
str) – Boxed diagram matchingformat_screen_box()layout.cursor (
tuple[int,int] |None,optional) – Expected zero-based(row, col)cursor coordinates, if checked.
- 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:
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)¶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
-
libvt.testing.format_screen_box(target, *, rows=None, cols=None)¶libvt.testing.format_screen_box(target, *, rows=None, cols=None)¶
Render target inside a column-aligned Unicode
┌──┐/│..│frame.A
Terminalis captured from the live working buffer viasnapshot(), including uncommitted writes inside an open?2026synchronized update. Passcommittedto render the last committed frame. Soft-wrapped rows display aWmarker immediately right of the right border, and C0/C1/BiDi override codepoints are escaped safely.- Parameters:
- Returns:
Column-aligned box text with optional trailing
Wwrap markers.- Return type:
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)¶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) – WhenTrueand 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:
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)¶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 itscommittedframe, holding the previous frame while?2026synchronized output is open. Passsnapshot()(matchingassert_screen()andassert_screen_box()) to serialize the live working buffer instead. Visible row order and soft-wrap markers come from the captured grid. A standaloneRegionViewuses the default profile and grapheme mode for replacement glyphs.- Parameters:
target (
VtTarget|VtScreenView) –Terminal(read viacommitted),Snapshot,Screen,RegionView,SupportsVtTargetprovider,VtScreenView, or pane wrapper exposing.terminal,.snapshot, or.capture_vt().scrubbers (
Sequence[ScrubberSpec],optional) – Regex or literal path pairs applied to each visible row. SeeScrubberSpecfor 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) – WhenTrue, includeshape=<CursorShape>in the cursor header tuple unless marked unexposed bytmuxcapture completeness metadata.include_styles (
bool,optional) – WhenTrue, append run-lengthstyles:spans below the viewport box.
- Returns:
Escape-free boxed snapshot text with metadata header and
styles:spans. Acolumns:footer records cell boundaries when needed.- Return type:
- Raises:
TypeError– If target (or aVtScreenView’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)¶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 itscommittedframe when serialized. Passsnapshot()to capture the live working buffer during an open?2026synchronized update.- Parameters:
target (
VtTarget) – Terminal (read viacommitted), 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) – AdditionalScrubberSpecpairs 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 thestyles: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:
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
(pattern, replacement)pair. Pass astrorre.Patternfor a regex, or anos.PathLikefor a literal path substring outside a URI.pathlib.PureWindowsPathmatches either slash and either case of a leading drive letter. A matching Windows drive path takes precedence over a one-letter scheme, as inc:/Temp. Supply a regex to match URI text. URI recognition follows captured soft wraps. Replacements stay within the visible row.
Terminal, snapshot, screen, region slice,
SupportsVtTargetprovider (such asTmuxCaptureResult,AsyncTerminalStream, orPtySession), or pane wrapper exposing.terminal,.snapshot, or.capture_vt()accepted byvt_screen()andserialize_vt_snapshot(). ATerminalor wrapper exposing.terminalsuppliescommitted; passsnapshot()for the working buffer.