Skip to main content

browser_fixtures: register as a pytest plugin

ID
ce97982
date
2026-11-20 08:46:06+00:00
author
Alex Chan <alex@alexwlchan.net>
parent
db7a622
message
browser_fixtures: register as a pytest plugin

This makes the fixtures easier to use, because you don't need to import
and then re-export them in your `conftest.py` file.
changed files
6 files, 194 additions, 34 deletions

Changed files

CHANGELOG.md (9718 → 9858)

diff --git a/CHANGELOG.md b/CHANGELOG.md
index 62cd507..5fa298f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,9 @@
 # CHANGELOG
 
+## v61 - 2026-11-20
+
+Register the chives browser fixtures as a pytest plugin, so you don't need to import them in your `conftest.py` file.
+
 ## v60 - 2026-11-01
 
 Rename `verify_local_page_integrity` to `assert_page_is_self_contained`.

pyproject.toml (2013 → 2089)

diff --git a/pyproject.toml b/pyproject.toml
index 8a6591d..026d411 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -45,6 +45,9 @@ chives-write-js = "chives.cli:write_chives_js"
 get_codec = "chives.cli:get_video_codec_cli"
 srt-to-vtt = "chives.cli:convert_srt_to_vtt_cli"
 
+[project.entry-points.pytest11]
+chives-browser = "chives.browser_fixtures"
+
 [project.urls]
 "Homepage" = "https://alexwlchan.net/projects/chives/"
 "Changelog" = "https://alexwlchan.net/projects/chives/releases/"

python/chives/__init__.py (391 → 391)

diff --git a/python/chives/__init__.py b/python/chives/__init__.py
index f537da1..e054a62 100644
--- a/python/chives/__init__.py
+++ b/python/chives/__init__.py
@@ -11,4 +11,4 @@ I share across multiple sites.
 
 """
 
-__version__ = "60"
+__version__ = "61"

python/chives/browser_fixtures.py (13003 → 13780)

diff --git a/python/chives/browser_fixtures.py b/python/chives/browser_fixtures.py
index 925ec42..d705d28 100644
--- a/python/chives/browser_fixtures.py
+++ b/python/chives/browser_fixtures.py
@@ -48,18 +48,23 @@ from collections.abc import Iterator
 from contextlib import closing
 import os
 from pathlib import Path
+from typing import Any, TYPE_CHECKING
 import urllib.parse
 from urllib.request import pathname2url
 
 import pytest
-from playwright.sync_api import (
-    Browser,
-    BrowserContext,
-    ConsoleMessage,
-    Page,
-    Request,
-    sync_playwright,
-)
+
+if TYPE_CHECKING:
+    from playwright.sync_api import (
+        Browser,
+        BrowserContext,
+        ConsoleMessage,
+        Page,
+        Playwright,
+        Request,
+    )
+else:
+    Browser = BrowserContext = ConsoleMessage = Page = Playwright = Request = Any
 
 
 __all__ = ["PageError", "file_uri", "browser", "page", "assert_page_is_self_contained"]
@@ -74,16 +79,24 @@ def file_uri(p: Path | str) -> str:
     return pathname2url(absolute_path, add_scheme=True)
 
 
+def skip_playwright_tests() -> bool:
+    """
+    Return whether the SKIP_PLAYWRIGHT environment variable contains
+    a truthy value.
+    """
+    return os.environ.get("SKIP_PLAYWRIGHT", "").lower() in {"1", "true", "yes"}
+
+
 # In regular test suites, a session-scoped fixture is fine, and means
 # we only need to start the browser once.
 #
 # For the chives test suite, we use this fixture from the Python tests
 # and inside a Pytester test suite, and a session-scoped fixture gives
 # errors about using the Playwright Async API.
-_browser_scope = "function" if os.environ.get("CHIVES_TEST") == "true" else "session"
+_scope = "function" if os.environ.get("CHIVES_TEST") == "true" else "session"
 
 
-@pytest.fixture(scope=_browser_scope)
+@pytest.fixture(scope=_scope)
 def browser() -> Iterator[Browser]:
     """
     Launch an instance of WebKit for testing.
@@ -95,7 +108,15 @@ def browser() -> Iterator[Browser]:
     If the environment variable `SKIP_PLAYWRIGHT` is set, this fixture will
     automatically skip any tests that depend on it to speed up test runs.
     """
-    if os.environ.get("SKIP_PLAYWRIGHT", "").lower() in {"1", "true", "yes"}:
+    try:
+        from playwright.sync_api import sync_playwright
+    except ImportError as exc:  # pragma: no cover
+        raise pytest.UsageError(
+            "Playwright is not installed. Install it (and browser binaries) "
+            "to run browser test fixtures."
+        ) from exc
+
+    if skip_playwright_tests():
         pytest.skip(reason="skip slow Playwright tests")
 
     with sync_playwright() as p, closing(p.webkit.launch()) as browser:
@@ -110,6 +131,9 @@ def page(browser: Browser) -> Iterator[Page]:
     On teardown (after your test function finishes), this fixture asserts
     that no console warnings, console errors, or unhandled exceptions
     occurred during the page session.
+
+    If the environment variable `SKIP_PLAYWRIGHT` is set, this fixture will
+    automatically skip any tests that depend on it to speed up test runs.
     """
     with closing(browser.new_page()) as p:
         # Capture anything that gets logged to the console.

tests/conftest.py (234 → 165)

diff --git a/tests/conftest.py b/tests/conftest.py
index 2734d38..993aeab 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -1,8 +1,7 @@
 """Shared helpers and test fixtures."""
 
 from cassettes import cassette_name, vcr_cassette
-from chives.browser_fixtures import browser, page
 
 pytest_plugins = "pytester"
 
-__all__ = ["browser", "cassette_name", "page", "vcr_cassette"]
+__all__ = ["cassette_name", "vcr_cassette"]

tests/python/test_browser_fixtures.py (20700 → 25061)

diff --git a/tests/python/test_browser_fixtures.py b/tests/python/test_browser_fixtures.py
index 7aeea85..8eef7f8 100644
--- a/tests/python/test_browser_fixtures.py
+++ b/tests/python/test_browser_fixtures.py
@@ -8,48 +8,52 @@ import os
 from pathlib import Path
 import shutil
 import subprocess
+import textwrap
 import time
 
-from playwright.sync_api import sync_playwright, Browser
+from playwright.sync_api import Browser, sync_playwright
 import pytest
 from pytest import Pytester
 
-from chives.browser_fixtures import file_uri, assert_page_is_self_contained, PageError
+from chives.browser_fixtures import (
+    assert_page_is_self_contained,
+    file_uri,
+    skip_playwright_tests,
+    PageError,
+)
 
 
 git_root_cmd = ["git", "rev-parse", "--show-toplevel"]
 GIT_ROOT = subprocess.check_output(git_root_cmd, text=True).strip()
 
 
-@pytest.fixture(scope="session")
-def playwright_browsers_path() -> str:
-    """
-    Return the cache directory where Playwright browsers are installed.
-    """
-    with sync_playwright() as p:
-        # In my local builds, this returns a path like:
-        #
-        #    ~/Library/Caches/ms-playwright/webkit-2272/pw_run.sh
-        #
-        # Unwrap two levels to get to the `ms-playwright` folder.
-        return str(Path(p.webkit.executable_path).parent.parent)
+# Find the cache directory where Playwright browsers are installed.
+#
+# We run this before any tests run so we can complete our sync_playwright
+# before triggering another inside the fixture; Playwright gets unhappy
+# if you have multiple sync sessions running in parallel.
+#
+# In my local builds, this returns a path like:
+#
+#    ~/Library/Caches/ms-playwright/webkit-2272/pw_run.sh
+#
+# Unwrap two levels to get to the `ms-playwright` folder.
+with sync_playwright() as p:
+    BROWSERS_PATH = str(Path(p.webkit.executable_path).parent.parent)
 
 
 @pytest.fixture
-def playwright_pytester(pytester: Pytester, playwright_browsers_path: str) -> Pytester:
+def playwright_pytester(pytester: Pytester) -> Pytester:
     """
     Return a `Pytester` instance for which tests have access to the
     `browser` and `page` fixtures, and which use the shared Playwright cache.
     """
-    if "SKIP_PLAYWRIGHT" in os.environ:  # pragma: no cover
+    if skip_playwright_tests():  # pragma: no cover
         pytest.skip(reason="skip slow Playwright tests")
 
     pytester.makeconftest(f"""
         import os
-
-        from chives.browser_fixtures import browser, page
-
-        os.environ["PLAYWRIGHT_BROWSERS_PATH"] = {playwright_browsers_path!r}
+        os.environ["PLAYWRIGHT_BROWSERS_PATH"] = {BROWSERS_PATH!r}
     """)
 
     return pytester
@@ -615,3 +619,129 @@ class TestAssertPageIsSelfContained:
         )
 
         assert_page_is_self_contained(browser, url=file_uri(p))
+
+
+class TestPytestHook:
+    """
+    Test the pytest entry point.
+
+    *   If you have chives[browser_fixtures] installed, you can use
+        the fixtures without adding anything to your conftest.py
+    *   If you have chives but not browser_fixtures installed, the
+        fixtures don't interfere with your existing tests
+
+    """
+
+    def create_venv(self, tmp_path: Path, dependencies: list[str]) -> Path:
+        """
+        Set up a fresh virtual environment for the duration of a test,
+        install dependencies, and return its path.
+        """
+        venv_dir = tmp_path / ".venv"
+        subprocess.check_call(["uv", "venv", str(venv_dir)])
+
+        for dep in dependencies:
+            subprocess.check_call(
+                ["uv", "pip", "install", dep, "--prefix", str(venv_dir)]
+            )
+
+        return venv_dir
+
+    def run_venv_command(self, venv_dir: Path, command: list[str | Path]) -> None:
+        """
+        Run a Python command in the venv dir, and check it succeeds.
+        """
+        command = [str(c) for c in command]
+        subprocess.check_call(
+            [str(venv_dir / "bin" / command[0])] + command[1:], cwd=venv_dir
+        )
+
+    def test_chives_no_browser_fixtures(self, tmp_path: Path) -> None:
+        """
+        Somebody installs chives and pytest and runs a test without
+        installing browser-fixtures/Playwright.
+        """
+        # Install pytest and chives in the repo
+        venv_dir = self.create_venv(tmp_path, dependencies=["pytest", str(GIT_ROOT)])
+
+        # Check pytest is installed
+        self.run_venv_command(venv_dir, ["pytest", "--version"])
+
+        # Check Playwright is not installed in this venv
+        (tmp_path / "test_imports.py").write_text(
+            textwrap.dedent("""
+            import pytest
+
+            def test_truth():
+                assert True
+
+            def test_test_has_no_playwright():
+                with pytest.raises(ImportError):
+                    from playwright.sync_api import sync_playwright
+        """)
+        )
+        self.run_venv_command(
+            venv_dir, ["python3", "-m", "pytest", tmp_path / "test_imports.py"]
+        )
+
+    def test_chives_unused_browser_fixtures(self, tmp_path: Path) -> None:
+        """
+        Somebody installs chives and pytest and runs a test and
+        installs browser-fixtures, but doesn't use it.
+        """
+        # Install pytest and chives[browser-fixtures] in the repo
+        print(f"{GIT_ROOT}[browser_fixtures]")
+        venv_dir = self.create_venv(
+            tmp_path, dependencies=["pytest", f"{GIT_ROOT}[browser_fixtures]"]
+        )
+
+        # Check pytest is installed
+        self.run_venv_command(venv_dir, ["pytest", "--version"])
+
+        # Check Playwright is installed in this venv
+        (tmp_path / "test_imports.py").write_text(
+            textwrap.dedent("""
+            import pytest
+
+            def test_truth():
+                assert True
+
+            def test_has_playwright():
+                from playwright.sync_api import sync_playwright
+        """)
+        )
+        self.run_venv_command(venv_dir, ["pytest", tmp_path / "test_imports.py"])
+
+    def test_chives_browser_fixtures(self, tmp_path: Path) -> None:
+        """
+        Somebody installs chives and pytest and runs a test with
+        browser-fixtures.
+        """
+        # Install pytest and chives[browser-fixtures] in the repo
+        venv_dir = self.create_venv(
+            tmp_path, dependencies=["pytest", f"{GIT_ROOT}[browser_fixtures]"]
+        )
+
+        # Check pytest is installed
+        self.run_venv_command(venv_dir, ["pytest", "--version"])
+
+        # Run a basic test with browser-fixtures
+        (tmp_path / "test_page.py").write_text(
+            textwrap.dedent("""
+            from chives.browser_fixtures import file_uri
+            from playwright.sync_api import expect, Page
+
+            def test_truth():
+                assert True
+
+            with open("greeting.html", "x") as f:
+                f.write("<p>Hello world!</p>")
+
+            def test_page(page: Page):
+                page.goto(file_uri("greeting.html"))
+                expect(page.get_by_text("Hello world!")).to_be_visible()
+        """)
+        )
+        self.run_venv_command(
+            venv_dir, ["python", "-m", "pytest", tmp_path / "test_page.py"]
+        )