diff --git a/CHANGES b/CHANGES index a651601b..5d67e611 100644 --- a/CHANGES +++ b/CHANGES @@ -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 @@ -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 diff --git a/README.md b/README.md index ea3fcfbc..5ae7ea41 100644 --- a/README.md +++ b/README.md @@ -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 @@ -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 diff --git a/docs/topics/testing.md b/docs/topics/testing.md index 79f53dff..b0857c4e 100644 --- a/docs/topics/testing.md +++ b/docs/topics/testing.md @@ -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)= diff --git a/examples/replay_prompt.py b/examples/replay_prompt.py new file mode 100644 index 00000000..9440f8e6 --- /dev/null +++ b/examples/replay_prompt.py @@ -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"]) diff --git a/src/libvt/__main__.py b/src/libvt/__main__.py index 8f652607..140abd8a 100644 --- a/src/libvt/__main__.py +++ b/src/libvt/__main__.py @@ -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 @@ -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) @@ -51,6 +51,16 @@ 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) @@ -58,6 +68,16 @@ def main(argv: list[str] | None = None) -> int: 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": diff --git a/src/libvt/_replay.py b/src/libvt/_replay.py new file mode 100644 index 00000000..352ec56d --- /dev/null +++ b/src/libvt/_replay.py @@ -0,0 +1,341 @@ +"""Bounded capture and offline playback of terminal assertion failures.""" + +from __future__ import annotations + +import collections.abc +import json +import threading +import typing as t + +from libvt._ucd import sanitize_terminal_text +from libvt._util import _byte_view +from libvt.parser import ParserEncoding +from libvt.snapshot import Snapshot +from libvt.terminal import Terminal +from libvt.testing import serialize_vt_snapshot + +_MAX_BYTES = 1_048_576 +_MAX_EVENTS = 10_000 +_MAX_CELLS = 100_000 + +type _Event = tuple[t.Literal["feed"], str] | tuple[t.Literal["resize"], int, int, bool] + + +class _ReplayArtifact(t.TypedDict): + version: int + rows: int + cols: int + scrollback: int + encoding: ParserEncoding + events: list[_Event] + actual: tuple[str, ...] + frame: str + cursor: tuple[int, int] + pending_wrap: bool + viewport: tuple[int, int] + expected: list[str] | None + difference: str | None + incomplete: str | None + + +def _geometry_ok(rows: int, cols: int) -> bool: + return ( + not isinstance(rows, bool) + and not isinstance(cols, bool) + and rows > 0 + and cols > 0 + and rows * cols <= _MAX_CELLS + ) + + +class _ReplayCapture: + """Bounded :class:`~libvt.recorder.TerminalRecorder` for pytest failure replay.""" + + __slots__ = ( + "_lock", + "byte_count", + "cols", + "encoding", + "events", + "incomplete", + "rows", + "scrollback", + ) + + def __init__( + self, + rows: int, + cols: int, + scrollback: int, + *, + encoding: ParserEncoding = "utf-8", + supported: bool, + ) -> None: + self._lock = threading.Lock() + scrollback_ok = ( + not isinstance(scrollback, bool) and 0 <= scrollback <= _MAX_CELLS + ) + self.rows = rows if not isinstance(rows, bool) and rows > 0 else 1 + self.cols = cols if not isinstance(cols, bool) and cols > 0 else 1 + self.scrollback = ( + scrollback if not isinstance(scrollback, bool) and scrollback >= 0 else 0 + ) + self.encoding: ParserEncoding = encoding + self.events: list[_Event] = [] + self.byte_count = 0 + self.incomplete: str | None = None + if not supported: + self.incomplete = ( + "Capture requires default profile, policy, limits and no event callback" + ) + elif not _geometry_ok(rows, cols) or not scrollback_ok: + self.incomplete = "Initial geometry or scrollback exceeds replay bounds" + + def on_feed(self, data: memoryview, /) -> None: + """Record a normalized 1-D C-contiguous unsigned-byte span.""" + with self._lock: + if self.incomplete: + return + with _byte_view(data) as mv: + if not mv.nbytes: + return + if ( + self.byte_count + mv.nbytes > _MAX_BYTES + or len(self.events) >= _MAX_EVENTS + ): + self.incomplete = "Capture exceeded the byte or event limit" + return + self.byte_count += mv.nbytes + self.events.append(("feed", mv.hex())) + + def on_resize(self, rows: int, cols: int, reflow: bool, /) -> None: + """Record an explicit external terminal resize.""" + with self._lock: + if self.incomplete: + return + if not _geometry_ok(rows, cols) or len(self.events) >= _MAX_EVENTS: + self.incomplete = "Capture exceeded the geometry or event limit" + return + self.events.append(("resize", rows, cols, reflow)) + + def artifact( + self, + snap: Snapshot, + expected: list[str] | None = None, + difference: str | None = None, + ) -> _ReplayArtifact: + """Build a JSON-serializable replay artifact for *snap*.""" + with self._lock: + events = self.events.copy() + incomplete = self.incomplete + artifact: _ReplayArtifact = { + "version": 1, + "rows": self.rows, + "cols": self.cols, + "scrollback": self.scrollback, + "encoding": self.encoding, + "events": events, + "actual": snap.lines, + "frame": serialize_vt_snapshot(snap, include_cursor_shape=True), + "cursor": (snap.cursor.row, snap.cursor.col), + "pending_wrap": snap.cursor.pending_wrap, + "viewport": (snap.rows, snap.cols), + "expected": expected, + "difference": difference, + "incomplete": incomplete, + } + return artifact + + +def _frame_matches(artifact: _ReplayArtifact, snap: Snapshot, frame: str) -> bool: + return ( + snap.lines == artifact["actual"] + and (snap.cursor.row, snap.cursor.col) == artifact["cursor"] + and (snap.rows, snap.cols) == artifact["viewport"] + and snap.cursor.pending_wrap == artifact["pending_wrap"] + and frame == artifact["frame"] + ) + + +def _verify_capture(artifact: _ReplayArtifact) -> None: + if artifact["incomplete"] is not None: + return + replayed = _play( + artifact["rows"], + artifact["cols"], + artifact["scrollback"], + artifact["events"], + encoding=artifact["encoding"], + ) + if not _frame_matches( + artifact, replayed, serialize_vt_snapshot(replayed, include_cursor_shape=True) + ): + artifact["incomplete"] = ( + "Feed and resize history does not reproduce the captured screen" + ) + + +def _play( + rows: int, + cols: int, + scrollback: int, + events: collections.abc.Sequence[_Event], + chunk_size: int | None = None, + *, + encoding: ParserEncoding = "utf-8", +) -> Snapshot: + term = Terminal(rows=rows, cols=cols, scrollback=scrollback, encoding=encoding) + for event in events: + match event: + case ("feed", encoded): + data = bytes.fromhex(encoded) + if chunk_size is None: + term.feed(data) + else: + for offset in range(0, len(data), chunk_size): + term.feed(data[offset : offset + chunk_size]) + case ("resize", new_rows, new_cols, reflow): + term.resize(rows=new_rows, cols=new_cols, reflow=reflow) + return term.snapshot() + + +def _parse_encoding(raw: object) -> ParserEncoding: + if raw == "utf-8": + return "utf-8" + if raw == "latin-1": + return "latin-1" + msg = f"Invalid encoding in replay artifact: {raw!r}" + raise ValueError(msg) + + +def _read_artifact(raw: bytes) -> _ReplayArtifact: + record: object = json.loads(raw) + match record: + case { + "version": int(version), + "rows": int(rows), + "cols": int(cols), + "scrollback": int(scrollback), + "actual": list(actual), + "frame": str(frame), + "cursor": [int(row), int(col)], + "pending_wrap": bool(pending_wrap), + "viewport": [int(view_rows), int(view_cols)], + "events": list(events), + "expected": expected, + "difference": difference, + "incomplete": incomplete, + } if version == 1 and type(version) is int: + encoding = _parse_encoding(record.get("encoding", "utf-8")) + case _: + msg = "Invalid libvt replay artifact" + raise ValueError(msg) + + expected_lines: list[str] | None = None + if isinstance(expected, list): + expected_lines = [line for line in expected if isinstance(line, str)] + if len(expected_lines) != len(expected): + msg = "Invalid expected rows in replay artifact" + raise ValueError(msg) + elif expected is not None: + msg = "Invalid expected rows in replay artifact" + raise ValueError(msg) + actual_lines = tuple(line for line in actual if isinstance(line, str)) + if ( + len(actual_lines) != len(actual) + or (difference is not None and not isinstance(difference, str)) + or (incomplete is not None and not isinstance(incomplete, str)) + or any( + isinstance(n, bool) + for n in (rows, cols, scrollback, row, col, view_rows, view_cols) + ) + or rows <= 0 + or cols <= 0 + or scrollback < 0 + or view_rows <= 0 + or view_cols <= 0 + or len(actual_lines) != view_rows + or not 0 <= row < view_rows + or not 0 <= col < view_cols + or len(events) > _MAX_EVENTS + ): + msg = "Invalid rows, cursor, viewport or event count in replay artifact" + raise ValueError(msg) + if incomplete is None and (not _geometry_ok(rows, cols) or scrollback > _MAX_CELLS): + msg = "Replay geometry or scrollback exceeds capture limits" + raise ValueError(msg) + + validated: list[_Event] = [] + hex_length = 0 + for event in events: + match event: + case ["feed", str(encoded)]: + hex_length += len(encoded) + if hex_length > 2 * _MAX_BYTES: + msg = "Replay exceeds capture byte limit" + raise ValueError(msg) + try: + raw_bytes = bytes.fromhex(encoded) + except ValueError as exc: + msg = "Invalid replay event" + raise ValueError(msg) from exc + if len(encoded) != 2 * len(raw_bytes): + msg = "Invalid replay event" + raise ValueError(msg) + validated.append(("feed", encoded)) + case ["resize", int(new_rows), int(new_cols), bool(reflow)] if _geometry_ok( + new_rows, new_cols + ): + validated.append(("resize", new_rows, new_cols, reflow)) + case _: + msg = "Invalid replay event" + raise ValueError(msg) + return { + "version": version, + "rows": rows, + "cols": cols, + "scrollback": scrollback, + "encoding": encoding, + "events": validated, + "actual": actual_lines, + "frame": frame, + "cursor": (row, col), + "pending_wrap": pending_wrap, + "viewport": (view_rows, view_cols), + "expected": expected_lines, + "difference": difference, + "incomplete": incomplete, + } + + +def _format_replay(raw: bytes, chunk_size: int | None) -> tuple[str, bool]: + artifact = _read_artifact(raw) + rows, cols = artifact["viewport"] + output = [f"size: {cols}x{rows}"] + if artifact["difference"] is not None: + output.append(sanitize_terminal_text(artifact["difference"])) + if artifact["incomplete"] is not None: + reason = sanitize_terminal_text(artifact["incomplete"]) + output.append(f"Replay unavailable: {reason}") + lines = artifact["actual"] + row, col = artifact["cursor"] + matches = False + else: + snap = _play( + artifact["rows"], + artifact["cols"], + artifact["scrollback"], + artifact["events"], + chunk_size, + encoding=artifact["encoding"], + ) + frame = serialize_vt_snapshot(snap, include_cursor_shape=True) + lines = snap.lines + row, col = snap.cursor.row, snap.cursor.col + matches = _frame_matches(artifact, snap, frame) + if not matches: + output.append("Replayed frame differs from the artifact") + output.append(frame) + output.extend(f"row {index}: {line!r}" for index, line in enumerate(lines)) + output.append(f"cursor: ({row}, {col})") + return "\n".join(output), matches diff --git a/src/libvt/pytest_plugin.py b/src/libvt/pytest_plugin.py index 46448499..b6462875 100644 --- a/src/libvt/pytest_plugin.py +++ b/src/libvt/pytest_plugin.py @@ -9,14 +9,175 @@ if t.TYPE_CHECKING: import collections.abc + import contextlib import os + import pathlib + import weakref + from libvt._replay import _ReplayArtifact, _ReplayCapture from libvt.aio import PtySession, TtyMode from libvt.config import Limits, Policy, Profile from libvt.events import Event + from libvt.exc import ScreenAssertionError from libvt.parser import Parser, ParserEncoding from libvt.recorder import FlightRecorder, TerminalRecorder + from libvt.snapshot import Snapshot + from libvt.terminal import Terminal + + +_replay_terminals = pytest.StashKey[dict["Terminal", "_ReplayCapture"]]() +_replay_assertions = pytest.StashKey[ + "weakref.WeakKeyDictionary[ScreenAssertionError, _ReplayArtifact]" +]() + + +def pytest_addoption(parser: pytest.Parser) -> None: + """Register the opt-in terminal failure artifact directory.""" + parser.addoption( + "--vt-replay-dir", + metavar="DIR", + help="Write libvt terminal replay artifacts for failing tests to DIR", + ) + + +def _enable_replay( + request: pytest.FixtureRequest, + term: Terminal, + scrollback: int, + *, + supported: bool = True, +) -> Terminal: + if request.config.getoption("--vt-replay-dir", default=None): + from libvt._replay import _ReplayCapture + + capture = _ReplayCapture( + term.rows, + term.cols, + scrollback, + encoding=term.encoding, + supported=supported, + ) + if capture.incomplete is None: + term._attach_recorder(capture) + request.node.stash.setdefault(_replay_terminals, {})[term] = capture + return term + + +def _pop_stash[T](stash: pytest.Stash, key: pytest.StashKey[T]) -> T | None: + value = stash.get(key, None) + if key in stash: + del stash[key] + return value + + +@pytest.hookimpl(wrapper=True) +def pytest_runtest_call( + item: pytest.Item, +) -> collections.abc.Generator[None, None, None]: + """Observe screen assertions during an opted-in test call.""" + if not item.config.getoption("--vt-replay-dir", default=None): + yield + return + + import threading + import weakref + from libvt.terminal import Terminal + from libvt.testing import _observe_mismatches + + terminals = item.stash.setdefault(_replay_terminals, {}) + assertions: weakref.WeakKeyDictionary[ScreenAssertionError, _ReplayArtifact] = ( + weakref.WeakKeyDictionary() + ) + assertions_lock = threading.Lock() + item.stash[_replay_assertions] = assertions + + def observe( + error: ScreenAssertionError, + target: Terminal | Snapshot, + snap: Snapshot, + expected: list[str] | None, + difference: str | None, + ) -> None: + if ( + isinstance(target, Terminal) + and (capture := terminals.get(target)) is not None + ): + artifact = capture.artifact(snap, expected, difference) + with assertions_lock: + assertions[error] = artifact + + with _observe_mismatches(observe): + yield + + +def _write_replay(directory: pathlib.Path, artifact: _ReplayArtifact) -> pathlib.Path: + import json + import pathlib + import tempfile + + pending: pathlib.Path | None = None + try: + with tempfile.NamedTemporaryFile( + mode="w", + encoding="utf-8", + prefix="libvt-", + suffix=".part", + dir=directory, + delete=False, + ) as stream: + pending = pathlib.Path(stream.name) + json.dump(artifact, stream) + return pending.replace(pending.with_suffix(".json")) + finally: + if pending is not None: + pending.unlink(missing_ok=True) + + +@pytest.hookimpl(wrapper=True) +def pytest_runtest_makereport( + item: pytest.Item, call: pytest.CallInfo[None] +) -> collections.abc.Generator[None, pytest.TestReport, pytest.TestReport]: + """Write terminal traces after a failed test call.""" + report = yield + if call.when == "teardown": + _pop_stash(item.stash, _replay_terminals) + _pop_stash(item.stash, _replay_assertions) + return report + if call.when != "call": + return report + + terminals = _pop_stash(item.stash, _replay_terminals) + assertions = _pop_stash(item.stash, _replay_assertions) + directory: str | None = item.config.getoption("--vt-replay-dir", default=None) + if not (directory and terminals and report.failed): + return report + + from libvt._replay import _verify_capture + from libvt.exc import ScreenAssertionError + + error = call.excinfo.value if call.excinfo is not None else None + artifact = ( + assertions.get(error) + if assertions is not None and isinstance(error, ScreenAssertionError) + else None + ) + artifacts = ( + [artifact] + if artifact is not None + else [capture.artifact(term.snapshot()) for term, capture in terminals.items()] + ) + paths: list[str] = [] + try: + out = (item.config.invocation_params.dir / directory).resolve() + out.mkdir(parents=True, exist_ok=True) + for item_artifact in artifacts: + _verify_capture(item_artifact) + paths.append(str(_write_replay(out, item_artifact))) + except OSError as exc: + paths.append(f"Could not write replay: {exc}") + report.sections.append(("libvt replay", "\n".join(paths))) + return report class TerminalFactory(t.Protocol): @@ -65,10 +226,6 @@ def __call__( """Open a POSIX PTY subprocess session.""" -if t.TYPE_CHECKING: - import contextlib - - @pytest.fixture def vt_recorder() -> FlightRecorder: r"""Return a fresh 4 KiB :class:`~libvt.recorder.FlightRecorder`. @@ -93,7 +250,9 @@ def vt_recorder() -> FlightRecorder: @pytest.fixture -def vt_terminal(vt_recorder: FlightRecorder) -> Terminal: +def vt_terminal( + vt_recorder: FlightRecorder, request: pytest.FixtureRequest +) -> Terminal: r"""Return a fresh ``24x80`` :class:`~libvt.terminal.Terminal` with recorder. Returns @@ -111,11 +270,13 @@ def vt_terminal(vt_recorder: FlightRecorder) -> Terminal: """ from libvt.terminal import Terminal - return Terminal(rows=24, cols=80, recorder=vt_recorder) + return _enable_replay( + request, Terminal(rows=24, cols=80, recorder=vt_recorder), 2_000 + ) @pytest.fixture -def vt_factory() -> TerminalFactory: +def vt_factory(request: pytest.FixtureRequest) -> TerminalFactory: r"""Return a typed factory creating :class:`~libvt.terminal.Terminal` instances. Returns @@ -148,7 +309,7 @@ def _make( record_events: bool = False, recorder: TerminalRecorder | None = None, ) -> Terminal: - return Terminal( + term = Terminal( rows=rows, cols=cols, scrollback=scrollback, @@ -160,6 +321,17 @@ def _make( record_events=record_events, recorder=recorder, ) + return _enable_replay( + request, + term, + scrollback, + supported=( + profile == DEFAULT_PROFILE + and policy == DEFAULT_POLICY + and limits == DEFAULT_LIMITS + and on_event is None + ), + ) return _make @@ -185,7 +357,7 @@ def vt_parser() -> Parser: @pytest.fixture -def vt_pty() -> PtyFactory: +def vt_pty(request: pytest.FixtureRequest) -> PtyFactory: """Return a POSIX :func:`~libvt.aio.open_pty` factory (skips on Windows). Returns @@ -197,10 +369,13 @@ def vt_pty() -> PtyFactory: if sys.platform == "win32": pytest.skip("vt_pty requires POSIX pty.openpty()") + import contextlib + from libvt.aio import open_pty from libvt.config import DEFAULT_LIMITS, DEFAULT_POLICY, DEFAULT_PROFILE - def _spawn( + @contextlib.asynccontextmanager + async def _spawn( argv: collections.abc.Sequence[str], *, rows: int = 24, @@ -218,8 +393,8 @@ def _spawn( sync_timeout: float = 1.0, write_high_water: int | None = None, max_write_buffer: int = 16_777_216, - ) -> contextlib.AbstractAsyncContextManager[PtySession]: - return open_pty( + ) -> collections.abc.AsyncGenerator[PtySession]: + async with open_pty( argv, rows=rows, cols=cols, @@ -236,7 +411,19 @@ def _spawn( sync_timeout=sync_timeout, write_high_water=write_high_water, max_write_buffer=max_write_buffer, - ) + ) as session: + # The reader is registered; its first callback runs at the next yield. + _enable_replay( + request, + session.terminal, + scrollback, + supported=( + profile == DEFAULT_PROFILE + and policy == DEFAULT_POLICY + and limits == DEFAULT_LIMITS + ), + ) + yield session return _spawn diff --git a/src/libvt/testing.py b/src/libvt/testing.py index 26a67431..0cbee690 100644 --- a/src/libvt/testing.py +++ b/src/libvt/testing.py @@ -2,7 +2,9 @@ from __future__ import annotations +import bisect import collections.abc +import contextlib import difflib import inspect import itertools @@ -11,14 +13,17 @@ import pathlib import re import textwrap +import threading import typing as t from dataclasses import dataclass, field from libvt._ucd import ( + CLUSTER_NONE, WidthRole, display_width, sanitize_terminal_text, segment_graphemes, + step_cluster, ) from libvt.codec import format_explain from libvt.config import DEFAULT_PROFILE, Profile, UnicodeBehavior @@ -57,6 +62,26 @@ def _box_row_cells(row: RowView) -> list[str]: return cells +def _segment_expected(text: str, *, mode_2027: bool = True) -> list[str]: + """Segment *text* into UAX #29 clusters or legacy-mode glyphs.""" + if not text: + return [] + if mode_2027: + return segment_graphemes(text) + clusters: list[str] = [] + buf: list[str] = [text[0]] + _, state, _ = step_cluster(CLUSTER_NONE, ord(text[0]), mode_2027=False) + for ch in text[1:]: + extends, state, _ = step_cluster(state, ord(ch), mode_2027=False) + if extends: + buf.append(ch) + else: + clusters.append("".join(buf)) + buf = [ch] + clusters.append("".join(buf)) + return clusters + + def _pad_expected_line( line: str, width: int, @@ -102,7 +127,7 @@ def _pad_expected_line( sanitized = sanitize_terminal_text(line) out: list[str] = [] cols_used = 0 - for cluster in segment_graphemes(sanitized): + for cluster in _segment_expected(sanitized, mode_2027=mode_2027): cw = display_width(cluster, mode_2027=mode_2027, profile=profile) if cols_used + cw > width: break @@ -207,25 +232,124 @@ def format_flight_recorder(target: Terminal) -> str: return "\n".join(lines) +type _MismatchObserver = collections.abc.Callable[ + [ScreenAssertionError, Terminal | Snapshot, Snapshot, list[str] | None, str | None], + None, +] +_mismatch_lock = threading.Lock() +_mismatch_observers: list[_MismatchObserver] = [] + + +@contextlib.contextmanager +def _observe_mismatches( + observer: _MismatchObserver, +) -> collections.abc.Generator[None]: + with _mismatch_lock: + _mismatch_observers.append(observer) + try: + yield + finally: + with _mismatch_lock: + _mismatch_observers.remove(observer) + + def _raise_mismatch( target: Terminal | Snapshot, snap: Snapshot, expected_box: str, actual_box: str, cursor: tuple[int, int] | None, + *, + expected: list[str] | None = None, + difference: str | None = None, ) -> None: details = [ "Screen state mismatch:", f"cursor actual=({snap.cursor.row}, {snap.cursor.col})" + (f" expected={cursor}" if cursor is not None else ""), - "Expected:", - expected_box, - "Actual:", - actual_box, ] + if difference is not None: + details.append(difference) + details.extend(("Expected:", expected_box, "Actual:", actual_box)) if isinstance(target, Terminal): details.append(format_flight_recorder(target)) - raise ScreenAssertionError("\n".join(details)) + error = ScreenAssertionError("\n".join(details)) + with _mismatch_lock: + observers = tuple(_mismatch_observers) + for observer in observers: + observer(error, target, snap, expected, difference) + raise error + + +def _first_screen_difference( + snap: Snapshot, + expected: list[str], + actual: list[str], + cursor: tuple[int, int] | None, +) -> str | None: + for row, (exp, act) in enumerate(itertools.zip_longest(expected, actual)): + if exp == act: + continue + if exp is None or act is None: + boundary = " beyond the viewport" if row >= snap.rows else "" + return ( + f"First difference at row {row}{boundary}: " + f"expected {exp!r}, actual {act!r}" + ) + + offset = next( + index + for index, (left, right) in enumerate(itertools.zip_longest(exp, act)) + if left != right + ) + expected_glyphs = _segment_expected( + exp, mode_2027=Mode.GRAPHEME_CLUSTERING in snap.modes + ) + row_view = snap[row] + actual_cells = [ + (column, glyph) + for column in range(row_view.text_used) + if (glyph := row_view[column].text) + ] + expected_starts = list( + itertools.accumulate(map(len, expected_glyphs), initial=0) + ) + actual_starts = list( + itertools.accumulate((len(glyph) for _, glyph in actual_cells), initial=0) + ) + # A difference inside either glyph starts at its first character. + # Look up both labels at that shared position in the literal prefix. + start = min( + expected_starts[bisect.bisect_right(expected_starts, offset) - 1], + actual_starts[bisect.bisect_right(actual_starts, offset) - 1], + ) + expected_index = bisect.bisect_right(expected_starts, start) - 1 + actual_index = bisect.bisect_right(actual_starts, start) - 1 + expected_cell = ( + repr(expected_glyphs[expected_index]) + if expected_index < len(expected_glyphs) + else "padding" + ) + if actual_index < len(actual_cells): + column, glyph = actual_cells[actual_index] + actual_cell = repr(glyph) + else: + column = row_view.text_used + if column and row_view[column - 1].width_role == WidthRole.SPACER_HEAD: + column -= 1 + actual_cell = "outside the viewport" if column >= snap.cols else "padding" + + return ( + f"First difference at row {row}, column {column}: " + f"expected {expected_cell}, actual {actual_cell}" + ) + + if cursor is not None: + return ( + f"Cursor differs: expected {cursor}, " + f"actual ({snap.cursor.row}, {snap.cursor.col})" + ) + return None def assert_screen( @@ -253,7 +377,7 @@ def assert_screen( 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. + 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. @@ -310,7 +434,15 @@ def assert_screen( ) exp_box_lines.append(f"│{padded}│") exp_box_lines.append(f"└{exp_border}┘") - _raise_mismatch(target, snap, "\n".join(exp_box_lines), actual_box, cursor) + _raise_mismatch( + target, + snap, + "\n".join(exp_box_lines), + actual_box, + cursor, + expected=exp_lines, + difference=_first_screen_difference(snap, exp_lines, act_lines, cursor), + ) def assert_screen_box( diff --git a/tests/test_codec.py b/tests/test_codec.py index c238e47d..362cbaec 100644 --- a/tests/test_codec.py +++ b/tests/test_codec.py @@ -85,7 +85,7 @@ def test_codec_conformance_tables_cover_all_modes_and_documented_osc() -> None: assert {"CUP", "SGR", "DECSTBM", "XTWINOPS", "REP"} <= set(_CSI_NAMES.values()) -@pytest.mark.parametrize("command", ["render", "strip", "explain"]) +@pytest.mark.parametrize("command", ["render", "strip", "explain", "replay"]) def test_cli_reports_missing_input( command: str, tmp_path: pathlib.Path, capsys: pytest.CaptureFixture[str] ) -> None: @@ -100,15 +100,26 @@ def test_cli_reports_missing_input( @pytest.mark.parametrize( - ("flag", "value"), [("--rows", "0"), ("--cols", "-1"), ("--cols", "bad-width")] + ("command", "flag", "value"), + [ + ("render", "--rows", "0"), + ("render", "--cols", "-1"), + ("render", "--cols", "bad-width"), + ("replay", "--chunk-size", "0"), + ("replay", "--chunk-size", "-1"), + ], ) def test_cli_rejects_geometry_before_opening_input( - flag: str, value: str, tmp_path: pathlib.Path, capsys: pytest.CaptureFixture[str] + command: str, + flag: str, + value: str, + tmp_path: pathlib.Path, + capsys: pytest.CaptureFixture[str], ) -> None: """Point to the invalid dimension even when the input path is missing.""" missing = tmp_path / "missing.vt" with pytest.raises(SystemExit) as exit_info: - main(["render", flag, value, str(missing)]) + main([command, flag, value, str(missing)]) assert exit_info.value.code == 2 out, err = capsys.readouterr() assert not out diff --git a/tests/test_testing.py b/tests/test_testing.py index 0663e661..18a16e87 100644 --- a/tests/test_testing.py +++ b/tests/test_testing.py @@ -2,6 +2,7 @@ from __future__ import annotations +import json import os import pathlib import re @@ -11,6 +12,15 @@ import pytest +from libvt._replay import ( + _MAX_BYTES, + _MAX_CELLS, + _MAX_EVENTS, + _format_replay, + _read_artifact, + _ReplayCapture, + _verify_capture, +) from libvt.config import Profile, UnicodeBehavior from libvt.contrib.tmux.capture import ( TmuxPaneMetadata, @@ -23,6 +33,7 @@ from libvt.pytest_plugin import TerminalFactory from libvt.terminal import FlightRecorder, Terminal, strip from libvt.testing import ( + _segment_expected, assert_screen, assert_screen_box, format_screen_box, @@ -1956,3 +1967,983 @@ def test_serialize_retained_live_region_across_scroll_and_reflow() -> None: ) cjk_term.resize(rows=1, cols=1, reflow=False) assert serialize_vt_snapshot(cjk_mid) == "size=0x1 region=True\n┌┐\n││\n└┘" + + +@pytest.mark.parametrize( + ("cols", "actual", "expected", "cjk", "column", "shown_expected", "shown_actual"), + [ + (6, "ab", "a\u0301b", False, 0, "'a\u0301'", "'a'"), + (6, "a\u0301b", "ab", False, 0, "'a'", "'a\u0301'"), + (1, "a", "a\u0301", False, 0, "'a\u0301'", "'a'"), + (1, "a\u0301", "a", False, 0, "'a'", "'a\u0301'"), + (4, "Ωab", "Ωa\u0301b", True, 2, "'a\u0301'", "'a'"), + (4, "Ωa\u0301b", "Ωab", True, 2, "'a'", "'a\u0301'"), + (5, "\x1b[?2027l🇺🇬z", "🇺🇸z", False, 1, "'🇸'", "'🇬'"), + (5, "\x1b[?2027l🇺🇸a\u0301", "🇺🇸a", False, 2, "'a'", "'a\u0301'"), + (6, "\x1b[?2027l©️a\x1b[?2027h", "©️b", False, 1, "'b'", "'a'"), + (4, "日X ", "日X", False, 3, "padding", "' '"), + (4, "日X", "日X ", False, 3, "' '", "padding"), + (2, "日", "日 ", False, 2, "' '", "outside the viewport"), + ], +) +def test_screen_difference_uses_complete_glyphs_and_stored_columns( + cols: int, + actual: str, + expected: str, + cjk: bool, + column: int, + shown_expected: str, + shown_actual: str, +) -> None: + """Locate the difference at the captured cell's physical column.""" + term = Terminal( + rows=1, + cols=cols, + profile=Profile(unicode=UnicodeBehavior(ambiguous_width=2 if cjk else 1)), + ) + term.feed_str(actual) + snap = term.snapshot() + with pytest.raises(ScreenAssertionError) as error: + assert_screen(snap, [expected]) + assert str(error.value).splitlines()[2] == ( + f"First difference at row 0, column {column}: " + f"expected {shown_expected}, actual {shown_actual}" + ) + + +def test_screen_difference_uses_padding_column_before_wide_wrap() -> None: + """A wide-wrap spacer leaves room for the expected last cell in the preview.""" + term = Terminal(rows=2, cols=4) + term.feed_str("abc日") + snap = term.snapshot() + assert snap[0].wrapped + assert snap[0:2, 2:4].lines == ("c", "") + with pytest.raises(ScreenAssertionError) as error: + assert_screen(snap, ["abcX", "日"]) + assert str(error.value).splitlines()[2] == ( + "First difference at row 0, column 3: expected 'X', actual padding" + ) + + +def test_pytest_failure_replays_ordered_resize_and_written_space( + tmp_path: pathlib.Path, +) -> None: + """Replay a failing assertion from outside the original working directory.""" + script = tmp_path / "test_example.py" + example = pathlib.Path(__file__).resolve().parents[1] / "examples/replay_prompt.py" + shutil.copyfile(example, script) + outdir = tmp_path / "artifacts" + config = tmp_path / "pytest.ini" + config.write_text("[pytest]\n", encoding="utf-8") + env = {**os.environ, "PYTHONIOENCODING": "utf-8"} + result = subprocess.run( + [ + sys.executable, + "-m", + "pytest", + "-q", + "-c", + str(config), + f"--vt-replay-dir={outdir}", + str(script), + ], + cwd=tmp_path, + env=env, + capture_output=True, + text=True, + encoding="utf-8", + check=False, + ) + assert result.returncode == 1, result.stdout + result.stderr + assert "row 0, column 4" in result.stdout, result.stdout + assert "actual ' '" in result.stdout + (artifact,) = outdir.glob("*.json") + record = json.loads(artifact.read_text(encoding="utf-8")) + assert record["expected"] == [" X"] + assert record["actual"] == [" X ", ""] + assert record["encoding"] == "utf-8" + assert record["events"][:5] == [ + ["resize", 2, 4, False], + ["feed", "1b5b313b37"], + ["feed", "4858"], + ["resize", 2, 8, False], + ["feed", "1b5b313b354820"], + ] + replay_cwd = tmp_path / "elsewhere" + replay_cwd.mkdir() + replay_args = [ + sys.executable, + "-m", + "libvt", + "replay", + "--chunk-size", + "1", + str(artifact), + ] + offline = subprocess.run( + replay_args, + cwd=replay_cwd, + env=env, + capture_output=True, + text=True, + encoding="utf-8", + check=False, + ) + assert offline.returncode == 0, offline.stderr + assert "' X '" in offline.stdout + + record["events"] = [event for event in record["events"] if event[0] != "resize"] + artifact.write_text(json.dumps(record), encoding="utf-8") + without_resize = subprocess.run( + replay_args, + cwd=replay_cwd, + env=env, + capture_output=True, + text=True, + encoding="utf-8", + check=False, + ) + assert without_resize.returncode == 1 + assert "differs from the artifact" in without_resize.stdout + + +@pytest.mark.skipif(os.name != "posix", reason="requires a POSIX terminal") +def test_pytest_replays_a_real_pty_failure(tmp_path: pathlib.Path) -> None: + """Capture startup output, a resize, and the child's acknowledgement.""" + script = tmp_path / "test_child.py" + script.write_text( + "import os\n" + "import sys\n" + "import pytest\n" + "from libvt.testing import assert_screen\n" + "@pytest.mark.asyncio\n" + "async def test_child(vt_pty, tmp_path):\n" + " root = tmp_path / 'child'\n" + " root.mkdir()\n" + " code = (\n" + " 'import os, tempfile; '\n" + " 'assert tempfile.gettempdir() == os.environ[\"TMPDIR\"]; '\n" + " \"print('Ready'); print('Taken: ' + input())\"\n" + " )\n" + " env = {**os.environ, 'TMPDIR': str(root)}\n" + " async with vt_pty([sys.executable, '-u', '-c', code], " + "rows=4, cols=16, env=env) as session:\n" + " await session.wait_for('Ready', timeout=5)\n" + " session.resize(rows=5, cols=20)\n" + " session.paste('lime')\n" + " session.send_key('enter')\n" + " await session.wait_for('Taken: lime', timeout=5)\n" + " assert_screen(session.terminal, ['wrong'])\n", + encoding="utf-8", + ) + outdir = tmp_path / "artifacts" + result = subprocess.run( + [ + sys.executable, + "-m", + "pytest", + "-q", + f"--vt-replay-dir={outdir}", + str(script), + ], + cwd=tmp_path, + capture_output=True, + text=True, + check=False, + ) + assert result.returncode == 1 and "actual 'R'" in result.stdout, result.stdout + (path,) = outdir.glob("*.json") + artifact = json.loads(path.read_text(encoding="utf-8")) + assert (artifact["rows"], artifact["cols"]) == (4, 16) + assert artifact["incomplete"] is None + assert artifact["expected"] == ["wrong"] + resized = next( + i for i, event in enumerate(artifact["events"]) if event[0] == "resize" + ) + before = b"".join(bytes.fromhex(data) for _, data in artifact["events"][:resized]) + after = b"".join( + bytes.fromhex(data) for _, data in artifact["events"][resized + 1 :] + ) + assert b"Ready" in before and b"Taken: lime" in after + replay = subprocess.run( + [sys.executable, "-m", "libvt", "replay", "--chunk-size", "1", str(path)], + cwd=tmp_path, + capture_output=True, + text=True, + check=True, + ) + assert "'Taken: lime'" in replay.stdout and "actual 'R'" in replay.stdout + + +def test_pytest_replay_fallback_and_incomplete_capture(tmp_path: pathlib.Path) -> None: + """Keep actual rows for plain failures and explain incomplete replay.""" + script = tmp_path / "test_example.py" + script.write_text( + "from libvt.config import Profile, UnicodeBehavior\n" + "from libvt.testing import assert_screen\n" + "def test_plain(vt_terminal):\n" + " vt_terminal.feed(b'actual')\n" + " assert vt_terminal.lines[0] == 'expected'\n" + "def test_unsupported(vt_factory):\n" + " profile = Profile(unicode=UnicodeBehavior(ambiguous_width=2))\n" + " term = vt_factory(rows=1, cols=8, profile=profile)\n" + " term.feed(b'actual ')\n" + " assert_screen(term, ['actual'])\n" + "def test_truncated(vt_terminal):\n" + " for _ in range(10_001):\n" + " vt_terminal.feed(b'\\x00')\n" + " vt_terminal.feed(b'late')\n" + " assert_screen(vt_terminal, ['early'])\n" + "def test_snapshot(vt_terminal):\n" + " vt_terminal.feed(b'original')\n" + " snap = vt_terminal.committed\n" + " vt_terminal.feed(b' later')\n" + " assert_screen(snap, ['expected'])\n" + "def test_pass(vt_terminal):\n" + " vt_terminal.feed(b'ok')\n" + " assert_screen(vt_terminal, ['ok'])\n", + encoding="utf-8", + ) + (tmp_path / "pytest.ini").write_text("[pytest]\n", encoding="utf-8") + outdir = tmp_path / "artifacts" + env = {**os.environ, "PYTHONIOENCODING": "utf-8"} + pytest_args = [sys.executable, "-m", "pytest", "-q", str(script)] + for options in ([], [f"--vt-replay-dir={outdir}"]): + result = subprocess.run( + [*pytest_args, *options], + cwd=tmp_path, + env=env, + capture_output=True, + text=True, + encoding="utf-8", + check=False, + ) + assert result.returncode == 1, result.stdout + result.stderr + assert "4 failed, 1 passed" in result.stdout, result.stdout + if not options: + assert not outdir.exists() + artifacts = { + record["actual"][0]: (record, path) + for path in outdir.glob("*.json") + if (record := json.loads(path.read_text(encoding="utf-8"))) + } + assert set(artifacts) == {"actual", "actual ", "late", "original later"} + assert artifacts["actual"][0]["expected"] is None + assert artifacts["original later"][0]["expected"] is None + assert artifacts["actual "][0]["expected"] == ["actual"] + assert "default profile" in artifacts["actual "][0]["incomplete"] + record, path = artifacts["late"] + assert "byte or event limit" in record["incomplete"] + assert record["expected"] == ["early"] + assert len(record["events"]) == 10_000 + offline = subprocess.run( + [sys.executable, "-m", "libvt", "replay", str(path)], + cwd=tmp_path, + env=env, + capture_output=True, + text=True, + encoding="utf-8", + check=False, + ) + assert offline.returncode == 1, offline.stderr + assert "Replay unavailable" in offline.stdout + assert "row 0: 'late'" in offline.stdout + assert "expected 'e', actual 'l'" in offline.stdout + + +@pytest.mark.parametrize( + ("cols", "payload", "expected", "diagnostic"), + [ + (8, "\x1b[?2027le\u0301Y", ["XY"], "column 0: expected 'X', actual 'e\u0301'"), + (8, "ready>", ["ready> "], "column 6: expected ' ', actual padding"), + (8, "ready> ", ["ready>"], "column 6: expected padding, actual ' '"), + (8, "日X", ["日Y"], "column 2: expected 'Y', actual 'X'"), + (2, "OK", ["OK!"], "column 2: expected '!', actual outside the viewport"), + (2, "OK", ["OK", "extra"], "row 1 beyond the viewport"), + ], +) +def test_assert_screen_identifies_exact_cell_or_boundary( + cols: int, payload: str, expected: list[str], diagnostic: str +) -> None: + """Describe the stored cell or exact viewport boundary on mismatch.""" + term = Terminal(rows=1, cols=cols) + term.feed(payload.encode()) + with pytest.raises(AssertionError) as caught: + assert_screen(term, expected) + assert diagnostic in str(caught.value) + + +def _record_failure( + tmp_path: pathlib.Path, + body: str, + *, + plugins: tuple[str, ...] = ("libvt.pytest_plugin",), +) -> tuple[pathlib.Path, str]: + root = tmp_path / "owned" + root.mkdir(parents=True, exist_ok=True) + script = root / "test_example.py" + script.write_text(body, encoding="utf-8") + config = root / "pytest.ini" + config.write_text("[pytest]\n", encoding="utf-8") + out = root / "replay" + plugin_args: list[str] = [] + for plugin in plugins: + plugin_args.extend(("-p", plugin)) + result = subprocess.run( + [ + sys.executable, + "-m", + "pytest", + *plugin_args, + "-q", + "-c", + str(config), + f"--vt-replay-dir={out}", + str(script), + ], + cwd=root, + env={**os.environ, "PYTEST_DISABLE_PLUGIN_AUTOLOAD": "1", "PYTHONUTF8": "1"}, + capture_output=True, + text=True, + encoding="utf-8", + timeout=15, + check=False, + ) + assert result.returncode == 1, result.stdout + result.stderr + (path,) = out.glob("*.json") + assert str(path) in result.stdout + return path, result.stdout + + +def _replay(path: pathlib.Path) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, "-m", "libvt", "replay", "--chunk-size", "1", str(path)], + cwd=path.parent, + env={**os.environ, "PYTHONUTF8": "1"}, + capture_output=True, + text=True, + encoding="utf-8", + timeout=10, + check=False, + ) + + +def test_replay_rejects_style_only_change(tmp_path: pathlib.Path) -> None: + """Verify that an unchanged line can still differ in style.""" + path, _stdout = _record_failure( + tmp_path, + "from libvt.testing import assert_screen\n" + "def test_example(vt_factory):\n" + " term = vt_factory(rows=2, cols=6)\n" + " term.feed(b'\\x1b[31mQ')\n" + " assert_screen(term, ['wrong'])\n", + ) + original = json.loads(path.read_text(encoding="utf-8")) + assert original["actual"] == ["Q", ""] + assert original["events"] == [["feed", "1b5b33316d51"]] + match = _replay(path) + assert match.returncode == 0, match.stdout + match.stderr + original["events"][0] = ["feed", "1b5b33326d51"] + path.write_text(json.dumps(original), encoding="utf-8") + result = _replay(path) + assert result.returncode == 1, result.stdout + result.stderr + assert "differs from the artifact" in result.stdout + + +def test_replay_preserves_exact_assertion_prefix(tmp_path: pathlib.Path) -> None: + """Capture the frame before failure cleanup mutates the terminal.""" + path, _stdout = _record_failure( + tmp_path, + "from libvt.testing import assert_screen\n" + "def test_example(vt_factory):\n" + " term = vt_factory(rows=2, cols=6)\n" + " term.feed(b'before')\n" + " try:\n" + " assert_screen(term, ['before\u0301'])\n" + " finally:\n" + " term.feed(b'late')\n", + ) + record = json.loads(path.read_text(encoding="utf-8")) + assert record["actual"] == ["before", ""] + assert record["events"] == [["feed", "6265666f7265"]] + assert record["expected"] == ["before\u0301"] + difference = "First difference at row 0, column 5: expected 'e\u0301', actual 'e'" + assert record["difference"] == difference + replay = _replay(path) + assert replay.returncode == 0, replay.stderr + assert difference in replay.stdout + + +def test_replay_requires_only_bytes_consumed_by_feed_until( + tmp_path: pathlib.Path, +) -> None: + """Capture the reported input slice and keep the fixture's raw recorder.""" + path, _stdout = _record_failure( + tmp_path, + "from libvt.terminal import StopOn\n" + "from libvt.testing import assert_screen\n" + "def test_example(vt_factory, vt_recorder):\n" + " term = vt_factory(rows=2, cols=8, recorder=vt_recorder)\n" + " assert term.recorder is vt_recorder\n" + " data = b'ignored\\x1b[?2026hframe\\x1b[?2026lunused'\n" + " step = term.feed_until(data, offset=7, stop=StopOn.SYNC_END)\n" + " assert data[step.offset:] == b'unused'\n" + " assert_screen(term, ['wrong'])\n", + ) + record = json.loads(path.read_text(encoding="utf-8")) + assert record["actual"] == ["frame", ""] + capture = b"".join( + bytes.fromhex(data) for kind, data in record["events"] if kind == "feed" + ) + assert capture == b"\x1b[?2026hframe\x1b[?2026l" + assert _replay(path).returncode == 0 + + +def test_replay_distinguishes_wire_resize_from_external_resize( + tmp_path: pathlib.Path, +) -> None: + """Replay DECCOLM from its bytes and record the external resize separately.""" + path, _stdout = _record_failure( + tmp_path, + "from libvt.testing import assert_screen\n" + "def test_example(vt_factory, vt_recorder):\n" + " term = vt_factory(rows=2, cols=8, recorder=vt_recorder)\n" + " assert term.recorder is vt_recorder\n" + " term.feed(b'\\x1b[?40h\\x1b[?3hX')\n" + " assert term.cols == 132\n" + " term.resize(rows=2, cols=6, reflow=False)\n" + " assert_screen(term, ['wrong'])\n", + ) + artifact = json.loads(path.read_text(encoding="utf-8")) + assert artifact["actual"] == ["X", ""] + assert artifact["events"] == [ + ["feed", "1b5b3f3430681b5b3f336858"], + ["resize", 2, 6, False], + ] + assert _replay(path).returncode == 0 + + +def test_replay_slotted_terminal_strided_buffers_and_deccolm( + tmp_path: pathlib.Path, +) -> None: + """Slotted Terminal, strided feeds, DECCOLM, and FlightRecorder coexist.""" + path, stdout = _record_failure( + tmp_path, + "from libvt.terminal import StopOn\n" + "from libvt.testing import assert_screen\n" + "def test_example(vt_terminal, vt_recorder):\n" + " assert not hasattr(vt_terminal, '__dict__')\n" + " assert vt_terminal.recorder is vt_recorder\n" + " raw1 = b'\\x1b[?40h\\x1b[?3hAB'\n" + " b1 = bytearray(len(raw1) * 2)\n" + " b1[::2] = raw1[::-1]\n" + " strided_rev = memoryview(b1)[::2][::-1]\n" + " vt_terminal.feed(strided_rev)\n" + " assert vt_terminal.cols == 132\n" + " vt_terminal.resize(rows=2, cols=8, reflow=False)\n" + " raw2 = b'skip\\x1b[?2026hCD\\x1b[?2026lrest'\n" + " b2 = bytearray(len(raw2) * 2)\n" + " b2[::2] = raw2\n" + " strided2 = memoryview(b2)[::2]\n" + " step = vt_terminal.feed_until(strided2, offset=4, stop=StopOn.SYNC_END)\n" + " assert bytes(strided2[step.offset:]) == b'rest'\n" + " assert vt_recorder.tail().endswith(b'\\x1b[?2026hCD\\x1b[?2026l')\n" + " assert_screen(vt_terminal, ['wrong'])\n", + ) + assert "recent_bytes (" in stdout + record = json.loads(path.read_text(encoding="utf-8")) + assert record["incomplete"] is None + assert record["encoding"] == "utf-8" + assert record["actual"] == ["ABCD", ""] + assert record["events"] == [ + ["feed", b"\x1b[?40h\x1b[?3hAB".hex()], + ["resize", 2, 8, False], + ["feed", b"\x1b[?2026hCD\x1b[?2026l".hex()], + ] + replay = _replay(path) + assert replay.returncode == 0, replay.stdout + replay.stderr + assert "'ABCD'" in replay.stdout + + +def test_replay_latin1_encoding_roundtrip(tmp_path: pathlib.Path) -> None: + """Record and replay ``encoding='latin-1'`` and reject invalid encodings.""" + path, _stdout = _record_failure( + tmp_path, + "from libvt.testing import assert_screen\n" + "def test_latin1(vt_factory):\n" + " term = vt_factory(rows=2, cols=8, encoding='latin-1')\n" + " assert not hasattr(term, '__dict__')\n" + " term.feed(b'caf\\xe9')\n" + " assert_screen(term, ['cafe'])\n", + ) + record = json.loads(path.read_text(encoding="utf-8")) + assert record["incomplete"] is None + assert record["encoding"] == "latin-1" + assert record["actual"] == ["café", ""] + assert record["events"] == [["feed", b"caf\xe9".hex()]] + replay = _replay(path) + assert replay.returncode == 0, replay.stdout + replay.stderr + assert "'café'" in replay.stdout + + record["encoding"] = "ascii" + path.write_text(json.dumps(record), encoding="utf-8") + invalid = _replay(path) + assert invalid.returncode == 2 + assert "Invalid encoding" in invalid.stderr + + +@pytest.mark.skipif(os.name != "posix", reason="requires a POSIX terminal") +def test_replay_pty_slotted_and_latin1(tmp_path: pathlib.Path) -> None: + """``vt_pty`` attaches replay onto slotted ``Terminal`` with latin-1 encoding.""" + path, stdout = _record_failure( + tmp_path, + "import sys\n" + "import pytest\n" + "from libvt.testing import assert_screen\n" + "@pytest.mark.asyncio\n" + "async def test_pty_replay(vt_pty):\n" + " code = (\n" + " \"import sys; sys.stdout.buffer.write(b'caf\\\\xe9\\\\n'); \"\n" + " \"sys.stdout.buffer.flush(); print('got:' + input())\"\n" + " )\n" + " argv = [sys.executable, '-u', '-c', code]\n" + " async with vt_pty(argv, rows=4, cols=16, encoding='latin-1') as session:\n" + " assert not hasattr(session.terminal, '__dict__')\n" + " await session.wait_for('café', timeout=5)\n" + " session.resize(rows=5, cols=20)\n" + " session.paste('ok')\n" + " session.send_key('enter')\n" + " await session.wait_for('got:ok', timeout=5)\n" + " assert_screen(session.terminal, ['wrong'])\n", + plugins=("pytest_asyncio.plugin", "libvt.pytest_plugin"), + ) + assert "recent_bytes (" in stdout + record = json.loads(path.read_text(encoding="utf-8")) + assert record["incomplete"] is None + assert record["encoding"] == "latin-1" + assert (record["rows"], record["cols"]) == (4, 16) + assert any(ev[0] == "resize" and ev[1:3] == [5, 20] for ev in record["events"]) + replay = _replay(path) + assert replay.returncode == 0, replay.stdout + replay.stderr + assert "'café'" in replay.stdout and "'got:ok'" in replay.stdout + + +def test_segment_expected_legacy_mode_cursor_diff_and_bce_blank() -> None: + """Legacy ?2027l segmentation keeps CLUSTER_NONE, cursor diffs, and BCE blanks.""" + assert _segment_expected("") == [] + assert _segment_expected("e\u0301x", mode_2027=False) == ["e\u0301", "x"] + assert _segment_expected("\u200d\u0301", mode_2027=False) == ["\u200d", "\u0301"] + assert _segment_expected("👨\u200d🏻", mode_2027=False) == ["👨", "\u200d", "🏻"] + + # Cursor-only mismatch reports explicit cursor difference. + cur_term = Terminal(rows=1, cols=6) + cur_term.feed(b"OK") + with pytest.raises(ScreenAssertionError) as cur_err: + assert_screen(cur_term, ["OK"], cursor=(0, 5)) + assert "Cursor differs: expected (0, 5), actual (0, 2)" in str(cur_err.value) + + # Legacy ?2027l combining mark in expected text reports the full legacy glyph. + leg_term = Terminal(rows=1, cols=8) + leg_term.feed("\x1b[?2027l\u200d\u0301X".encode()) + with pytest.raises(ScreenAssertionError) as leg_err: + assert_screen(leg_term, ["\u200d\u0301Y"]) + assert "expected '\\u200d', actual 'X'" in str(leg_err.value) + + # BCE styled blank row (used > 0, text_used == 0) stays unwritten padding. + bce_term = Terminal(rows=2, cols=6) + bce_term.feed(b"\x1b[41m\x1b[2K\r\nOK") + assert (bce_term.screen[0].used, bce_term.screen[0].text_used) == (6, 0) + with pytest.raises(ScreenAssertionError) as bce_err: + assert_screen(bce_term, [" ", "OK"]) + assert "First difference at row 0, column 0: expected ' ', actual padding" in str( + bce_err.value + ) + + +def test_replay_worker_thread_box_assertion_and_stash_release( + tmp_path: pathlib.Path, +) -> None: + """Capture worker-thread and boxed assertion frames and release item stash.""" + root = tmp_path / "worker" + root.mkdir() + (root / "pytest.ini").write_text("[pytest]\n", encoding="utf-8") + (root / "conftest.py").write_text( + "import json, pathlib\n" + "from libvt.pytest_plugin import _replay_assertions, _replay_terminals\n" + "def pytest_sessionfinish(session, exitstatus):\n" + " leaked = [\n" + " item.name\n" + " for item in session.items\n" + " if (_replay_terminals in item.stash\n" + " or _replay_assertions in item.stash)\n" + " ]\n" + " (pathlib.Path(session.config.rootpath) / 'stash_check.json').write_text(\n" + " json.dumps({'count': len(session.items), 'leaked': leaked}),\n" + " encoding='utf-8',\n" + " )\n", + encoding="utf-8", + ) + script = root / "test_worker_cases.py" + script.write_text( + "from concurrent.futures import ThreadPoolExecutor\n" + "from libvt.testing import assert_screen, assert_screen_box\n" + "def test_worker(vt_factory):\n" + " term = vt_factory(rows=1, cols=6)\n" + " term.feed(b'before')\n" + " with ThreadPoolExecutor(max_workers=1) as workers:\n" + " try:\n" + " workers.submit(assert_screen, term, 'wanted').result()\n" + " finally:\n" + " term.feed(b'\\rlate!!')\n" + "def test_box_assertion(vt_factory):\n" + " term = vt_factory(rows=1, cols=6)\n" + " term.feed(b'boxed!')\n" + " try:\n" + " assert_screen_box(term, '┌──────┐\\n│other!│\\n└──────┘')\n" + " finally:\n" + " term.feed(b'\\rafter!')\n" + "def test_pass_cleans_stash(vt_terminal):\n" + " vt_terminal.feed(b'ok')\n" + " assert_screen(vt_terminal, ['ok'])\n", + encoding="utf-8", + ) + outdir = root / "replays" + result = subprocess.run( + [ + sys.executable, + "-m", + "pytest", + "-p", + "libvt.pytest_plugin", + "-q", + "-c", + str(root / "pytest.ini"), + f"--vt-replay-dir={outdir}", + str(script), + ], + cwd=root, + env={**os.environ, "PYTEST_DISABLE_PLUGIN_AUTOLOAD": "1", "PYTHONUTF8": "1"}, + capture_output=True, + text=True, + encoding="utf-8", + timeout=15, + check=False, + ) + assert result.returncode == 1, result.stdout + result.stderr + assert "2 failed, 1 passed" in result.stdout, result.stdout + stash_report = json.loads((root / "stash_check.json").read_text(encoding="utf-8")) + assert stash_report == {"count": 3, "leaked": []} + + by_actual = { + rec["actual"][0]: (rec, p) + for p in outdir.glob("*.json") + if (rec := json.loads(p.read_text(encoding="utf-8"))) + } + assert set(by_actual) == {"before", "boxed!"} + + worker_rec, worker_path = by_actual["before"] + assert worker_rec["incomplete"] is None + assert worker_rec["expected"] == ["wanted"] + assert worker_rec["difference"] == ( + "First difference at row 0, column 0: expected 'w', actual 'b'" + ) + assert worker_rec["events"] == [["feed", b"before".hex()]] + + box_rec, box_path = by_actual["boxed!"] + assert box_rec["incomplete"] is None + assert box_rec["expected"] is None + assert box_rec["events"] == [["feed", b"boxed!".hex()]] + + # Whole-feed CLI replay (no --chunk-size) matches --chunk-size 1 and stdin '-'. + whole = subprocess.run( + [sys.executable, "-m", "libvt", "replay", str(worker_path)], + cwd=tmp_path, + env={**os.environ, "PYTHONUTF8": "1"}, + capture_output=True, + text=True, + encoding="utf-8", + timeout=10, + check=False, + ) + chunked = _replay(worker_path) + stdin_run = subprocess.run( + [sys.executable, "-m", "libvt", "replay", "-"], + input=worker_path.read_text(encoding="utf-8"), + cwd=tmp_path, + env={**os.environ, "PYTHONUTF8": "1"}, + capture_output=True, + text=True, + encoding="utf-8", + timeout=10, + check=False, + ) + assert whole.returncode == chunked.returncode == stdin_run.returncode == 0 + assert whole.stdout == chunked.stdout == stdin_run.stdout + assert _replay(box_path).returncode == 0 + + +def test_replay_bce_blank_and_sync_2026_held_frame(tmp_path: pathlib.Path) -> None: + """Replay preserves BCE styled blanks (used>0, text_used==0) and open ?2026.""" + bce_path, _ = _record_failure( + tmp_path / "bce", + "from libvt.testing import assert_screen\n" + "def test_bce(vt_factory):\n" + " term = vt_factory(rows=1, cols=6)\n" + " term.feed(b'\\x1b[41m\\x1b[2K')\n" + " assert_screen(term, [' '])\n", + ) + bce_rec = json.loads(bce_path.read_text(encoding="utf-8")) + assert bce_rec["incomplete"] is None + assert bce_rec["actual"] == [""] + assert "bg=red" in bce_rec["frame"] + assert _replay(bce_path).returncode == 0 + bce_rec["events"] = [["feed", b"\x1b[42m\x1b[2K".hex()]] + bce_path.write_text(json.dumps(bce_rec), encoding="utf-8") + bce_diff = _replay(bce_path) + assert bce_diff.returncode == 1 + assert "differs from the artifact" in bce_diff.stdout + + sync_path, _ = _record_failure( + tmp_path / "sync", + "from libvt.testing import assert_screen\n" + "def test_sync_held(vt_factory):\n" + " term = vt_factory(rows=1, cols=6)\n" + " term.feed(b'OLD\\x1b[?2026h\\rNEW')\n" + " assert_screen(term, ['OLD'])\n", + ) + sync_rec = json.loads(sync_path.read_text(encoding="utf-8")) + assert sync_rec["incomplete"] is None + assert sync_rec["actual"] == ["NEW"] + assert sync_rec["expected"] == ["OLD"] + whole = subprocess.run( + [sys.executable, "-m", "libvt", "replay", str(sync_path)], + cwd=tmp_path, + env={**os.environ, "PYTHONUTF8": "1"}, + capture_output=True, + text=True, + encoding="utf-8", + timeout=10, + check=False, + ) + chunked = _replay(sync_path) + assert whole.returncode == chunked.returncode == 0 + assert whole.stdout == chunked.stdout + assert "row 0: 'NEW'" in whole.stdout + + +def test_replay_direct_validation_limits_unwritable_dir_and_on_event( + tmp_path: pathlib.Path, +) -> None: + """Validate replay artifact schema, limits, divergence, on_event, and OSError.""" + # Oversized geometry / scrollback, byte limit, resize limit, and divergence. + big_geom = _ReplayCapture(500, 500, 0, supported=True) + assert big_geom.incomplete is not None and "geometry" in big_geom.incomplete + + big_scroll = _ReplayCapture(2, 4, _MAX_CELLS + 1, supported=True) + assert big_scroll.incomplete is not None + + cap = _ReplayCapture(1, 6, 0, supported=True) + cap.on_feed(memoryview(b"")) + assert cap.events == [] + cap.on_feed(memoryview(b"A" * (_MAX_BYTES + 1))) + assert cap.incomplete is not None and "byte or event limit" in cap.incomplete + + cap_resize = _ReplayCapture(1, 6, 0, supported=True) + cap_resize.on_resize(500, 500, True) + assert cap_resize.incomplete is not None and "geometry" in cap_resize.incomplete + + # _verify_capture flags mismatch when state changed outside feed/resize (reset). + term = Terminal(rows=1, cols=6) + div_cap = _ReplayCapture(1, 6, 0, supported=True) + term._attach_recorder(div_cap) + term.feed(b"hello") + term.reset() + art = div_cap.artifact(term.snapshot()) + _verify_capture(art) + assert art["incomplete"] is not None + assert "does not reproduce" in art["incomplete"] + + # Build a valid baseline artifact and test strict schema validation. + ok_term = Terminal(rows=1, cols=6) + ok_cap = _ReplayCapture(1, 6, 0, supported=True) + ok_term._attach_recorder(ok_cap) + ok_term.feed(b"AB") + valid = ok_cap.artifact(ok_term.snapshot()) + formatted, matched = _format_replay(json.dumps(valid).encode("utf-8"), None) + assert matched is True and "row 0: 'AB'" in formatted + + with pytest.raises(json.JSONDecodeError): + _read_artifact(b"{bad json") + with pytest.raises(UnicodeDecodeError): + _read_artifact(b"\x80\x81") + + bad_mutations: list[tuple[dict[str, object], str]] = [ + ({"version": 2}, "Invalid libvt replay artifact"), + ({"version": True}, "Invalid libvt replay artifact"), + ({"expected": "not-a-list"}, "Invalid expected rows"), + ({"expected": [123]}, "Invalid expected rows"), + ({"actual": [123]}, "Invalid rows, cursor, viewport"), + ({"difference": 123}, "Invalid rows, cursor, viewport"), + ({"incomplete": 123}, "Invalid rows, cursor, viewport"), + ({"rows": True, "incomplete": "partial"}, "Invalid rows, cursor, viewport"), + ({"cols": False, "incomplete": "partial"}, "Invalid rows, cursor, viewport"), + ( + {"scrollback": True, "incomplete": "partial"}, + "Invalid rows, cursor, viewport", + ), + ({"rows": 0, "incomplete": "partial"}, "Invalid rows, cursor, viewport"), + ({"cols": -1, "incomplete": "partial"}, "Invalid rows, cursor, viewport"), + ({"scrollback": -1, "incomplete": "partial"}, "Invalid rows, cursor, viewport"), + ( + {"viewport": [0, 6], "actual": [], "incomplete": "partial"}, + "Invalid rows, cursor, viewport", + ), + ( + {"viewport": [1, -5], "incomplete": "partial"}, + "Invalid rows, cursor, viewport", + ), + ( + {"cursor": [-1, 0], "incomplete": "partial"}, + "Invalid rows, cursor, viewport", + ), + ({"cursor": [0, 6], "incomplete": "partial"}, "Invalid rows, cursor, viewport"), + ( + {"cursor": [True, 0], "incomplete": "partial"}, + "Invalid rows, cursor, viewport", + ), + ({"events": [["feed", "zz"]], "incomplete": "partial"}, "Invalid replay event"), + ({"events": [["feed", "4"]], "incomplete": "partial"}, "Invalid replay event"), + ( + {"events": [["feed", "41 42"]], "incomplete": "partial"}, + "Invalid replay event", + ), + ({"events": [["feed", "41 42"]]}, "Invalid replay event"), + ({"events": [["resize", 0, 4, True]]}, "Invalid replay event"), + ({"events": [["unknown", "41"]]}, "Invalid replay event"), + ({"events": [["feed", "00"]] * (_MAX_EVENTS + 1)}, "event count"), + ({"events": [["feed", "00" * (_MAX_BYTES + 1)]]}, "byte limit"), + ({"rows": 500, "cols": 500, "viewport": [1, 6]}, "capture limits"), + ({"scrollback": _MAX_CELLS + 1}, "capture limits"), + ] + for patch, expected_msg in bad_mutations: + mutated = {**valid, **patch} + with pytest.raises(ValueError, match=expected_msg): + _read_artifact(json.dumps(mutated).encode("utf-8")) + + # CLI returns exit 2 on invalid stdin JSON. + bad_stdin = subprocess.run( + [sys.executable, "-m", "libvt", "replay", "-"], + input="{not-json", + cwd=tmp_path, + env={**os.environ, "PYTHONUTF8": "1"}, + capture_output=True, + text=True, + encoding="utf-8", + timeout=10, + check=False, + ) + assert bad_stdin.returncode == 2 + + # on_event marks capture incomplete without dropping actual rows. + ev_path, _ = _record_failure( + tmp_path / "on_event", + "from libvt.testing import assert_screen\n" + "def test_on_event(vt_factory):\n" + " term = vt_factory(rows=1, cols=6, on_event=lambda ev: None)\n" + " term.feed(b'bell\\x07')\n" + " assert_screen(term, ['quiet'])\n", + ) + ev_rec = json.loads(ev_path.read_text(encoding="utf-8")) + assert ev_rec["incomplete"] is not None + assert "no event callback" in ev_rec["incomplete"] + assert ev_rec["actual"] == ["bell"] + + # Unwritable --vt-replay-dir (regular file) reports OSError without crashing pytest. + unwritable = tmp_path / "not_a_dir" + unwritable.write_text("file", encoding="utf-8") + err_root = tmp_path / "unwritable_case" + err_root.mkdir() + (err_root / "pytest.ini").write_text("[pytest]\n", encoding="utf-8") + err_script = err_root / "test_fail.py" + err_script.write_text( + "from libvt.testing import assert_screen\n" + "def test_fail(vt_factory):\n" + " term = vt_factory(rows=1, cols=6)\n" + " term.feed(b'hi')\n" + " assert_screen(term, ['bye'])\n", + encoding="utf-8", + ) + unwritable_run = subprocess.run( + [ + sys.executable, + "-m", + "pytest", + "-p", + "libvt.pytest_plugin", + "-q", + "-c", + str(err_root / "pytest.ini"), + f"--vt-replay-dir={unwritable}", + str(err_script), + ], + cwd=err_root, + env={**os.environ, "PYTEST_DISABLE_PLUGIN_AUTOLOAD": "1", "PYTHONUTF8": "1"}, + capture_output=True, + text=True, + encoding="utf-8", + timeout=15, + check=False, + ) + assert unwritable_run.returncode == 1 + assert "Could not write replay:" in unwritable_run.stdout + + # Relative --vt-replay-dir stays anchored to pytest invocation dir across chdir. + inv_root = tmp_path / "chdir_inv" + inv_root.mkdir() + (inv_root / "pytest.ini").write_text("[pytest]\n", encoding="utf-8") + chdir_script = inv_root / "test_chdir.py" + chdir_script.write_text( + "from libvt.testing import assert_screen\n" + "def test_chdir(vt_factory, monkeypatch, tmp_path):\n" + " monkeypatch.chdir(tmp_path)\n" + " term = vt_factory(rows=1, cols=6)\n" + " term.feed(b'moved')\n" + " assert_screen(term, ['wrong'])\n", + encoding="utf-8", + ) + chdir_run = subprocess.run( + [ + sys.executable, + "-m", + "pytest", + "-p", + "libvt.pytest_plugin", + "-q", + "-c", + str(inv_root / "pytest.ini"), + "--vt-replay-dir=.vt-replays", + str(chdir_script), + ], + cwd=inv_root, + env={**os.environ, "PYTEST_DISABLE_PLUGIN_AUTOLOAD": "1", "PYTHONUTF8": "1"}, + capture_output=True, + text=True, + encoding="utf-8", + timeout=15, + check=False, + ) + assert chdir_run.returncode == 1, chdir_run.stdout + chdir_run.stderr + (anchored,) = (inv_root / ".vt-replays").glob("*.json") + assert json.loads(anchored.read_text(encoding="utf-8"))["actual"] == ["moved"] + + # bool/negative scrollback emits valid incomplete JSON readable by _format_replay. + for bad_sb in (False, True, -1): + bad_cap = _ReplayCapture(1, 6, bad_sb, supported=True) + assert bad_cap.incomplete is not None + assert "replay bounds" in bad_cap.incomplete + bad_art = bad_cap.artifact(ok_term.snapshot()) + bad_text, bad_matched = _format_replay( + json.dumps(bad_art).encode("utf-8"), None + ) + assert bad_matched is False + assert "Replay unavailable" in bad_text