Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions CHANGES
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,14 @@
_Notes on the upcoming release will go here._
<!-- END PLACEHOLDER - ADD NEW CHANGELOG ENTRIES BELOW THIS LINE -->

### Fixes

#### Select terminal snapshots in filtered updates (#189)

`pytest -m syrupy_snapshot --snapshot-update` includes tests using only
`vt_snapshot`. The fixture is also available when the project explicitly
loads the Syrupy and libvt plugin modules in `conftest.py`.

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

`libvt` 0.0.1a5 adds rectangular grid blitting, display-column text writes, and
Expand Down
9 changes: 9 additions & 0 deletions docs/topics/testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,15 @@ from `pytest --fixtures` when `syrupy` is uninstalled or disabled via
>>> test_worker_row(_CheckAmbr()) # doctest: +HIDE
```

With the Syrupy plugin active, `pytest -m syrupy_snapshot --snapshot-update`
updates terminal goldens in tests that request only `vt_snapshot`.
Projects that disable plugin autoload can select all three modules in
`conftest.py`:

```python
>>> pytest_plugins = ["syrupy", "libvt.pytest_plugin", "libvt.contrib.syrupy"]
```

### Project-wide `.ambr` scrubbers

To share scrubbers across every `.ambr` test in a repository, build a memoized
Expand Down
96 changes: 56 additions & 40 deletions src/libvt/contrib/syrupy.py
Original file line number Diff line number Diff line change
Expand Up @@ -294,50 +294,51 @@ def get_vt_snapshot_extension() -> type[VtSnapshotExtension]:
return _build_extension_class()


@functools.lru_cache(maxsize=1)
def _build_vt_snapshot_fixture() -> object:
import pytest
def _vt_snapshot(request: pytest.FixtureRequest) -> SnapshotAssertion:
r"""Return a ``syrupy`` assertion bound to :class:`VtSnapshotExtension`.

@pytest.fixture
def vt_snapshot(request: pytest.FixtureRequest) -> SnapshotAssertion:
r"""Return a ``syrupy`` assertion bound to :class:`VtSnapshotExtension`.
Registered automatically by ``libvt_syrupy`` when ``syrupy`` is active
in ``pytest`` (and omitted from ``pytest --fixtures`` when ``syrupy``
is uninstalled or disabled via ``-p no:syrupy``).

Registered automatically by ``libvt_syrupy`` when ``syrupy`` is active
in ``pytest`` (and omitted from ``pytest --fixtures`` when ``syrupy``
is uninstalled or disabled via ``-p no:syrupy``).
Returns
-------
SnapshotAssertion
``syrupy`` assertion serializing terminals, snapshots, screens,
region slices, ``tmux`` captures, and nested dicts/tuples as boxed
``.ambr`` text with ``styles:`` spans.

Returns
-------
SnapshotAssertion
``syrupy`` assertion serializing terminals, snapshots, screens,
region slices, ``tmux`` captures, and nested dicts/tuples as boxed
``.ambr`` text with ``styles:`` spans.
Examples
--------
>>> from libvt import Terminal
>>> from libvt.testing import vt_screen
>>> term = Terminal(rows=1, cols=16)
>>> term.feed(b"\x1b[1;32mOK\x1b[0m pid=48210")
>>> view = vt_screen(term, scrubbers=[(r"pid=\d+", "pid=<PID>")])
>>> print(vt_snapshot.extension.serialize(view))
size=16x1 cursor=(0,13,vis=True) alt=False modes=[]
┌────────────────┐
│OK pid=<PID> │
└────────────────┘
styles:
r0[0..2]: bold fg=green
"""
import pytest

Examples
--------
>>> from libvt import Terminal
>>> from libvt.testing import vt_screen
>>> term = Terminal(rows=1, cols=16)
>>> term.feed(b"\x1b[1;32mOK\x1b[0m pid=48210")
>>> view = vt_screen(term, scrubbers=[(r"pid=\d+", "pid=<PID>")])
>>> print(vt_snapshot.extension.serialize(view))
size=16x1 cursor=(0,13,vis=True) alt=False modes=[]
┌────────────────┐
│OK pid=<PID> │
└────────────────┘
styles:
r0[0..2]: bold fg=green
"""
if importlib.util.find_spec("syrupy") is None:
pytest.skip("vt_snapshot requires the optional 'syrupy' pytest plugin")
try:
base_snapshot = request.getfixturevalue("snapshot")
except pytest.FixtureLookupError:
pytest.skip("vt_snapshot requires an active 'syrupy' pytest plugin")
return base_snapshot.use_extension(get_vt_snapshot_extension())
if importlib.util.find_spec("syrupy") is None:
pytest.skip("vt_snapshot requires the optional 'syrupy' pytest plugin")
try:
base_snapshot = request.getfixturevalue("snapshot")
except pytest.FixtureLookupError:
pytest.skip("vt_snapshot requires an active 'syrupy' pytest plugin")
return base_snapshot.use_extension(get_vt_snapshot_extension())

vt_snapshot.__module__ = __name__
return vt_snapshot

@functools.lru_cache(maxsize=1)
def _build_vt_snapshot_fixture() -> object:
import pytest

return pytest.fixture(_vt_snapshot)


class _SyrupyPytestPlugin:
Expand All @@ -352,8 +353,23 @@ def pytest_configure(self, config: pytest.Config) -> None:
if config.pluginmanager.hasplugin("libvt_syrupy_fixtures"):
return

import pytest

def pytest_itemcollected(item: pytest.Item) -> None:
if not isinstance(item, pytest.Function):
return
# A fixture can be imported under an alias or override its outer fixture.
for name, definitions in item._fixtureinfo.name2fixturedefs.items():
for definition in reversed(definitions):
if definition.func is _vt_snapshot:
item.add_marker("syrupy_snapshot")
return
if name not in definition.argnames:
break

holder = types.ModuleType(f"{__name__}._fixtures")
holder.__dict__["vt_snapshot"] = _build_vt_snapshot_fixture()
holder.__dict__["pytest_itemcollected"] = pytest_itemcollected
config.pluginmanager.register(holder, name="libvt_syrupy_fixtures")


Expand Down Expand Up @@ -382,7 +398,7 @@ def __getattr__(name: str) -> object:


def __dir__() -> list[str]:
names = ["get_vt_snapshot_extension"]
names = ["get_vt_snapshot_extension", "pytest_configure"]
if importlib.util.find_spec("syrupy") is not None:
names.append("VtSnapshotExtension")
return sorted(names)
Expand Down
103 changes: 103 additions & 0 deletions tests/test_syrupy.py
Original file line number Diff line number Diff line change
Expand Up @@ -440,3 +440,106 @@ def test_explicit_skip(vt_snapshot):
)
assert disabled.returncode == 0, disabled.stdout + disabled.stderr
assert "1 skipped" in disabled.stdout


@pytest.mark.parametrize("modules", [False, True], ids=["entry-points", "modules"])
def test_snapshot_marker_updates_terminal_only_fixture(
modules: bool, tmp_path: pathlib.Path
) -> None:
"""A filtered downstream update selects both Syrupy and terminal fixtures."""
pytest.importorskip("syrupy")
env = _child_env()
env["PYTEST_DISABLE_PLUGIN_AUTOLOAD"] = "1"
args = [sys.executable, "-m", "pytest", "-q", "-p", "no:cacheprovider"]
if modules:
(tmp_path / "conftest.py").write_text(
"pytest_plugins = ['syrupy', 'libvt.pytest_plugin', "
"'libvt.contrib.syrupy']\n",
encoding="utf-8",
)
else:
args.extend(["-p", "syrupy", "-p", "libvt", "-p", "libvt_syrupy"])
case = tmp_path / "test_receipt.py"
first = (
"from libvt import Terminal\n"
"from libvt.testing import vt_screen\n"
"def test_receipt(vt_snapshot):\n"
" t = Terminal(rows=1, cols=8)\n"
" t.feed(b'RIGHT')\n"
" assert vt_screen(t) == vt_snapshot\n"
"def test_control(snapshot):\n"
" assert 'control' == snapshot\n"
)
case.write_text(first, encoding="utf-8")

def run(*options: str) -> subprocess.CompletedProcess[str]:
return subprocess.run(
[*args, *options],
cwd=tmp_path,
env=env,
capture_output=True,
text=True,
encoding="utf-8",
check=False,
timeout=30,
)

original = run("--snapshot-update")
assert original.returncode == 0, original.stdout + original.stderr
case.write_text(first.replace("RIGHT", "UPDATED"), encoding="utf-8")
direct = run("-k", "test_receipt")
assert direct.returncode == 1 and "UPDATED" in direct.stdout
filtered = run("-m", "syrupy_snapshot", "--snapshot-update")
assert filtered.returncode == 0 and "2 passed" in filtered.stdout, filtered.stdout
final = run()
assert final.returncode == 0 and "2 passed" in final.stdout, final.stdout


def test_snapshot_marker_follows_the_effective_fixture(tmp_path: pathlib.Path) -> None:
"""A local override can replace or delegate to the plugin's fixture."""
(tmp_path / "test_project.py").write_text(
"import pytest\n"
"@pytest.fixture\n"
"def vt_snapshot():\n"
" return 'local'\n"
"def test_local(vt_snapshot):\n"
" assert vt_snapshot == 'local'\n",
encoding="utf-8",
)
(tmp_path / "test_indirect.py").write_text(
"import pytest\n"
"from libvt import Terminal\n"
"from libvt.contrib.syrupy import vt_snapshot as golden\n"
"@pytest.fixture\n"
"def vt_snapshot(vt_snapshot):\n"
" return vt_snapshot\n"
"def test_wrapped(vt_snapshot):\n"
" assert Terminal(rows=1, cols=2) == vt_snapshot\n"
"def test_alias(golden):\n"
" assert Terminal(rows=1, cols=2) == golden\n",
encoding="utf-8",
)
run = subprocess.run(
[
sys.executable,
"-m",
"pytest",
"-q",
"-p",
"syrupy",
"-p",
"libvt_syrupy",
"-m",
"syrupy_snapshot",
"--snapshot-update",
],
cwd=tmp_path,
env=_child_env() | {"PYTEST_DISABLE_PLUGIN_AUTOLOAD": "1"},
capture_output=True,
text=True,
encoding="utf-8",
check=False,
)
assert run.returncode == 0, run.stdout + run.stderr
assert "2 passed, 1 deselected" in run.stdout
assert "test_wrapped" in next(tmp_path.rglob("*.ambr")).read_text(encoding="utf-8")
Loading