Skip to content

Commit 4eed00a

Browse files
author
temp-merge
committed
testing(fix[scrub]): Keep PathLike paths literal
why: PathLike scrubbers should match literal filesystem paths across POSIX and Windows separators without implicit URI percent-encoding magic that obscures explicit file:// scrubber rules. what: - Compile os.PathLike[str] literally with escaped segments and [\\/] - Normalize scrubbers eagerly in VtSnapshotExtension.configure() - Document explicit re.escape(path.as_uri()) pairing for file:// URIs - Test Windows drives, UNC, POSIX metacharacters, and unhashable paths
1 parent ed663a3 commit 4eed00a

6 files changed

Lines changed: 91 additions & 139 deletions

File tree

‎CHANGES‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,8 @@ _Notes on the upcoming release will go here._
1515
{class}`~libvt.contrib.syrupy.VtSnapshotExtension`'s
1616
{meth}`~libvt.contrib.syrupy.VtSnapshotExtension.configure` accept
1717
{class}`os.PathLike` values such as `pytest`'s `tmp_path` alongside `str` and
18-
compiled regex patterns. Literal path scrubbers escape regex metacharacters and
19-
match `/` separators, lowercase Windows drive letters, and percent-encoded
20-
`file:///` URIs cleanly.
18+
compiled regex patterns, escaping regex metacharacters and matching `/` or `\`
19+
separators and lowercase Windows drive letters literally.
2120

2221
## libvt 0.0.1a5 (2026-11-30)
2322

‎docs/topics/testing.md‎

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -129,22 +129,30 @@ True
129129

130130
Pass a {class}`pathlib.Path` (such as `pytest`'s `tmp_path`) or any
131131
{class}`os.PathLike` directly in `scrubbers` to match a literal filesystem path
132-
without regex-escaping metacharacters or Windows backslashes. Literal path
133-
scrubbers also match percent-encoded `file:///` URIs, forward-slash separators,
134-
and lowercase Windows drive letters:
132+
without regex-escaping metacharacters or Windows backslashes. When output also
133+
prints `file://` URIs across OSes, pair {meth}`pathlib.Path.as_uri` with
134+
{func}`re.escape` as `(re.escape(tmp_path.as_uri()), "file://<TMP>")`:
135135

136136
```python
137137
>>> import pathlib
138+
>>> import re
138139
>>> import libvt
139140
>>> from libvt.testing import serialize_vt_snapshot
140141
>>> win_tmp = pathlib.PureWindowsPath(r"C:\Users\runner\Temp\test[0]")
141-
>>> term = libvt.Terminal(rows=2, cols=54)
142+
>>> work_dir = pathlib.Path.cwd() / "work[0]"
143+
>>> term = libvt.Terminal(rows=8, cols=56)
142144
>>> term.feed_str(
143-
... "dir=C:\\Users\\runner\\Temp\\test[0]\\run.log\r\n"
144-
... "uri=file:///C:/Users/runner/Temp/test%5B0%5D/run.log"
145+
... "dir=c:/Users/runner/Temp/test[0]/run.log\r\n"
146+
... f"uri={work_dir.as_uri()}/run.log"
145147
... )
146-
>>> out = serialize_vt_snapshot(term, scrubbers=[(win_tmp, "<TMP>")])
147-
>>> r"│dir=<TMP>\run.log" in out and "│uri=file:///<TMP>/run.log" in out
148+
>>> out = serialize_vt_snapshot(
149+
... term,
150+
... scrubbers=[
151+
... (re.escape(work_dir.as_uri()), "file://<TMP>"),
152+
... (win_tmp, "<TMP>"),
153+
... ],
154+
... )
155+
>>> "│dir=<TMP>/run.log" in out and "│uri=file://<TMP>/run.log" in out
148156
True
149157
```
150158

‎src/libvt/contrib/syrupy.py‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -154,8 +154,13 @@ def configure(
154154
normalized_scrubbers = (
155155
cls._scrubbers
156156
if scrubbers is None
157-
else tuple(
158-
(_compile_scrubber_pattern(pat), repl) for pat, repl in scrubbers
157+
else (
158+
tuple(
159+
(_compile_scrubber_pattern(pat), repl)
160+
for pat, repl in scrubbers
161+
)
162+
if scrubbers
163+
else ()
159164
)
160165
)
161166
return _build_extension_class(

‎src/libvt/testing.py‎

Lines changed: 19 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@
88
import re
99
import textwrap
1010
import typing as t
11-
import urllib.parse
1211
from dataclasses import dataclass
1312

1413
from libvt._grid import raw_width_bits
@@ -542,56 +541,34 @@ class _CellMeta:
542541
hyperlink: Hyperlink | None
543542

544543

545-
def _has_ascii_drive(segment: str) -> bool:
546-
return (
547-
len(segment) == 2
548-
and segment[0].isascii()
549-
and segment[0].isalpha()
550-
and segment[1] == ":"
551-
)
552-
553-
554544
def _compile_scrubber_pattern(
555545
pat: str | re.Pattern[str] | os.PathLike[str],
556546
) -> re.Pattern[str]:
557547
if isinstance(pat, re.Pattern):
558548
if not isinstance(pat.pattern, str):
559-
msg = "Expected str regex pattern for scrubber, got bytes pattern"
549+
msg = "scrubber regex must be a str pattern, not bytes pattern"
560550
raise TypeError(msg)
561551
return pat
552+
if isinstance(pat, str):
553+
return re.compile(pat)
562554
if isinstance(pat, os.PathLike):
563-
raw: str | bytes = os.fspath(pat)
555+
raw = os.fspath(pat)
564556
if not isinstance(raw, str):
565-
msg = f"Expected str path from PathLike scrubber, got {type(raw).__name__}"
557+
msg = f"scrubber PathLike must return str, got {type(raw).__name__}"
566558
raise TypeError(msg)
567559
if not raw:
568-
msg = "PathLike scrubber path must not be empty"
560+
msg = "scrubber PathLike path must not be empty"
569561
raise ValueError(msg)
570-
has_win_drive = False
571-
if "\\" in raw:
572-
parts = raw.split("\\")
573-
has_win_drive = _has_ascii_drive(parts[0])
574-
head = (
575-
f"[{parts[0][0].lower()}{parts[0][0].upper()}]:"
576-
if has_win_drive
577-
else re.escape(parts[0])
578-
)
579-
base_expr = r"[\\/]".join([head, *(re.escape(p) for p in parts[1:])])
580-
else:
581-
base_expr = re.escape(raw)
582-
posix_raw = raw.replace("\\", "/")
583-
quoted = urllib.parse.quote(posix_raw, safe="/:")
584-
if quoted != posix_raw:
585-
uri_expr = (
586-
f"[{quoted[0].lower()}{quoted[0].upper()}]:{re.escape(quoted[2:])}"
587-
if has_win_drive
588-
else re.escape(quoted)
589-
)
590-
return re.compile(f"(?:{base_expr}|{uri_expr})")
591-
return re.compile(base_expr)
592-
if isinstance(pat, str):
593-
return re.compile(pat)
594-
msg = f"Expected str, re.Pattern, or os.PathLike scrubber, got {type(pat).__name__}"
562+
if "\\" not in raw:
563+
return re.compile(re.escape(raw))
564+
parts = [re.escape(part) for part in raw.split("\\")]
565+
if len(raw) >= 2 and raw[0].isascii() and raw[0].isalpha() and raw[1] == ":":
566+
parts[0] = f"[{raw[0].lower()}{raw[0].upper()}]:"
567+
return re.compile(r"[\\/]".join(parts))
568+
msg = (
569+
"scrubber pattern must be str, re.Pattern[str], or os.PathLike[str], "
570+
f"got {type(pat).__name__}"
571+
)
595572
raise TypeError(msg)
596573

597574

@@ -1013,9 +990,8 @@ def serialize_vt_snapshot(
1013990
or duck-typed pane wrapper exposing ``.terminal``, ``.snapshot()``, or
1014991
``.capture_vt()``.
1015992
scrubbers : Sequence[ScrubberSpec], optional
1016-
Regex ``(pattern, replacement)`` pairs or literal :class:`os.PathLike`
1017-
prefixes applied during serialization; backslash paths also match
1018-
forward-slash ``/`` forms.
993+
Regex or literal :class:`os.PathLike` ``(pattern, replacement)`` pairs
994+
applied during serialization.
1019995
include_cursor_shape : bool, optional
1020996
When ``True``, include ``shape=<CursorShape>`` in the cursor header tuple
1021997
unless marked unexposed by ``tmux`` capture completeness metadata.
@@ -1032,11 +1008,7 @@ def serialize_vt_snapshot(
10321008
------
10331009
TypeError
10341010
If *target* (or a :class:`VtScreenView`'s inner target) is not a supported
1035-
terminal, snapshot, screen, region, or pane wrapper, or if a scrubber
1036-
pattern is not a ``str``, compiled ``str`` regex, or ``str``
1037-
:class:`os.PathLike`.
1038-
ValueError
1039-
If an :class:`os.PathLike` scrubber resolves to an empty path.
1011+
terminal, snapshot, screen, region, or pane wrapper.
10401012
10411013
Examples
10421014
--------

‎tests/test_syrupy.py‎

Lines changed: 26 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@
77
import importlib.util
88
import os
99
import pathlib
10-
import pickle
1110
import subprocess
1211
import sys
1312

@@ -147,6 +146,32 @@ def test_configure_lru_cache_and_nested_containers() -> None:
147146
assert c1 is c2
148147
assert c1.configure(scrubbers=())._scrubbers == ()
149148

149+
class _UnhashablePathLike:
150+
__hash__ = None # type: ignore[assignment]
151+
152+
def __init__(self, raw: str) -> None:
153+
self._raw = raw
154+
155+
def __fspath__(self) -> str:
156+
return self._raw
157+
158+
p_dir = pathlib.PurePosixPath("/tmp/work[0]/c++")
159+
cp1 = ext_cls.configure(scrubbers=[(p_dir, "<WORK>")])
160+
cp2 = ext_cls.configure(
161+
scrubbers=[(_UnhashablePathLike("/tmp/work[0]/c++"), "<WORK>")]
162+
)
163+
assert cp1 is cp2
164+
t_path = Terminal(rows=1, cols=32)
165+
t_path.feed_str("log=/tmp/work[0]/c++/run.log")
166+
assert "│log=<WORK>/run.log" in cp1().serialize(t_path)
167+
168+
class _EmptyPath:
169+
def __fspath__(self) -> str:
170+
return ""
171+
172+
with pytest.raises(ValueError, match="must not be empty"):
173+
ext_cls.configure(scrubbers=[(_EmptyPath(), "<TMP>")])
174+
150175
t_prev = Terminal(rows=2, cols=14)
151176
t_prev.feed(b"Menu: [A] B")
152177
t_next = Terminal(rows=2, cols=14)
@@ -169,66 +194,6 @@ def snapshot(self) -> Snapshot:
169194
_ = __import__("libvt.contrib.syrupy", fromlist=["_missing"])._missing
170195

171196

172-
def test_configure_pathlike_and_unhashable_scrubbers(
173-
tmp_path: pathlib.Path,
174-
) -> None:
175-
"""``VtSnapshotExtension.configure()`` normalizes ``PathLike`` scrubbers."""
176-
177-
class _UnhashablePath(os.PathLike[str]):
178-
def __init__(self, path: str) -> None:
179-
self.path = path
180-
181-
def __fspath__(self) -> str:
182-
return self.path
183-
184-
def __eq__(self, other: object) -> bool:
185-
return isinstance(other, _UnhashablePath) and self.path == other.path
186-
187-
work_dir = tmp_path / "test_sync[jobs=2]" / "c++"
188-
unhashable = _UnhashablePath(os.fspath(work_dir))
189-
with pytest.raises(TypeError, match="unhashable"):
190-
hash(unhashable)
191-
192-
win_tmp = pathlib.PureWindowsPath(r"C:\Users\runner\Temp\test_sync[case0]")
193-
ext_a = VtSnapshotExtension.configure(
194-
scrubbers=[(unhashable, "<WORK>"), (win_tmp, "<WTMP>")],
195-
)
196-
ext_b = VtSnapshotExtension.configure(
197-
scrubbers=[
198-
(_UnhashablePath(os.fspath(work_dir)), "<WORK>"),
199-
(win_tmp, "<WTMP>"),
200-
],
201-
)
202-
assert ext_a is ext_b
203-
assert pickle.loads(pickle.dumps(ext_a._scrubbers)) == ext_a._scrubbers
204-
205-
term = Terminal(rows=3, cols=60)
206-
term.feed_str(
207-
f"work={work_dir}/run.log\r\n"
208-
"win=C:\\Users\\runner\\Temp\\test_sync[case0]\\a.log\r\n"
209-
"uri=file:///C:/Users/runner/Temp/test_sync%5Bcase0%5D/a.log"
210-
)
211-
rendered = ext_a().serialize(term)
212-
assert "│work=<WORK>/run.log" in rendered
213-
assert r"│win=<WTMP>\a.log" in rendered
214-
assert "│uri=file:///<WTMP>/a.log" in rendered
215-
216-
class _EmptyPath:
217-
def __fspath__(self) -> str:
218-
return ""
219-
220-
class _BytesPath:
221-
def __fspath__(self) -> bytes:
222-
return b"/tmp/raw"
223-
224-
with pytest.raises(ValueError, match="must not be empty"):
225-
VtSnapshotExtension.configure(scrubbers=[(_EmptyPath(), "<TMP>")])
226-
with pytest.raises(TypeError, match="PathLike"):
227-
VtSnapshotExtension.configure(scrubbers=[(_BytesPath(), "<TMP>")]) # ty: ignore[invalid-argument-type]
228-
with pytest.raises(TypeError, match="scrubber"):
229-
VtSnapshotExtension.configure(scrubbers=[(123, "<X>")]) # ty: ignore[invalid-argument-type]
230-
231-
232197
def test_default_pytest_truncation_pty_colors_and_ci_carets(
233198
tmp_path: pathlib.Path,
234199
) -> None:

‎tests/test_testing.py‎

Lines changed: 21 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -322,32 +322,35 @@ def test_vt_screen_styles_region_sync_hold_cjk_and_errors() -> None:
322322
serialize_vt_snapshot(vt_screen(t_prev, diff=object())) # ty: ignore[invalid-argument-type]
323323

324324

325-
def test_pathlike_scrubbers_windows_separators_and_metacharacters(
325+
def test_pathlike_literal_scrubbers_and_validation(
326326
tmp_path: pathlib.Path,
327327
) -> None:
328-
"""``os.PathLike`` scrubbers escape metacharacters and match Windows URIs."""
328+
"""``os.PathLike`` scrubbers escape literal paths without URI magic."""
329329
win_tmp = pathlib.PureWindowsPath(r"C:\Users\runner\Temp\test[0]")
330330
win_uri = "file:///C:/Users/runner/Temp/test%5B0%5D"
331331

332332
t_win = Terminal(rows=4, cols=60)
333333
t_win.feed_str(
334334
"raw=C:\\Users\\runner\\Temp\\test[0]\\a.log\r\n"
335-
f"uri={win_uri}/a.log\r\n"
336335
"low=c:/Users/runner/Temp/test[0]/a.log\r\n"
337-
"mix=C:\\Users/runner/Temp\\test[0]\\a.log"
336+
"mix=C:\\Users/runner/Temp\\test[0]\\a.log\r\n"
337+
f"uri={win_uri}/a.log"
338338
)
339-
out_win = serialize_vt_snapshot(t_win, scrubbers=[(win_tmp, "<TMP>")])
340-
assert r"│raw=<TMP>\a.log" in out_win
341-
assert "│uri=file:///<TMP>/a.log" in out_win
342-
assert "│low=<TMP>/a.log" in out_win
343-
assert r"│mix=<TMP>\a.log" in out_win
344-
345-
win_plain = pathlib.PureWindowsPath(r"C:\Users\runner\Temp\run1")
346-
t_plain = Terminal(rows=1, cols=40)
347-
t_plain.feed_str("dir=c:/Users/runner/Temp/run1/ok")
348-
assert "│dir=<TMP>/ok" in serialize_vt_snapshot(
349-
t_plain, scrubbers=[(win_plain, "<TMP>")]
339+
out_literal_only = serialize_vt_snapshot(t_win, scrubbers=[(win_tmp, "<TMP>")])
340+
assert r"│raw=<TMP>\a.log" in out_literal_only
341+
assert "│low=<TMP>/a.log" in out_literal_only
342+
assert r"│mix=<TMP>\a.log" in out_literal_only
343+
# Percent-encoded [0] in file:// URI stays untouched without explicit as_uri() rule.
344+
assert "test%5B0%5D" in out_literal_only
345+
346+
out_with_uri = serialize_vt_snapshot(
347+
t_win,
348+
scrubbers=[
349+
(re.escape(win_uri), "file://<TMP>"),
350+
(win_tmp, "<TMP>"),
351+
],
350352
)
353+
assert "│uri=file://<TMP>/a.log" in out_with_uri
351354

352355
unc_tmp = pathlib.PureWindowsPath(r"\\srv\share\dir[0]")
353356
t_unc = Terminal(rows=1, cols=40)
@@ -357,21 +360,21 @@ def test_pathlike_scrubbers_windows_separators_and_metacharacters(
357360
)
358361

359362
meta_dir = tmp_path / "test_sync[jobs=2]" / "c++"
360-
t_posix = Terminal(rows=4, cols=60)
363+
t_posix = Terminal(rows=6, cols=60)
361364
t_posix.feed_str(f"dir={meta_dir}/out(1).log pid=42\r\nuri={meta_dir.as_uri()}/out")
362365
out_posix = serialize_vt_snapshot(
363366
vt_screen(
364367
t_posix,
365368
scrubbers=[
369+
(re.escape(meta_dir.as_uri()), "file://<WORK>"),
366370
(meta_dir, "<WORK>"),
367371
(r"\(\d+\)", "(<N>)"),
368372
(re.compile(r"pid=\d+"), "pid=<PID>"),
369373
],
370374
)
371375
)
372-
uri_scheme = "file:///" if sys.platform == "win32" else "file://"
373376
assert "│dir=<WORK>/out(<N>).log pid=<PID>" in out_posix
374-
assert f"│uri={uri_scheme}<WORK>/out" in out_posix
377+
assert "│uri=file://<WORK>/out" in out_posix
375378

376379
class _EmptyPath:
377380
def __fspath__(self) -> str:

0 commit comments

Comments
 (0)