From 56da923351ba6926c5104d020b26a985478610b8 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Wed, 2 Dec 2026 19:16:39 -0600 Subject: [PATCH 1/3] pytest(fix[syrupy]): Discover module hook why: Module-based pytest loading cannot find the lazy configure hook. what: - Expose the configure hook through module introspection. - Compare explicit module and entry-point fixture registration. Fixes #112 --- docs/topics/testing.md | 7 ++++++ src/libvt/contrib/syrupy.py | 2 +- tests/test_syrupy.py | 46 +++++++++++++++++++++++++++++++++++++ 3 files changed, 54 insertions(+), 1 deletion(-) diff --git a/docs/topics/testing.md b/docs/topics/testing.md index 7d96c24..b4c657d 100644 --- a/docs/topics/testing.md +++ b/docs/topics/testing.md @@ -242,6 +242,13 @@ from `pytest --fixtures` when `syrupy` is uninstalled or disabled via >>> test_worker_row(_CheckAmbr()) # doctest: +HIDE ``` +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 diff --git a/src/libvt/contrib/syrupy.py b/src/libvt/contrib/syrupy.py index c089012..71c27c0 100644 --- a/src/libvt/contrib/syrupy.py +++ b/src/libvt/contrib/syrupy.py @@ -382,7 +382,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) diff --git a/tests/test_syrupy.py b/tests/test_syrupy.py index 4e47c25..3302310 100644 --- a/tests/test_syrupy.py +++ b/tests/test_syrupy.py @@ -440,3 +440,49 @@ 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_explicit_plugin_loading_exposes_vt_snapshot( + modules: bool, tmp_path: pathlib.Path +) -> None: + """Explicit module and entry-point loading both expose vt_snapshot.""" + 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 From 6da58f906bb665efbe061846f61184d7dd38e6e4 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Wed, 2 Dec 2026 19:16:39 -0600 Subject: [PATCH 2/3] pytest(fix[syrupy]): Select terminal snapshots why: A filtered snapshot update can skip terminal-only fixtures. what: - Mark tests using the effective terminal snapshot fixture. - Cover handlers using aliases and fixture overrides. - Verify that a filtered update replaces the stale golden. Fixes #87 --- docs/topics/testing.md | 2 + src/libvt/contrib/syrupy.py | 94 ++++++++++++++++++++++--------------- tests/test_syrupy.py | 61 +++++++++++++++++++++++- 3 files changed, 116 insertions(+), 41 deletions(-) diff --git a/docs/topics/testing.md b/docs/topics/testing.md index b4c657d..ad96050 100644 --- a/docs/topics/testing.md +++ b/docs/topics/testing.md @@ -242,6 +242,8 @@ 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`: diff --git a/src/libvt/contrib/syrupy.py b/src/libvt/contrib/syrupy.py index 71c27c0..6ad3c9c 100644 --- a/src/libvt/contrib/syrupy.py +++ b/src/libvt/contrib/syrupy.py @@ -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=")]) + >>> print(vt_snapshot.extension.serialize(view)) + size=16x1 cursor=(0,13,vis=True) alt=False modes=[] + ┌────────────────┐ + │OK 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=")]) - >>> print(vt_snapshot.extension.serialize(view)) - size=16x1 cursor=(0,13,vis=True) alt=False modes=[] - ┌────────────────┐ - │OK 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: @@ -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") diff --git a/tests/test_syrupy.py b/tests/test_syrupy.py index 3302310..7ad6ebd 100644 --- a/tests/test_syrupy.py +++ b/tests/test_syrupy.py @@ -443,10 +443,10 @@ def test_explicit_skip(vt_snapshot): @pytest.mark.parametrize("modules", [False, True], ids=["entry-points", "modules"]) -def test_explicit_plugin_loading_exposes_vt_snapshot( +def test_snapshot_marker_updates_terminal_only_fixture( modules: bool, tmp_path: pathlib.Path ) -> None: - """Explicit module and entry-point loading both expose vt_snapshot.""" + """A filtered downstream update selects both Syrupy and terminal fixtures.""" pytest.importorskip("syrupy") env = _child_env() env["PYTEST_DISABLE_PLUGIN_AUTOLOAD"] = "1" @@ -486,3 +486,60 @@ def run(*options: str) -> subprocess.CompletedProcess[str]: 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") From fcde7dab517482b2005fca0e74789ccb050fff9b Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Wed, 2 Dec 2026 19:58:51 -0600 Subject: [PATCH 3/3] CHANGES(docs): Record syrupy fixture registration why: Readers need the behavior and scope of this change at release. what: - Add the unreleased entry for PR #189 - Preserve previously published notes and the parent branch's entries --- CHANGES | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/CHANGES b/CHANGES index ca1c339..ebc8491 100644 --- a/CHANGES +++ b/CHANGES @@ -6,6 +6,14 @@ _Notes on the upcoming release will go here._ +### 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