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
13 changes: 13 additions & 0 deletions CHANGES
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,13 @@ directly. {func}`~libvt.modes.is_private_mode_supported` exposes profile mode
support queries, and {class}`~libvt.snapshot.SnapshotDict` types the dictionary
returned by {meth}`~libvt.snapshot.Snapshot.to_dict`.

#### Replay failed pytest terminal tests (#139)

Run pytest with `--vt-replay-dir` to save the bytes fed to the terminal,
resizes, initial encoding, and the observed screen from a failed test. Run
`python -m libvt replay` on the saved file to check the final rows, wraps,
styles, and cursor offline. See {ref}`replaying-pytest-failures`.

#### Find snapshot text by cell coordinates (#133)

{meth}`~libvt.snapshot.Snapshot.find_cells` returns each visible match as a
Expand All @@ -35,6 +42,12 @@ combined graphemes.

### Fixes

#### Identify hidden screen assertion differences (#139)

{func}`~libvt.testing.assert_screen` reports the first differing row or
column even when box padding hides a written space or expected text lies
beyond the viewport.

#### Keep retained live regions aligned across scroll and reflow (#197)

A live {class}`~libvt.views.RegionView` and its nested crops resolve viewport
Expand Down
6 changes: 5 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,10 @@ styles:

[`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:
and POSIX `vt_pty` fixtures with no snapshot-tool dependencies.

Use `--vt-replay-dir` to [replay a failed terminal test][pytest_replay]
from the bytes and resizes saved by pytest.

```python
>>> import libvt
Expand Down Expand Up @@ -257,6 +260,7 @@ 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/
[pytest_replay]: https://libvt.git-pull.com/topics/testing/#replay-a-failed-terminal-test
[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
Expand Down
54 changes: 54 additions & 0 deletions docs/topics/testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -517,6 +517,60 @@ with no dependency on `syrupy` or any other snapshot tool:
>>> test_parser_actions(vt_parser) # doctest: +HIDE
```

(replaying-pytest-failures)=

### Replay a failed terminal test

Pass `--vt-replay-dir` to capture failures from tests using
{fixture}`vt_terminal`, {fixture}`vt_factory`, or POSIX {fixture}`vt_pty`.
The {download}`example <../../examples/replay_prompt.py>` draws `X` while
the screen is four columns wide. After widening the screen, it writes a
space in column 4. The assertion deliberately omits that space.

```{literalinclude} ../../examples/replay_prompt.py
:language: python
:start-at: from libvt.pytest_plugin
```

Run the failing test from the repository root to save the trace.

```console
$ uv run pytest -q examples/replay_prompt.py --vt-replay-dir=.vt-replays
```

Run `python -m libvt replay` with the JSON path printed in the test report.
The replay command runs offline with libvt installed. It feeds the captured
bytes to a fresh terminal, applies each resize in order, and prints the box
and style spans. Python string literals show written spaces in the visible
rows. Pass `--chunk-size 1` to replay each feed one byte at a time. The CLI
exits with status 1 if replay is unavailable or the captured frame differs.

{func}`~libvt.testing.assert_screen` reports the first differing row or
zero-based display column and shows the full glyph on each side. It prints
a written trailing space as `' '` and shows `padding` past the written cells.
Pass the live fixture terminal to capture the expected rows and the working
frame at the assertion. A boxed assertion
({func}`~libvt.testing.assert_screen_box`) captures the working frame at the
assertion as well. A plain pytest failure or an assertion on an immutable
snapshot (such as `term.committed`) captures each fixture terminal's working
frame at the end of the test call and cannot infer the expected cells or
recover an earlier snapshot.

Replay preserves the terminal's initial `encoding` (`"utf-8"` or `"latin-1"`)
and uses the default profile, policy, and limits. A custom event callback
leaves the trace incomplete. The plugin tracks
{meth}`~libvt.terminal.Terminal.feed`, the bytes consumed by
{meth}`~libvt.terminal.Terminal.feed_until`, and caller-initiated
{meth}`~libvt.terminal.Terminal.resize`. With `vt_pty`, the trace begins
before the first read of the child's output. Set `rows`, `cols`, and `env`
when the child needs fixed dimensions or a controlled `TMPDIR`. The file
includes output from the child and any input the terminal echoed.

Capture stops after 1 MiB of input or 10,000 events per terminal. Unsupported
configuration, oversized geometry or an incomplete history can still produce
a diagnostic artifact with actual rows and the assertion difference. The
JSON includes raw terminal bytes, which may contain private data.

---

(topics-testing-fzf)=
Expand Down
17 changes: 17 additions & 0 deletions examples/replay_prompt.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
"""A deliberately failing screen assertion for the pytest replay guide."""

from __future__ import annotations

from libvt.pytest_plugin import TerminalFactory
from libvt.testing import assert_screen


def test_prompt(vt_factory: TerminalFactory) -> None:
"""Draw while the terminal is narrow and leave a written space after X."""
term = vt_factory(rows=2, cols=8)
term.resize(rows=2, cols=4, reflow=False)
term.feed(b"\x1b[1;7")
term.feed(b"HX")
term.resize(rows=2, cols=8, reflow=False)
term.feed(b"\x1b[1;5H ")
assert_screen(term, [" X"])
24 changes: 22 additions & 2 deletions src/libvt/__main__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
"""Command-line entry point for ``python -m libvt`` (explain, render, strip)."""
"""Command-line entry point for ``python -m libvt`` (explain, render, replay, strip)."""

from __future__ import annotations

Expand Down Expand Up @@ -32,7 +32,7 @@ def main(argv: list[str] | None = None) -> int:
"""Run ``python -m libvt`` subcommands."""
parser = argparse.ArgumentParser(
prog="python -m libvt",
description="Inspect, render, or strip VT byte streams.",
description="Inspect VT byte streams and replay terminal failures.",
)
sub = parser.add_subparsers(dest="command", required=True)

Expand All @@ -51,13 +51,33 @@ def main(argv: list[str] | None = None) -> int:
p_strip = sub.add_parser("strip", help="Strip VT control sequences from input")
p_strip.add_argument("file", nargs="?", default="-", help="Input file or '-'")

p_replay = sub.add_parser(
"replay", help="Replay a pytest terminal failure artifact"
)
p_replay.add_argument("file", help="Replay artifact file or '-'")
p_replay.add_argument(
"--chunk-size",
type=_positive_dimension,
help="Split each feed into N-byte chunks",
)

args = parser.parse_args(argv)
try:
raw = _read_input(args.file)
except OSError as exc:
path = sanitize_terminal_text(args.file)
parser.error(f"cannot read {path}: {exc.strerror or exc}")

if args.command == "replay":
from libvt._replay import _format_replay

try:
out, matches = _format_replay(raw, args.chunk_size)
except ValueError as exc:
p_replay.error(sanitize_terminal_text(str(exc)))
sys.stdout.buffer.write((out + "\n").encode("utf-8"))
return 0 if matches else 1

if args.command == "explain":
out = format_explain(raw)
elif args.command == "render":
Expand Down
Loading
Loading