diff --git a/CHANGES b/CHANGES index db4b065..af1e979 100644 --- a/CHANGES +++ b/CHANGES @@ -26,6 +26,17 @@ scrubbers = [(r"pid=\d+ +", "pid= ")] See {ref}`topics-testing` for runnable examples. +### What's new + +#### Scrub filesystem paths with path objects (#150) + +{func}`~libvt.testing.vt_screen`, {func}`~libvt.testing.serialize_vt_snapshot`, +and {meth}`~libvt.contrib.syrupy.VtSnapshotExtension.configure` accept +{class}`os.PathLike` values such as pytest's `tmp_path`. A +{class}`pathlib.PureWindowsPath` matches both path separators and either case +of a drive letter. Use an explicit regex for paths inside URIs. When using +`region=`, pass the source frame to account for cropped URI text. + ### Fixes #### Keep erased viewport text separate from scrollback (#149) diff --git a/MIGRATION b/MIGRATION index 0055ea3..e7da0f5 100644 --- a/MIGRATION +++ b/MIGRATION @@ -23,6 +23,14 @@ fixed-width field. For logical text from a line-oriented command, scrub the output of {func}`~libvt.terminal.strip`. Use {ref}`topics-testing` for runnable examples. +### Scrubbing paths and file URIs (#150) + +When switching a snapshot scrubber from a regex to a path object, pass a +separate rule for each URI you want to scrub. For a local absolute +`pathlib.Path` displayed within one row, use +`[(path, ""), (re.escape(path.as_uri()), "")]`. Pass the source +frame with `region=` when a crop omits part of a wrapped URI. + ## libvt 0.0.1a2 (2026-11-28) ### Curated PEP 562 `libvt` root exports (#43) diff --git a/docs/api/testing.md b/docs/api/testing.md index 5684590..ddcfb2d 100644 --- a/docs/api/testing.md +++ b/docs/api/testing.md @@ -31,9 +31,15 @@ immutable {class}`~libvt.terminal.Snapshot` objects, inline .. py:type:: ScrubberSpec :module: libvt.testing - :canonical: tuple[str | re.Pattern[str], str] - - Regex ``(pattern, replacement)`` pair accepted by :func:`~libvt.testing.serialize_vt_snapshot` and :func:`~libvt.testing.vt_screen`. + :canonical: tuple[str | re.Pattern[str] | os.PathLike[str], str] + + ``(pattern, replacement)`` pair. Pass a ``str`` or :class:`re.Pattern` for a + regex, or an :class:`os.PathLike` for a literal path substring outside a URI. + :class:`pathlib.PureWindowsPath` matches either slash and either case of a + leading drive letter. A matching Windows drive path takes precedence over + a one-letter scheme, as in ``c:/Temp``. Supply a regex to match URI text. + URI recognition follows captured soft wraps. Replacements stay within the + visible row. .. py:type:: VtTarget :module: libvt.testing diff --git a/docs/topics/testing.md b/docs/topics/testing.md index aac45f8..a8d4385 100644 --- a/docs/topics/testing.md +++ b/docs/topics/testing.md @@ -136,6 +136,47 @@ styles: r0[0..4]: fg=green ``` +### Scrubbing paths and URIs + +Pass `pytest`'s `tmp_path` or another `os.PathLike[str]` in `scrubbers` to match +its literal spelling outside URIs. A {class}`pathlib.PureWindowsPath` matches slash and +backslash separators and either case of a leading drive letter. + +The serializer uses captured soft wraps to recognize a URI that spans rows. +Pass the original frame with `region=` when the crop omits its prefix. A +standalone {class}`~libvt.screen.RegionView` can use backing columns in its +retained rows. If it starts after a wrapped URI's prefix, a visible +continuation can match a literal path. + +To scrub URI text, add a regex for the displayed spelling on each row. Use +`re.escape(tmp_path.as_uri())` for an unwrapped URI from a +{class}`pathlib.Path`. + +```python +>>> import pathlib +>>> import re +>>> import libvt +>>> from libvt.testing import serialize_vt_snapshot +>>> path = pathlib.PureWindowsPath(r"C:\Temp\run[0]") +>>> uri = "file:///C:/Temp/run%5B0%5D" +>>> term = libvt.Terminal(rows=2, cols=40) +>>> term.feed_str(r"dir=c:/Temp\run[0]\app.log" + "\r\n" + f"uri={uri}/app.log") +>>> scrubbers = [(path, "")] +>>> print(serialize_vt_snapshot(term, scrubbers=scrubbers)) +size=40x2 cursor=(1,38,vis=True) alt=False modes=[] +┌────────────────────────────────────────┐ +│dir=\app.log │ +│uri=file:///C:/Temp/run%5B0%5D/app.log │ +└────────────────────────────────────────┘ +>>> scrubbers.append((re.escape(uri), "")) +>>> print(serialize_vt_snapshot(term, scrubbers=scrubbers)) +size=40x2 cursor=(1,17,vis=True) alt=False modes=[] +┌────────────────────────────────────────┐ +│dir=\app.log │ +│uri=/app.log │ +└────────────────────────────────────────┘ +``` + ### Temporary paths in command output Set the temporary root in the child process environment and give the diff --git a/src/libvt/contrib/syrupy.py b/src/libvt/contrib/syrupy.py index c089012..4ea1466 100644 --- a/src/libvt/contrib/syrupy.py +++ b/src/libvt/contrib/syrupy.py @@ -21,12 +21,12 @@ from syrupy.assertion import SnapshotAssertion from syrupy.extensions.amber import AmberSnapshotExtension - from libvt.testing import ScrubberSpec + from libvt.testing import ScrubberSpec, _CompiledScrubbers class VtSnapshotExtension(AmberSnapshotExtension): """``syrupy`` ``.ambr`` extension for boxed VT and ``SGR`` snapshots.""" - _scrubbers: t.ClassVar[tuple[ScrubberSpec, ...]] + _scrubbers: t.ClassVar[_CompiledScrubbers] _include_cursor_shape: t.ClassVar[bool] _include_styles: t.ClassVar[bool] @@ -66,18 +66,19 @@ def diff_lines( # memoize configured subclasses so repeated configure() calls share class identity. @functools.lru_cache(maxsize=64) def _build_extension_class( - scrubbers: tuple[ScrubberSpec, ...] = (), + scrubbers: _CompiledScrubbers = (), *, include_cursor_shape: bool = False, include_styles: bool = True, ) -> type[t.Any]: from libvt.testing import ( VtScreenView, + _compile_scrubbers, _convert_nested, _extract_target, _serialize_extracted, + _serialize_view, format_vt_diff_lines, - serialize_vt_snapshot, ) amber_mod = importlib.import_module("syrupy.extensions.amber") @@ -126,7 +127,8 @@ def configure( Parameters ---------- scrubbers : Sequence[ScrubberSpec] | None, optional - Replacement ``(pattern, replacement)`` pairs; ``None`` inherits *cls*. + Regex or literal path pairs as defined by + :type:`~libvt.testing.ScrubberSpec`. ``None`` inherits *cls*. include_cursor_shape : bool | None, optional Whether to include cursor shape metadata; ``None`` inherits *cls*. include_styles : bool | None, optional @@ -137,6 +139,13 @@ def configure( type[VtSnapshotExtension] Cached ``AmberSnapshotExtension`` subclass. + Raises + ------ + TypeError + If a scrubber pattern has an invalid type. + ValueError + If an :class:`os.PathLike` scrubber resolves to an empty path. + Examples -------- >>> from libvt import Terminal @@ -150,7 +159,7 @@ def configure( True """ return _build_extension_class( - cls._scrubbers if scrubbers is None else tuple(scrubbers), + cls._scrubbers if scrubbers is None else _compile_scrubbers(scrubbers), include_cursor_shape=( cls._include_cursor_shape if include_cursor_shape is None @@ -186,7 +195,7 @@ def serialize( resolved = matcher(data=data, path=()) if callable(matcher) else data rendered: str | None = None if isinstance(resolved, VtScreenView): - rendered = serialize_vt_snapshot( + rendered = _serialize_view( resolved, scrubbers=self._scrubbers, include_cursor_shape=self._include_cursor_shape, diff --git a/src/libvt/testing.py b/src/libvt/testing.py index e44b4f7..3d872cb 100644 --- a/src/libvt/testing.py +++ b/src/libvt/testing.py @@ -5,10 +5,12 @@ import collections.abc import difflib import itertools +import os +import pathlib import re import textwrap import typing as t -from dataclasses import dataclass +from dataclasses import dataclass, field from libvt._grid import raw_width_bits from libvt._ucd import ( @@ -416,7 +418,52 @@ class _SupportsCaptureVt(t.Protocol): def capture_vt(self) -> TmuxCaptureResult: ... -type ScrubberSpec = tuple[str | re.Pattern[str], str] +type ScrubberSpec = tuple[str | re.Pattern[str] | os.PathLike[str], str] + + +_URI = re.compile( + r"(?"\\^`{|}]*""" +) + + +@dataclass(frozen=True, slots=True) +class _PathPattern: + """Match a filesystem spelling in the text between URI tokens.""" + + pattern: re.Pattern[str] + drive_spelling: bool + + def outside_uris( + self, text: str, before: str + ) -> collections.abc.Iterator[tuple[int, int]]: + scope = before + text + offset = len(before) + start = 0 + for uri in _URI.finditer(scope, offset): + # A matching Windows drive can begin with the same bytes as a URI scheme. + if ( + self.drive_spelling + and self.pattern.match(scope, uri.start()) + and not scope.startswith("//", uri.start() + 2) + ): + continue + yield start, uri.start() - offset + start = uri.end() - offset + yield start, len(text) + + +type _CompiledScrubbers = tuple[tuple[re.Pattern[str] | _PathPattern, str], ...] +# A URI column can carry the start column of an ambiguous drive spelling. +type _UriColumns = dict[int, int | None] + + +@dataclass(slots=True) +class _UriContext: + before: str = "" + columns: _UriColumns = field(default_factory=dict) + + type VtTarget = ( Terminal | Snapshot @@ -445,8 +492,8 @@ class VtScreenView: Optional baseline terminal or snapshot target; when set, serialization emits only the compact contextual delta from *diff* to *target*. scrubbers : tuple[ScrubberSpec, ...] - Regex ``(pattern, replacement)`` pairs applied on top of any caller or - extension scrubbers to the text of each visible row. + Regex or literal path pairs applied after caller or extension scrubbers. + The view resolves each path once. Equality uses the compiled rules. region : tuple[int, int, int, int] | None Optional ``(start_row, end_row, start_col, end_col)`` slice extracted from *target* (and *diff* when given) prior to serialization. @@ -474,10 +521,17 @@ class VtScreenView: target: VtTarget diff: VtTarget | VtScreenView | None = None - scrubbers: tuple[ScrubberSpec, ...] = () + scrubbers: tuple[ScrubberSpec, ...] = field(default=(), compare=False) region: tuple[int, int, int, int] | None = None include_styles: bool | None = None include_cursor_shape: bool | None = None + _compiled_scrubbers: _CompiledScrubbers = field(init=False, repr=False) + + def __post_init__(self) -> None: + """Bind path providers for equality and for both frames of a diff.""" + object.__setattr__( + self, "_compiled_scrubbers", _compile_scrubbers(self.scrubbers) + ) def vt_screen( @@ -499,7 +553,7 @@ def vt_screen( Previous terminal or snapshot state; when provided, serializes only the contextual diff between *diff* and *target* (``"(unchanged)"`` when equal). scrubbers : Sequence[ScrubberSpec], optional - Additional ``(pattern, replacement)`` scrubbers applied within each row. + Additional :type:`ScrubberSpec` pairs applied within each visible row. region : tuple[int, int, int, int] | None, optional Half-open ``(start_row, end_row, start_col, end_col)`` viewport slice. Replacement glyphs use the source frame's width settings. @@ -541,13 +595,48 @@ class _CellMeta: source: tuple[int, Cell] | None = None +def _compile_scrubber_pattern( + pat: str | re.Pattern[str] | os.PathLike[str], +) -> re.Pattern[str] | _PathPattern: + if isinstance(pat, str): + return re.compile(pat) + if isinstance(pat, re.Pattern): + if not isinstance(pat.pattern, str): + msg = "Expected str regex pattern for scrubber, got bytes pattern" + raise TypeError(msg) + return pat + if isinstance(pat, os.PathLike): + raw: str | bytes = os.fspath(pat) + if not isinstance(raw, str): + msg = f"Expected str path from PathLike scrubber, got {type(raw).__name__}" + raise TypeError(msg) + if not raw: + msg = "PathLike scrubber path must not be empty" + raise ValueError(msg) + windows = isinstance(pat, pathlib.PureWindowsPath) + drive_spelling = ( + raw[1:2] == ":" + and raw[0].isascii() + and raw[0].isalpha() + and (windows or raw[2:3] == "\\") + ) + if windows: + parts = raw.replace("\\", "/").split("/") + pattern = r"[\\/]".join(re.escape(part) for part in parts) + if drive_spelling: + letter = raw[0].lower() + pattern = f"[{letter}{letter.upper()}]{pattern[1:]}" + else: + pattern = re.escape(raw) + return _PathPattern(re.compile(pattern), drive_spelling=drive_spelling) + msg = f"Expected str, re.Pattern, or os.PathLike scrubber, got {type(pat).__name__}" + raise TypeError(msg) + + def _compile_scrubbers( scrubbers: collections.abc.Sequence[ScrubberSpec], -) -> tuple[tuple[re.Pattern[str], str], ...]: - return tuple( - (re.compile(pat) if isinstance(pat, str) else pat, repl) - for pat, repl in scrubbers - ) +) -> _CompiledScrubbers: + return tuple((_compile_scrubber_pattern(pat), repl) for pat, repl in scrubbers) def _format_style_token(style: Style, hyperlink: Hyperlink | None) -> str: @@ -676,15 +765,141 @@ def _cursor_text_offset( return pos, max(0, target_col - col) +def _captured_uri_contexts( + source: Snapshot | Screen | RegionView, first: int, stop: int, col_start: int +) -> list[_UriContext]: + result = [_UriContext() for _ in range(first, stop)] + if not result: + return result + + # Follow only recorded wraps in the source viewport. + start = first + while start > 0 and source[start - 1].wrapped: + start -= 1 + end = stop + while end < source.rows and source[end - 1].wrapped: + end += 1 + + chars: list[str] = [] + positions: list[tuple[int, int]] = [] + for r in range(start, end): + backing = source[r]._current_row() + row = RowView(backing) + context = result[r - first] if first <= r < stop else None + if context is not None: + context.before = chars[-1][-1:] if chars else "" + if col_start > backing.used: + context.before = " " + for col in range(min(backing.used, len(row))): + cell = row[col] + if cell.width: + text = sanitize_terminal_text(cell.text) + chars.append(text) + positions.extend([(r, col)] * len(text)) + if context is not None and col < col_start <= backing.used and text: + context.before = text[-1:] + if row.wrapped and r + 1 < end: + if backing.used < len(row): + # An unwritten gap still separates tokens. + chars.append(" ") + positions.append((r, backing.used)) + continue + + chain = "".join(chars) + for uri in _URI.finditer(chain): + origin_row, origin_col = positions[uri.start()] + explicit_uri = chain.startswith("//", uri.start() + 2) + for uri_row, uri_col in positions[uri.start() : uri.end()]: + if first <= uri_row < stop: + columns = result[uri_row - first].columns + columns[uri_col] = ( + origin_col + if uri_row == origin_row and not explicit_uri + else None + ) + chars.clear() + positions.clear() + return result + + +def _captured_uri_overlap( + match: re.Match[str], + cells: list[_CellMeta], + uri_columns: _UriColumns, + col_start: int, + *, + drive_spelling: bool, +) -> int | None: + first = cells[match.start()].source + drive_col = first[0] + col_start if drive_spelling and first is not None else None + for index in range(match.start(), match.end()): + source = cells[index].source + if source is None: + continue + col = source[0] + col_start + if col in uri_columns and (drive_col is None or uri_columns[col] != drive_col): + return index + return None + + +def _path_matches( + pattern: _PathPattern, + text: str, + cells: list[_CellMeta], + context: _UriContext, + col_start: int, + *, + edited: bool, +) -> collections.abc.Iterator[re.Match[str]]: + ranges = pattern.outside_uris(text, context.before) if edited else ((0, len(text)),) + for start, stop in ranges: + while (match := pattern.pattern.search(text, start, stop)) is not None: + overlap = ( + _captured_uri_overlap( + match, + cells, + context.columns, + col_start, + drive_spelling=pattern.drive_spelling, + ) + if context.columns + else None + ) + if overlap is None: + yield match + start = match.end() + else: + # An overlapping candidate can start past the protected cells. + start = (match.start() if pattern.drive_spelling else overlap) + 1 + + def _scrub_cells( cells: list[_CellMeta], - compiled: tuple[tuple[re.Pattern[str], str], ...], + compiled: _CompiledScrubbers, cursor_idx: int | None, + *, + uri_context: _UriContext | None, + col_start: int, ) -> tuple[list[_CellMeta], int | None]: + original = cells cur = cursor_idx for pat, raw_repl in compiled: repl = sanitize_terminal_text(raw_repl) - matches = list(pat.finditer("".join(c.ch for c in cells))) + text = "".join(c.ch for c in cells) + if isinstance(pat, _PathPattern): + assert uri_context is not None + matches = list( + _path_matches( + pat, + text, + cells, + uri_context, + col_start, + edited=cells is not original and cells != original, + ) + ) + else: + matches = list(pat.finditer(text)) if not matches: continue out: list[_CellMeta] = [] @@ -776,7 +991,8 @@ def _render_scrubbed_row( def _render_fixed_rows( view: Snapshot | Screen | RegionView, *, - compiled: tuple[tuple[re.Pattern[str], str], ...], + compiled: _CompiledScrubbers, + uri_rows: collections.abc.Sequence[_UriContext], cur_row: int | None, cur_col: int, include_styles: bool, @@ -796,7 +1012,14 @@ def _render_fixed_rows( cursor_idx, extra = _cursor_text_offset( cells, cur_col, mode_2027=mode_2027, profile=profile ) - scrubbed, cursor_idx = _scrub_cells(cells, compiled, cursor_idx) + col_start = row._col_range.start + scrubbed, cursor_idx = _scrub_cells( + cells, + compiled, + cursor_idx, + uri_context=uri_rows[r] if uri_rows else None, + col_start=col_start, + ) if scrubbed != cells: text, spans, mapped = _render_scrubbed_row( scrubbed, @@ -810,7 +1033,6 @@ def _render_fixed_rows( out_col = mapped else: text = sanitize_terminal_text(row.display_text) - col_start = row._col_range.start spans = [ f"[{run.start_col - col_start}..{run.end_col - col_start}]: " f"{_format_style_token(run.style, run.hyperlink)}" @@ -888,7 +1110,8 @@ def serialize_vt_snapshot( or duck-typed pane wrapper exposing ``.terminal``, ``.snapshot()``, or ``.capture_vt()``. scrubbers : Sequence[ScrubberSpec], optional - Regex ``(pattern, replacement)`` pairs applied to each visible row. + Regex or literal path pairs applied to each visible row. + See :type:`ScrubberSpec` for path matching rules. Replacements shift the rest of that row and remap its cursor column. Insertions shift a cursor at the insertion point with its cell. Text is clipped to the captured width at glyph boundaries. @@ -908,7 +1131,10 @@ def serialize_vt_snapshot( ------ TypeError If *target* (or a :class:`VtScreenView`'s inner target) is not a supported - terminal, snapshot, screen, region, or pane wrapper. + terminal, snapshot, screen, region, or pane wrapper, or if a pattern has + an invalid type. + ValueError + If a path provider returns an empty string. Examples -------- @@ -926,56 +1152,12 @@ def serialize_vt_snapshot( r0[0..5]: bold fg=green """ if isinstance(target, VtScreenView): - merged_scrubbers = (*scrubbers, *target.scrubbers) - eff_styles = ( - include_styles if target.include_styles is None else target.include_styles - ) - eff_shape = ( - include_cursor_shape - if target.include_cursor_shape is None - else target.include_cursor_shape - ) - cur_ext = _extract_target(target.target) - if cur_ext is None: - msg = ( - "Expected Terminal, Snapshot, Screen, RegionView, or VT pane wrapper, " - f"got {type(target.target).__name__}" - ) - raise TypeError(msg) - cur_str = _serialize_extracted( - cur_ext, - region=target.region, - scrubbers=merged_scrubbers, - include_cursor_shape=eff_shape, - include_styles=eff_styles, + return _serialize_view( + target, + scrubbers=_compile_scrubbers(scrubbers), + include_cursor_shape=include_cursor_shape, + include_styles=include_styles, ) - if target.diff is not None: - base_ext = _extract_target(target.diff) - if base_ext is None: - msg = ( - "Expected Terminal, Snapshot, Screen, RegionView, or VT pane " - f"wrapper for diff, got {type(target.diff).__name__}" - ) - raise TypeError(msg) - base_str = _serialize_extracted( - base_ext, - region=target.region, - scrubbers=merged_scrubbers, - include_cursor_shape=eff_shape, - include_styles=eff_styles, - ) - if cur_str == base_str: - return "(unchanged)" - return "\n".join( - format_vt_diff_lines( - cur_str, - base_str, - color=False, - context_lines=2, - ) - ) - return cur_str - extracted = _extract_target(target) if extracted is None: msg = ( @@ -985,32 +1167,97 @@ def serialize_vt_snapshot( raise TypeError(msg) return _serialize_extracted( extracted, - scrubbers=scrubbers, + scrubbers=_compile_scrubbers(scrubbers), include_cursor_shape=include_cursor_shape, include_styles=include_styles, ) +def _serialize_view( + target: VtScreenView, + *, + scrubbers: _CompiledScrubbers, + include_cursor_shape: bool, + include_styles: bool, +) -> str: + merged_scrubbers = (*scrubbers, *target._compiled_scrubbers) + eff_styles = ( + include_styles if target.include_styles is None else target.include_styles + ) + eff_shape = ( + include_cursor_shape + if target.include_cursor_shape is None + else target.include_cursor_shape + ) + cur_ext = _extract_target(target.target) + if cur_ext is None: + msg = ( + "Expected Terminal, Snapshot, Screen, RegionView, or VT pane wrapper, " + f"got {type(target.target).__name__}" + ) + raise TypeError(msg) + cur_str = _serialize_extracted( + cur_ext, + region=target.region, + scrubbers=merged_scrubbers, + include_cursor_shape=eff_shape, + include_styles=eff_styles, + ) + if target.diff is not None: + base_ext = _extract_target(target.diff) + if base_ext is None: + msg = ( + "Expected Terminal, Snapshot, Screen, RegionView, or VT pane " + f"wrapper for diff, got {type(target.diff).__name__}" + ) + raise TypeError(msg) + base_str = _serialize_extracted( + base_ext, + region=target.region, + scrubbers=merged_scrubbers, + include_cursor_shape=eff_shape, + include_styles=eff_styles, + ) + if cur_str == base_str: + return "(unchanged)" + return "\n".join( + format_vt_diff_lines( + cur_str, + base_str, + color=False, + context_lines=2, + ) + ) + return cur_str + + def _serialize_extracted( extracted: tuple[Snapshot | Screen | RegionView, set[str]], *, region: tuple[int, int, int, int] | None = None, - scrubbers: collections.abc.Sequence[ScrubberSpec] = (), + scrubbers: _CompiledScrubbers = (), include_cursor_shape: bool = False, include_styles: bool = True, ) -> str: source, unexposed = extracted - compiled = _compile_scrubbers(scrubbers) profile = DEFAULT_PROFILE if isinstance(source, RegionView) else source._profile mode_2027 = ( not isinstance(source, Snapshot) or Mode.GRAPHEME_CLUSTERING in source.modes ) view = source if region is None else _slice_view(source, region) + uri_rows: collections.abc.Sequence[_UriContext] = () + if any(isinstance(pattern, _PathPattern) for pattern, _ in scrubbers): + first = ( + 0 if region is None else slice(region[0], region[1]).indices(source.rows)[0] + ) + col_start = view._col_range.start if isinstance(view, RegionView) else 0 + uri_rows = _captured_uri_contexts(source, first, first + view.rows, col_start) if isinstance(view, RegionView): box, style_lines, _ = _render_fixed_rows( view, - compiled=compiled, + compiled=scrubbers, + uri_rows=uri_rows, cur_row=None, cur_col=0, include_styles=include_styles, @@ -1029,7 +1276,8 @@ def _serialize_extracted( cursor = view.cursor box, style_lines, cur_col = _render_fixed_rows( view, - compiled=compiled, + compiled=scrubbers, + uri_rows=uri_rows, cur_row=cursor.row, cur_col=cursor.col, include_styles=include_styles, @@ -1260,12 +1508,12 @@ def format_vt_diff_lines( def _convert_nested( value: object, *, - scrubbers: tuple[ScrubberSpec, ...], + scrubbers: _CompiledScrubbers, include_cursor_shape: bool, include_styles: bool, ) -> object: if isinstance(value, VtScreenView): - return serialize_vt_snapshot( + return _serialize_view( value, scrubbers=scrubbers, include_cursor_shape=include_cursor_shape, diff --git a/tests/test_syrupy.py b/tests/test_syrupy.py index 4e47c25..96ca4bd 100644 --- a/tests/test_syrupy.py +++ b/tests/test_syrupy.py @@ -7,6 +7,7 @@ import importlib.util import os import pathlib +import re import subprocess import sys @@ -17,7 +18,7 @@ get_vt_snapshot_extension, ) from libvt.terminal import Snapshot, Terminal -from libvt.testing import format_vt_diff_lines, vt_screen +from libvt.testing import format_vt_diff_lines, serialize_vt_snapshot, vt_screen def _child_env() -> dict[str, str]: @@ -146,6 +147,32 @@ def test_configure_lru_cache_and_nested_containers() -> None: assert c1 is c2 assert c1.configure(scrubbers=())._scrubbers == () + class _UnhashablePathLike: + __hash__ = None # type: ignore[assignment] + + def __init__(self, raw: str) -> None: + self._raw = raw + + def __fspath__(self) -> str: + return self._raw + + p_dir = pathlib.PurePosixPath("/tmp/work[0]/c++") + cp1 = ext_cls.configure(scrubbers=[(p_dir, "")]) + cp2 = ext_cls.configure( + scrubbers=[(_UnhashablePathLike("/tmp/work[0]/c++"), "")] + ) + assert cp1 is cp2 + t_path = Terminal(rows=1, cols=32) + t_path.feed_str("log=/tmp/work[0]/c++/run.log") + assert "│log=/run.log" in cp1().serialize(t_path) + + class _EmptyPath: + def __fspath__(self) -> str: + return "" + + with pytest.raises(ValueError, match="must not be empty"): + ext_cls.configure(scrubbers=[(_EmptyPath(), "")]) + t_prev = Terminal(rows=2, cols=14) t_prev.feed(b"Menu: [A] B") t_next = Terminal(rows=2, cols=14) @@ -168,6 +195,79 @@ def snapshot(self) -> Snapshot: _ = __import__("libvt.contrib.syrupy", fromlist=["_missing"])._missing +def test_configure_pathlike_and_unhashable_scrubbers( + tmp_path: pathlib.Path, +) -> None: + """``VtSnapshotExtension.configure()`` normalizes ``PathLike`` scrubbers.""" + + class _UnhashablePath(os.PathLike[str]): + def __init__(self, path: str) -> None: + self.path = path + + def __fspath__(self) -> str: + return self.path + + def __eq__(self, other: object) -> bool: + return isinstance(other, _UnhashablePath) and self.path == other.path + + work_dir = tmp_path / "run[0]" / "c++" + unhashable = _UnhashablePath(os.fspath(work_dir)) + with pytest.raises(TypeError, match="unhashable"): + hash(unhashable) + + win_tmp = pathlib.PureWindowsPath(r"C:\Temp\job") + scrubbers = [(unhashable, ""), (win_tmp, "")] + ext_a = VtSnapshotExtension.configure(scrubbers=scrubbers) + ext_b = VtSnapshotExtension.configure( + scrubbers=[ + (_UnhashablePath(os.fspath(work_dir)), ""), + (pathlib.PureWindowsPath(r"c:\Temp\job"), ""), + ], + ) + assert ext_a is ext_b + assert ext_a.configure() is ext_a + assert ( + VtSnapshotExtension.configure( + scrubbers=[ + (unhashable, ""), + (pathlib.PureWindowsPath(r"C:\temp\job"), ""), + ] + ) + is not ext_a + ) + + uri = "file:///C:/Temp/job" + lines = [f"work={work_dir}/run.log", "win=c:/Temp/job/a.log", f"uri={uri}/a.log"] + term = Terminal(rows=3, cols=2 * max(map(len, lines))) + term.feed_str("\r\n".join(lines)) + rendered = ext_a().serialize(term) + assert rendered == serialize_vt_snapshot(term, scrubbers=scrubbers) + assert "│work=/run.log" in rendered + assert "│win=/a.log" in rendered + assert f"│uri={uri}/a.log" in rendered + explicit = ext_a().serialize(vt_screen(term, scrubbers=[(re.escape(uri), "")])) + assert "│uri=/a.log" in explicit + + +def test_configure_scrubber_pattern_validation() -> None: + """Reject invalid scrubbers before looking up the configured extension.""" + + class _EmptyPath: + def __fspath__(self) -> str: + return "" + + class _BytesPath: + def __fspath__(self) -> bytes: + return b"/tmp/raw" + + with pytest.raises(ValueError, match="must not be empty"): + VtSnapshotExtension.configure(scrubbers=[(_EmptyPath(), "")]) + with pytest.raises(TypeError, match="PathLike"): + VtSnapshotExtension.configure(scrubbers=[(_BytesPath(), "")]) # ty: ignore[invalid-argument-type] + with pytest.raises(TypeError, match="scrubber"): + VtSnapshotExtension.configure(scrubbers=[(123, "")]) # ty: ignore[invalid-argument-type] + + def test_default_pytest_truncation_pty_colors_and_ci_carets( tmp_path: pathlib.Path, ) -> None: diff --git a/tests/test_testing.py b/tests/test_testing.py index f01a612..01cb345 100644 --- a/tests/test_testing.py +++ b/tests/test_testing.py @@ -872,3 +872,511 @@ def test_live_tmux_server_vs_pure_terminal_snapshot_parity( capture_output=True, check=False, ) + + +def test_pathlike_literal_scrubbers_and_validation( + tmp_path: pathlib.Path, +) -> None: + """``os.PathLike`` scrubbers escape literal paths without URI magic.""" + win_tmp = pathlib.PureWindowsPath(r"C:\Users\runner\Temp\test[0]") + win_uri = "file:///C:/Users/runner/Temp/test%5B0%5D" + + t_win = Terminal(rows=4, cols=60) + t_win.feed_str( + "raw=C:\\Users\\runner\\Temp\\test[0]\\a.log\r\n" + "low=c:/Users/runner/Temp/test[0]/a.log\r\n" + "mix=C:\\Users/runner/Temp\\test[0]\\a.log\r\n" + f"uri={win_uri}/a.log" + ) + out_literal_only = serialize_vt_snapshot(t_win, scrubbers=[(win_tmp, "")]) + assert r"│raw=\a.log" in out_literal_only + assert "│low=/a.log" in out_literal_only + assert r"│mix=\a.log" in out_literal_only + # Percent-encoded [0] in file:// URI stays untouched without explicit as_uri() rule. + assert "test%5B0%5D" in out_literal_only + + out_with_uri = serialize_vt_snapshot( + t_win, + scrubbers=[ + (re.escape(win_uri), "file://"), + (win_tmp, ""), + ], + ) + assert "│uri=file:///a.log" in out_with_uri + + unc_tmp = pathlib.PureWindowsPath(r"\\srv\share\dir[0]") + t_unc = Terminal(rows=1, cols=40) + t_unc.feed_str(r"unc=\\srv\share\dir[0]\ok") + assert r"│unc=\ok" in serialize_vt_snapshot( + t_unc, scrubbers=[(unc_tmp, "")] + ) + + meta_dir = tmp_path / "test_sync[jobs=2]" / "c++" + meta_uri = meta_dir.as_uri() + literal = f"dir={meta_dir}/out(1).log pid=42" + uri = f"uri={meta_uri}/out" + t_posix = Terminal(rows=2, cols=max(len(line.encode()) for line in (literal, uri))) + t_posix.feed_str(f"{literal}\r\n{uri}") + out_posix = serialize_vt_snapshot( + vt_screen( + t_posix, + scrubbers=[ + (re.escape(meta_uri), "file://"), + (meta_dir, ""), + (r"\(\d+\)", "()"), + (re.compile(r"pid=\d+"), "pid="), + ], + ) + ) + assert "│dir=/out().log pid=" in out_posix + assert "│uri=file:///out" in out_posix + + class _EmptyPath: + def __fspath__(self) -> str: + return "" + + class _BytesPath: + def __fspath__(self) -> bytes: + return b"/tmp/raw" + + with pytest.raises(ValueError, match="must not be empty"): + serialize_vt_snapshot(t_posix, scrubbers=[(_EmptyPath(), "")]) + with pytest.raises(TypeError, match="PathLike"): + serialize_vt_snapshot(t_posix, scrubbers=[(_BytesPath(), "")]) # ty: ignore[invalid-argument-type] + with pytest.raises(TypeError, match="bytes pattern"): + serialize_vt_snapshot(t_posix, scrubbers=[(re.compile(b"raw"), "")]) # ty: ignore[invalid-argument-type] + with pytest.raises(TypeError, match="scrubber"): + serialize_vt_snapshot(t_posix, scrubbers=[(123, "")]) # ty: ignore[invalid-argument-type] + + +@pytest.mark.parametrize( + ("path", "visible", "expected"), + [ + ( + pathlib.PureWindowsPath(r"C:\Temp\run[0]"), + r"C:\Temp\run[0]\log", + r"\log", + ), + ( + pathlib.PureWindowsPath(r"C:\Temp\run[0]"), + r"c:\Temp/run[0]/log", + "/log", + ), + (pathlib.PureWindowsPath("C:run[0]"), "c:run[0]/log", "/log"), + ( + pathlib.PureWindowsPath(r"\\srv\share\run[0]"), + "//srv/share/run[0]/log", + "/log", + ), + ( + pathlib.PureWindowsPath(r"C:\Temp\run[0]"), + "C:/temp/run[0]/log", + "C:/temp/run[0]/log", + ), + ( + pathlib.PurePosixPath(r"/tmp/run[0]\c++"), + r"/tmp/run[0]\c++/log", + "/log", + ), + ( + pathlib.PurePosixPath(r"/tmp/run[0]\c++"), + "/tmp/run[0]/c++/log", + "/tmp/run[0]/c++/log", + ), + ( + pathlib.PurePosixPath("/tmp/run"), + "file:///tmp/run/log", + "file:///tmp/run/log", + ), + (pathlib.PurePosixPath("/tmp/run"), "file:/tmp/run", "file:/tmp/run"), + ( + pathlib.PurePosixPath("/tmp/run"), + "https://x?q=/tmp/run", + "https://x?q=/tmp/run", + ), + (pathlib.PurePosixPath("/tmp/run"), "x:/tmp/run", "x:/tmp/run"), + (pathlib.PurePosixPath("/tmp/run"), "X:one/tmp/run", "X:one/tmp/run"), + (pathlib.PureWindowsPath("X:/tmp"), "z:one/x:/tmp", "z:one/x:/tmp"), + (pathlib.PurePosixPath("file"), "file:", "file:"), + (pathlib.PurePosixPath("/tmp/a:b"), "/tmp/a:b", ""), + (pathlib.PurePosixPath("file=/tmp"), "file=/tmp", ""), + (pathlib.PurePosixPath("dir=file:/tmp"), "dir=file:/tmp", "dir=file:/tmp"), + ], +) +def test_pathlike_scrubbers_match_literal_paths( + path: pathlib.PurePath, visible: str, expected: str +) -> None: + """Match literal path spellings with Windows separator and drive variants.""" + term = Terminal(rows=1, cols=32) + term.feed_str(f"dir={visible}") + rendered = serialize_vt_snapshot(term, scrubbers=[(path, "")]) + row = f"dir={expected}" + assert rendered.splitlines() == [ + f"size=32x1 cursor=(0,{len(row)},vis=True) alt=False modes=[]", + "┌" + "─" * 32 + "┐", + f"│{row:<32}│", + "└" + "─" * 32 + "┘", + ] + + +def test_pathlike_scrubbers_leave_uri_encoding_to_caller( + tmp_path: pathlib.Path, +) -> None: + """Scrub a real ``tmp_path`` and let a caller-supplied regex match its URI.""" + path = tmp_path / "run[0]" / "c++" + uri = path.as_uri() + lines = [f"dir={path}/out(1).log pid=42", f"uri={uri}/out"] + term = Terminal(rows=2, cols=2 * max(map(len, lines))) + term.feed_str("\r\n".join(lines)) + view = vt_screen( + term, + scrubbers=[ + (path, ""), + (r"\(\d+\)", "()"), + (re.compile(r"pid=\d+"), "pid="), + ], + ) + rendered = serialize_vt_snapshot(view) + assert "│dir=/out().log pid=" in rendered + assert f"│uri={uri}/out" in rendered + explicit = serialize_vt_snapshot(view, scrubbers=[(re.escape(uri), "")]) + assert "│uri=/out" in explicit + assert term.text == "\n".join(lines) + + +def test_path_scrubbers_skip_uri_spans() -> None: + """Leave the URI intact between two matches, including its displayed Unicode.""" + path = pathlib.PurePosixPath("/tmp/run") + uri = "https://host/日/tmp/run" + term = Terminal(rows=1, cols=48) + term.feed_str(f"{path} {uri} {path}") + frame = term.snapshot() + view = vt_screen(frame, scrubbers=[(path, "X")]) + plain = serialize_vt_snapshot(view) + assert plain.splitlines() == [ + "size=48x1 cursor=(0,27,vis=True) alt=False modes=[]", + "┌" + "─" * 48 + "┐", + "│X https://host/日/tmp/run X" + " " * 21 + "│", + "└" + "─" * 48 + "┘", + ] + explicit = serialize_vt_snapshot(view, scrubbers=[(re.escape(uri), "URI")]) + assert explicit.splitlines() == [ + "size=48x1 cursor=(0,7,vis=True) alt=False modes=[]", + "┌" + "─" * 48 + "┐", + "│X URI X" + " " * 41 + "│", + "└" + "─" * 48 + "┘", + ] + + +_URI_SCRUBBERS = ((pathlib.PurePosixPath("/tmp/run"), "

"),) +_URI_TOP = "┌──────────┐" +_URI_BOTTOM = "└──────────┘" + + +@pytest.mark.parametrize("alternate", [False, True], ids=["primary", "alternate"]) +@pytest.mark.parametrize("split", [False, True], ids=["whole", "bytewise"]) +def test_wrapped_uri_uses_the_retained_frame(alternate: bool, split: bool) -> None: + """Keep styled URI cells in both buffers and in crops of the original frame.""" + term = Terminal(rows=2, cols=10) + wire = (b"\x1b[?1049h" if alternate else b"") + b"\x1b[32mfile:///ab/tmp/run\x1b[0m" + for chunk in tuple(bytes([byte]) for byte in wire) if split else (wire,): + term.feed(chunk) + frame = term.snapshot() + assert frame.lines == ("file:///ab", "/tmp/run") + assert tuple(row.wrapped for row in frame) == (True, False) + assert (frame.cursor.row, frame.cursor.col) == (1, 8) + + box = [_URI_TOP, "│file:///ab│W", "│/tmp/run │", _URI_BOTTOM] + expected = [ + f"size=10x2 cursor=(1,8,vis=True) alt={alternate} modes=[]", + *box, + "styles:", + " r0[0..10]: fg=green", + " r1[0..8]: fg=green", + ] + for source in (term, term.screen, frame): + assert ( + serialize_vt_snapshot(source, scrubbers=_URI_SCRUBBERS).splitlines() + == expected + ) + + crop = (1, 2, 0, 10) + expected_crop = [ + "size=10x1 region=True", + _URI_TOP, + "│/tmp/run │", + _URI_BOTTOM, + "styles:", + " r0[0..8]: fg=green", + ] + for source in (term, term.screen, frame, frame[0:2]): + assert ( + serialize_vt_snapshot( + vt_screen(source, region=crop, scrubbers=_URI_SCRUBBERS) + ).splitlines() + == expected_crop + ) + + assert serialize_vt_snapshot(frame[0:2], scrubbers=_URI_SCRUBBERS).splitlines()[ + 2:4 + ] == [ + "│file:///ab│", + "│/tmp/run │", + ] + assert ( + serialize_vt_snapshot(frame[1:2], scrubbers=_URI_SCRUBBERS).splitlines()[2] + == "│

│" + ) + + explicit = vt_screen( + frame, + region=crop, + scrubbers=[*_URI_SCRUBBERS, (re.compile(r"^/tmp/run$"), "")], + ) + assert serialize_vt_snapshot(explicit).splitlines()[2:] == [ + "│ │", + _URI_BOTTOM, + "styles:", + " r0[0..5]: fg=green", + ] + term.feed(b"\x1b[2;1HX") + assert frame.lines == ("file:///ab", "/tmp/run") + assert frame.cursor.col == 8 + assert ( + serialize_vt_snapshot(frame, scrubbers=_URI_SCRUBBERS).splitlines() == expected + ) + + +def test_horizontal_crop_uses_captured_uri_prefix() -> None: + """A horizontal region can still see the URI prefix in its backing row.""" + term = Terminal(rows=1, cols=16) + term.feed(b"\x1b[32mfile:///tmp/run") + frame = term.snapshot() + for target in (frame[0:1, 7:15], vt_screen(frame, region=(0, 1, 7, 15))): + assert serialize_vt_snapshot(target, scrubbers=_URI_SCRUBBERS).splitlines() == [ + "size=8x1 region=True", + "┌────────┐", + "│/tmp/run│", + "└────────┘", + "styles:", + " r0[0..8]: fg=green", + ] + + +def test_uri_stops_at_a_hard_row_boundary() -> None: + """A hard line break starts a separate path match.""" + term = Terminal(rows=2, cols=10) + term.feed(b"file:///ab\r\n/tmp/run") + assert not term.snapshot()[0].wrapped + result = serialize_vt_snapshot( + vt_screen(term, region=(1, 2, 0, 10), scrubbers=_URI_SCRUBBERS) + ) + assert result.splitlines() == [ + "size=10x1 region=True", + _URI_TOP, + "│

│", + _URI_BOTTOM, + ] + + +@pytest.mark.parametrize("split", [False, True], ids=["whole", "bytewise"]) +def test_wide_wrap_spacer_keeps_its_uri_context(split: bool) -> None: + """A wide wrap spacer contributes no character to the URI.""" + term = Terminal(rows=2, cols=10) + wire = b"\x1b[32mfile:///x" + "界/tmp/run".encode() + b"\x1b[0m" + for chunk in tuple(bytes([byte]) for byte in wire) if split else (wire,): + term.feed(chunk) + frame = term.snapshot() + assert frame[0].wrapped + assert frame[0, 9].width == 0 and frame[1, 0].width == 2 + assert frame.cursor.pending_wrap + assert serialize_vt_snapshot(frame, scrubbers=_URI_SCRUBBERS).splitlines() == [ + "size=10x2 cursor=(1,9,vis=True) alt=False modes=[]", + _URI_TOP, + "│file:///x │W", + "│界/tmp/run│", + _URI_BOTTOM, + "styles:", + " r0[0..10]: fg=green", + " r1[0..10]: fg=green", + ] + + +def test_one_column_uri_keeps_the_last_cell() -> None: + """A captured wrap can join one-column rows for URI recognition.""" + term = Terminal(rows=9, cols=1) + term.feed(b"file:///x") + region = vt_screen(term, region=(-1, 9, 0, 1)) + assert serialize_vt_snapshot( + region, scrubbers=[(pathlib.PurePosixPath("x"), "Y")] + ).splitlines() == ["size=1x1 region=True", "┌─┐", "│x│", "└─┘"] + + +@pytest.mark.parametrize( + ("visible", "expected"), + [ + (r"C:\Temp\run", "

"), + (r"c:\Temp\run", r"c:\Temp\run"), + ("C:/Temp/run", "C:/Temp/run"), + ], +) +def test_generic_path_provider_matches_its_exact_drive_spelling( + visible: str, expected: str +) -> None: + """Generic path providers match the exact spelling they supply.""" + + class CurrentPath: + def __fspath__(self) -> str: + return r"C:\Temp\run" + + term = Terminal(rows=1, cols=20) + term.feed_str(visible) + actual = serialize_vt_snapshot(term, scrubbers=[(CurrentPath(), "

")]) + assert actual.splitlines()[2] == f"│{expected:20}│" + + +def test_posix_drive_like_path_respects_a_one_letter_uri_scheme() -> None: + """A POSIX spelling with a slash uses the captured URI boundary.""" + term = Terminal(rows=1, cols=16) + visible = "x:/tmp/run" + term.feed_str(visible) + rule = (pathlib.PurePosixPath(visible), "X") + result = serialize_vt_snapshot(term, scrubbers=[rule]) + assert result.splitlines()[2] == f"│{visible:16}│" + + +def test_empty_file_uri_is_not_a_literal_path() -> None: + """The URI guard recognizes an empty URI path.""" + term = Terminal(rows=1, cols=8) + term.feed(b"file:") + result = serialize_vt_snapshot( + term, scrubbers=[(pathlib.PurePosixPath("file"), "X")] + ) + assert result.splitlines()[2] == "│file: │" + + +def test_literal_after_a_uri_remains_a_match() -> None: + """A rejected overlap leaves later literal matches available.""" + term = Terminal(rows=1, cols=24) + term.feed(b"https://h/x /x /x") + result = serialize_vt_snapshot( + term, scrubbers=[(pathlib.PurePosixPath("/x /x"), "X")] + ) + assert result.splitlines()[2] == f"│{'https://h/x X':24}│" + + +def test_crop_does_not_create_a_uri_boundary() -> None: + """An unchanged regex edit leaves a cropped token boundary intact.""" + term = Terminal(rows=1, cols=24) + term.feed(b"/parent/file:/tmp/run") + crop = term.snapshot()[0:1, 8:21] + result = serialize_vt_snapshot( + crop, scrubbers=[(re.compile("$"), ""), *_URI_SCRUBBERS] + ) + assert result.splitlines()[2] == f"│{'file:

':13}│" + + +def test_cropped_token_boundary_survives_an_unrelated_edit() -> None: + """An unrelated regex replacement preserves the captured scheme boundary.""" + term = Terminal(rows=1, cols=26) + term.feed(b"/parent/file:/tmp/run ABC") + source = term.snapshot()[0:1, 8:25] + rendered = serialize_vt_snapshot( + source, scrubbers=[(r"ABC", "DEF"), (pathlib.PurePosixPath("/tmp/run"), "

")] + ) + assert rendered.splitlines()[2] == "│file:

DEF │" + + +def test_new_uri_text_after_a_regex_stays_literal() -> None: + """A path rule respects URI text introduced by an earlier regex.""" + term = Terminal(rows=1, cols=18) + term.feed(b"form=/tmp/run") + rendered = serialize_vt_snapshot( + term, + scrubbers=[(r"^form=", "file:"), (pathlib.PurePosixPath("/tmp/run"), "

")], + ) + assert rendered.splitlines()[2] == "│file:/tmp/run │" + + +def test_hidden_uri_prefix_survives_a_width_change() -> None: + """Track original cells when a replacement shifts the candidate columns.""" + term = Terminal(rows=1, cols=40) + term.feed(b"file:///host/old/tmp/run /tmp/run") + source = term.snapshot()[0:1, 13:35] + rendered = serialize_vt_snapshot( + source, + scrubbers=[(r"^old", "longer"), (pathlib.PurePosixPath("/tmp/run"), "

")], + ) + assert rendered.splitlines()[2] == f"│{'longer/tmp/run

':22}│" + + +def test_hidden_uri_suffix_keeps_the_scheme_after_a_width_change() -> None: + """The backing row still identifies a scheme whose colon is outside the crop.""" + term = Terminal(rows=1, cols=22) + term.feed(b"tag file:/tmp/run") + source = term.snapshot()[0:1, 0:8] + rendered = serialize_vt_snapshot( + source, scrubbers=[(r"^tag", ""), (pathlib.PurePosixPath("file"), "

")] + ) + assert rendered.splitlines()[2] == "│ file │" + + +def test_path_view_equality_uses_the_matcher() -> None: + """Matching drive spellings share a view, while path components retain case.""" + term = Terminal(rows=1, cols=16) + term.feed_str("C:/Temp/job") + path = pathlib.PureWindowsPath("C:/Temp") + view = vt_screen(term, scrubbers=[(path, "X")]) + drive = vt_screen(term, scrubbers=[(pathlib.PureWindowsPath("c:/Temp"), "X")]) + component = vt_screen(term, scrubbers=[(pathlib.PureWindowsPath("C:/temp"), "X")]) + assert view.scrubbers[0][0] is path + assert view == drive + assert len({view, drive, component}) == 2 + assert "│X/job │" in serialize_vt_snapshot(view) + assert "│C:/Temp/job │" in serialize_vt_snapshot(component) + + +def test_a_diff_resolves_each_path_provider_once() -> None: + """Both frames in a diff share the same spelling from a path provider.""" + + class CurrentPath: + def __init__(self) -> None: + self.names = iter(("/first", "/second")) + + def __fspath__(self) -> str: + return next(self.names) + + term = Terminal(rows=1, cols=16) + term.feed_str("/first") + snap = term.snapshot() + assert ( + serialize_vt_snapshot( + vt_screen(snap, diff=snap), scrubbers=[(CurrentPath(), "X")] + ) + == "(unchanged)" + ) + view = vt_screen(term, diff=snap, scrubbers=[(CurrentPath(), "X")]) + assert serialize_vt_snapshot(view) == "(unchanged)" + assert serialize_vt_snapshot(view) == "(unchanged)" + + +def test_scrubber_pattern_validation() -> None: + """Reject empty or non-text path spellings and invalid pattern types.""" + + class _EmptyPath: + def __fspath__(self) -> str: + return "" + + class _BytesPath: + def __fspath__(self) -> bytes: + return b"/tmp/raw" + + term = Terminal(rows=1, cols=8) + with pytest.raises(ValueError, match="must not be empty"): + serialize_vt_snapshot(term, scrubbers=[(_EmptyPath(), "")]) + with pytest.raises(TypeError, match="PathLike"): + serialize_vt_snapshot(term, scrubbers=[(_BytesPath(), "")]) # ty: ignore[invalid-argument-type] + with pytest.raises(TypeError, match="bytes pattern"): + serialize_vt_snapshot(term, scrubbers=[(re.compile(b"raw"), "")]) # ty: ignore[invalid-argument-type] + with pytest.raises(TypeError, match="scrubber"): + serialize_vt_snapshot(term, scrubbers=[(123, "")]) # ty: ignore[invalid-argument-type]