Skip to content

Commit f00ea2b

Browse files
authored
testing(feat[replay]): Replay failed pytest runs (#139)
why: Debugging failed terminal tests across local runs and CI requires exact ordered input bytes, external resizes, initial encoding, and cell-level assertion diagnostics without polluting core Screen or Snapshot state. what: Add opt-in --vt-replay-dir failure capture to libvt.pytest_plugin, offline python -m libvt replay verification (whole-feed and --chunk-size 1), and exact cell-difference reporting in libvt.testing.assert_screen, with examples/replay_prompt.py, tests, docs/topics/testing.md, README.md, and CHANGES. Fixes #136 Fixes #127 Fixes #117
2 parents 9647ae1 + f180c75 commit f00ea2b

10 files changed

Lines changed: 1798 additions & 28 deletions

File tree

‎CHANGES‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,13 @@ directly. {func}`~libvt.modes.is_private_mode_supported` exposes profile mode
2626
support queries, and {class}`~libvt.snapshot.SnapshotDict` types the dictionary
2727
returned by {meth}`~libvt.snapshot.Snapshot.to_dict`.
2828

29+
#### Replay failed pytest terminal tests (#139)
30+
31+
Run pytest with `--vt-replay-dir` to save the bytes fed to the terminal,
32+
resizes, initial encoding, and the observed screen from a failed test. Run
33+
`python -m libvt replay` on the saved file to check the final rows, wraps,
34+
styles, and cursor offline. See {ref}`replaying-pytest-failures`.
35+
2936
#### Find snapshot text by cell coordinates (#133)
3037

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

3643
### Fixes
3744

45+
#### Identify hidden screen assertion differences (#139)
46+
47+
{func}`~libvt.testing.assert_screen` reports the first differing row or
48+
column even when box padding hides a written space or expected text lies
49+
beyond the viewport.
50+
3851
#### Keep retained live regions aligned across scroll and reflow (#197)
3952

4053
A live {class}`~libvt.views.RegionView` and its nested crops resolve viewport

‎README.md‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -166,7 +166,10 @@ styles:
166166

167167
[`libvt.pytest_plugin`][pytest_plugin] (`libvt[pytest]`) provides `vt_terminal`
168168
(wired to a 4 KiB `FlightRecorder`), `vt_factory`, `vt_recorder`, `vt_parser`,
169-
and POSIX `vt_pty` fixtures with no snapshot-tool dependencies:
169+
and POSIX `vt_pty` fixtures with no snapshot-tool dependencies.
170+
171+
Use `--vt-replay-dir` to [replay a failed terminal test][pytest_replay]
172+
from the bytes and resizes saved by pytest.
170173

171174
```python
172175
>>> import libvt
@@ -257,6 +260,7 @@ MIT License. See [LICENSE](LICENSE).
257260
[assert_screen_box]: https://libvt.git-pull.com/api/testing/#libvt.testing.assert_screen_box
258261
[contrib_syrupy]: https://libvt.git-pull.com/api/contrib/syrupy/
259262
[pytest_plugin]: https://libvt.git-pull.com/api/pytest_plugin/
263+
[pytest_replay]: https://libvt.git-pull.com/topics/testing/#replay-a-failed-terminal-test
260264
[vt_snapshot]: https://libvt.git-pull.com/api/contrib/syrupy/#libvt.contrib.syrupy.vt_snapshot
261265
[vt_screen]: https://libvt.git-pull.com/api/testing/#libvt.testing.vt_screen
262266
[serialize_vt_snapshot]: https://libvt.git-pull.com/api/testing/#libvt.testing.serialize_vt_snapshot

‎docs/topics/testing.md‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -517,6 +517,60 @@ with no dependency on `syrupy` or any other snapshot tool:
517517
>>> test_parser_actions(vt_parser) # doctest: +HIDE
518518
```
519519

520+
(replaying-pytest-failures)=
521+
522+
### Replay a failed terminal test
523+
524+
Pass `--vt-replay-dir` to capture failures from tests using
525+
{fixture}`vt_terminal`, {fixture}`vt_factory`, or POSIX {fixture}`vt_pty`.
526+
The {download}`example <../../examples/replay_prompt.py>` draws `X` while
527+
the screen is four columns wide. After widening the screen, it writes a
528+
space in column 4. The assertion deliberately omits that space.
529+
530+
```{literalinclude} ../../examples/replay_prompt.py
531+
:language: python
532+
:start-at: from libvt.pytest_plugin
533+
```
534+
535+
Run the failing test from the repository root to save the trace.
536+
537+
```console
538+
$ uv run pytest -q examples/replay_prompt.py --vt-replay-dir=.vt-replays
539+
```
540+
541+
Run `python -m libvt replay` with the JSON path printed in the test report.
542+
The replay command runs offline with libvt installed. It feeds the captured
543+
bytes to a fresh terminal, applies each resize in order, and prints the box
544+
and style spans. Python string literals show written spaces in the visible
545+
rows. Pass `--chunk-size 1` to replay each feed one byte at a time. The CLI
546+
exits with status 1 if replay is unavailable or the captured frame differs.
547+
548+
{func}`~libvt.testing.assert_screen` reports the first differing row or
549+
zero-based display column and shows the full glyph on each side. It prints
550+
a written trailing space as `' '` and shows `padding` past the written cells.
551+
Pass the live fixture terminal to capture the expected rows and the working
552+
frame at the assertion. A boxed assertion
553+
({func}`~libvt.testing.assert_screen_box`) captures the working frame at the
554+
assertion as well. A plain pytest failure or an assertion on an immutable
555+
snapshot (such as `term.committed`) captures each fixture terminal's working
556+
frame at the end of the test call and cannot infer the expected cells or
557+
recover an earlier snapshot.
558+
559+
Replay preserves the terminal's initial `encoding` (`"utf-8"` or `"latin-1"`)
560+
and uses the default profile, policy, and limits. A custom event callback
561+
leaves the trace incomplete. The plugin tracks
562+
{meth}`~libvt.terminal.Terminal.feed`, the bytes consumed by
563+
{meth}`~libvt.terminal.Terminal.feed_until`, and caller-initiated
564+
{meth}`~libvt.terminal.Terminal.resize`. With `vt_pty`, the trace begins
565+
before the first read of the child's output. Set `rows`, `cols`, and `env`
566+
when the child needs fixed dimensions or a controlled `TMPDIR`. The file
567+
includes output from the child and any input the terminal echoed.
568+
569+
Capture stops after 1 MiB of input or 10,000 events per terminal. Unsupported
570+
configuration, oversized geometry or an incomplete history can still produce
571+
a diagnostic artifact with actual rows and the assertion difference. The
572+
JSON includes raw terminal bytes, which may contain private data.
573+
520574
---
521575

522576
(topics-testing-fzf)=

‎examples/replay_prompt.py‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
"""A deliberately failing screen assertion for the pytest replay guide."""
2+
3+
from __future__ import annotations
4+
5+
from libvt.pytest_plugin import TerminalFactory
6+
from libvt.testing import assert_screen
7+
8+
9+
def test_prompt(vt_factory: TerminalFactory) -> None:
10+
"""Draw while the terminal is narrow and leave a written space after X."""
11+
term = vt_factory(rows=2, cols=8)
12+
term.resize(rows=2, cols=4, reflow=False)
13+
term.feed(b"\x1b[1;7")
14+
term.feed(b"HX")
15+
term.resize(rows=2, cols=8, reflow=False)
16+
term.feed(b"\x1b[1;5H ")
17+
assert_screen(term, [" X"])

‎src/libvt/__main__.py‎

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
"""Command-line entry point for ``python -m libvt`` (explain, render, strip)."""
1+
"""Command-line entry point for ``python -m libvt`` (explain, render, replay, strip)."""
22

33
from __future__ import annotations
44

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

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

54+
p_replay = sub.add_parser(
55+
"replay", help="Replay a pytest terminal failure artifact"
56+
)
57+
p_replay.add_argument("file", help="Replay artifact file or '-'")
58+
p_replay.add_argument(
59+
"--chunk-size",
60+
type=_positive_dimension,
61+
help="Split each feed into N-byte chunks",
62+
)
63+
5464
args = parser.parse_args(argv)
5565
try:
5666
raw = _read_input(args.file)
5767
except OSError as exc:
5868
path = sanitize_terminal_text(args.file)
5969
parser.error(f"cannot read {path}: {exc.strerror or exc}")
6070

71+
if args.command == "replay":
72+
from libvt._replay import _format_replay
73+
74+
try:
75+
out, matches = _format_replay(raw, args.chunk_size)
76+
except ValueError as exc:
77+
p_replay.error(sanitize_terminal_text(str(exc)))
78+
sys.stdout.buffer.write((out + "\n").encode("utf-8"))
79+
return 0 if matches else 1
80+
6181
if args.command == "explain":
6282
out = format_explain(raw)
6383
elif args.command == "render":

0 commit comments

Comments
 (0)