Skip to main content

python/chives/browser_fixtures.py

1"""
2Provide a set of Playwright fixtures to use when testing static sites.
4You can start an instance of a web browser, open a URL or local HTML file,
5and make Playwright assertions about the page.
7== browser fixture ==
9The `browser` fixture gives you an instance of a Playwright Browser.
10In this example, we open the local file `greeting.html` and check it
11contains the phrase `Hello world!`:
13 from playwright.sync_api import Browser, expect
14 from chives.browser_fixtures import browser, file_uri
17 def test_browser(browser: Browser) -> None:
18 uri = file_uri("greeting.html")
20 p = browser.new_page()
21 p.goto(uri)
22 expect(p.get_by_text("Hello world!")).to_be_visible()
24== page fixture ==
26The `page` fixture gives you an instance of a Playwright Page.
27It automatically listens for console warnings, console errors, and
28page errors, and raises an assertion error on teardown if any occurred:
30 from playwright.sync_api import Page, expect
31 from chives.browser_fixtures import page, file_uri
34 def test_page(page: Page) -> None:
35 uri = file_uri("greeting.html")
36 page.goto(uri)
37 expect(page.get_by_text("Hello world!")).to_be_visible()
39== verify_local_page_integrity function ==
41The `verify_local_page_integrity` function lets you verify that a local
42copy of a web page is completely self-contained: it loads without errors
43or warnings, and it doesn't make any requests for external resources.
45"""
47from collections.abc import Iterator
48from contextlib import closing
49import os
50from pathlib import Path
51import urllib.parse
52from urllib.request import pathname2url
54import pytest
55from playwright.sync_api import (
56 Browser,
57 BrowserContext,
58 ConsoleMessage,
59 Page,
60 Request,
61 sync_playwright,
65__all__ = ["PageError", "file_uri", "browser", "page", "assert_page_is_self_contained"]
68def file_uri(p: Path | str) -> str:
69 """
70 Convert a file path into a valid `file:///` URI for browser loading.
71 """
72 p = Path(p)
73 absolute_path = str(p.absolute())
74 return pathname2url(absolute_path, add_scheme=True)
77# In regular test suites, a session-scoped fixture is fine, and means
78# we only need to start the browser once.
80# For the chives test suite, we use this fixture from the Python tests
81# and inside a Pytester test suite, and a session-scoped fixture gives
82# errors about using the Playwright Async API.
83_browser_scope = "function" if os.environ.get("CHIVES_TEST") == "true" else "session"
86@pytest.fixture(scope=_browser_scope)
87def browser() -> Iterator[Browser]:
88 """
89 Launch an instance of WebKit for testing.
91 WebKit is my primary browser, so it's the only engine where I need
92 my static websites to work. My sites are simple enough that they're
93 unlikely to rely on WebKit-specific behavior or break in other browsers.
95 If the environment variable `SKIP_PLAYWRIGHT` is set, this fixture will
96 automatically skip any tests that depend on it to speed up test runs.
97 """
98 if os.environ.get("SKIP_PLAYWRIGHT", "").lower() in {"1", "true", "yes"}:
99 pytest.skip(reason="skip slow Playwright tests")
101 with sync_playwright() as p, closing(p.webkit.launch()) as browser:
102 yield browser
105@pytest.fixture(scope="function")
106def page(browser: Browser) -> Iterator[Page]:
107 """
108 Open a browser page that monitors for errors.
110 On teardown (after your test function finishes), this fixture asserts
111 that no console warnings, console errors, or unhandled exceptions
112 occurred during the page session.
113 """
114 with closing(browser.new_page()) as p:
115 # Capture anything that gets logged to the console.
116 console_messages = []
117 p.on("console", lambda msg: console_messages.append(msg))
119 # Capture any page errors
120 page_errors = []
121 p.on("pageerror", lambda err: page_errors.append(err))
123 yield p
125 # Check there weren't any console errors logged to the page.
126 console_errors = [
127 msg.text
128 for msg in console_messages
129 if msg.type == "error" or msg.type == "warning"
130 ]
131 assert console_errors == [], console_errors
133 # Check there weren't any page errors
134 assert page_errors == [], page_errors
137class PageError(Exception):
138 """
139 Thrown when there's an error verifying a page.
140 """
143def assert_page_is_self_contained(ctx: BrowserContext | Browser, url: str) -> None:
144 """
145 Open a new page, navigate to a URL, and assert that it loads cleanly
146 as a self-contained archive.
148 This acts as a heuristic validation check during initial page load.
149 It raises a `PageError` if any of the following occur:
150 - Uncaught page exceptions or errors
151 - Console warnings or errors
152 - Non-GET requests
153 - Requests targeting external resources
155 Note: This only covers the initial page load and will not catch dynamic
156 requests triggered later by user interaction or JavaScript.
157 """
158 with closing(ctx.new_page()) as page:
159 # Capture all console logs, page errors, and requests.
160 console_messages = []
161 page.on("console", lambda msg: console_messages.append(msg))
163 page_errors = []
164 page.on("pageerror", lambda err: page_errors.append(err))
166 requests = []
167 page.on("request", lambda req: requests.append(req))
169 page.goto(url, wait_until="networkidle")
171 # 2. Force a layout/paint to trigger CSS asset downloads (like
172 # background images).
173 if not _is_svg(url):
174 page.evaluate("document.body.offsetHeight")
176 # Wait for the fonts to load, so we get any errors about missing fonts.
177 # Otherwise we can miss the error because we return too quickly.
178 # See https://developer.mozilla.org/en-US/docs/Web/API/Document/fonts#doing_operation_after_fonts_are_loaded
179 page.evaluate("document.fonts.ready")
181 # Give the browser a small buffer tick to register the requests
182 page.wait_for_timeout(500)
184 # Check there weren't any page errors
185 if page_errors:
186 raise PageError(f"Unexpected page errors: {page_errors}")
188 # Check the console logs for errors and warnings.
189 console_errors = [
190 msg for msg in console_messages if _is_important_message(url, requests, msg)
191 ]
193 if console_errors:
194 raise PageError(f"Unexpected console warnings/errors: {console_errors}")
196 # Check there weren't any non-GET requests
197 non_get_requests = [r for r in requests if r.method != "GET"]
198 if non_get_requests: # pragma: no cover
199 raise PageError(f"Page made non-GET requests: {non_get_requests}")
201 # Check there weren't any HTTP requests to external resources
202 external_requests = [r for r in requests if _is_external_request(r, url)]
203 if external_requests:
204 raise PageError(
205 f"Page made requests for external resources: {external_requests}"
206 )
209def _file_url_exists(url: str, suffixes: set[str] | None = None) -> bool:
210 """
211 Return True if a URL is a file:/// URL, optionally with a required suffix.
212 """
213 u = urllib.parse.urlsplit(url)
214 if u.scheme != "file": # pragma: no cover
215 return False
216 path = Path(u.path)
217 if suffixes and path.suffix not in suffixes:
218 return False
219 return path.exists()
222def _is_svg(url: str) -> bool:
223 """
224 Return True if a URL points to an SVG file.
225 """
226 u = urllib.parse.urlsplit(url)
227 return u.path.lower().endswith(".svg")
230def _alternative_font_urls(url: str) -> set[str]:
231 """
232 Return a set of URLs that are equivalent to the current URL.
233 """
234 u = urllib.parse.urlsplit(url)
235 if not u.path.endswith((".otf", ".svg", ".ttf", ".woff", ".woff2")):
236 return set()
238 alt_suffixes = (".otf", ".ttf", ".woff", ".woff2")
240 _, suffix = os.path.splitext(u.path)
241 alt_paths = {u.path.replace(suffix, asf) for asf in alt_suffixes}
243 if u.path.endswith("-webfont.svg"):
244 alt_paths = alt_paths.union(
245 {u.path.replace("-webfont.svg", asf) for asf in alt_suffixes}
246 )
248 return {
249 urllib.parse.urlunsplit((u.scheme, u.netloc, path, "", ""))
250 for path in alt_paths
251 }
254def _path_only_url(url: str) -> str:
255 """
256 Return a URL without a query or fragment.
257 """
258 u = urllib.parse.urlsplit(url)
259 return urllib.parse.urlunsplit((u.scheme, u.netloc, u.path, "", ""))
262def _is_important_message(
263 page_url: str, requests: list[Request], msg: ConsoleMessage
264) -> bool:
265 """
266 Return whether this console message should be raised as an error.
267 """
268 if msg.type not in {"error", "warning"}:
269 return False
271 # Ignore errors about missing font files if:
272 #
273 # 1. The browser has loaded the font in a different format, or
274 # 2. The browser hasn't loaded the font, but it's saved in
275 # a different format
276 #
277 # I don't entirely understand how WebKit decides which font files
278 # to fetch. If a font is actually used on the page, it tries all the
279 # different variants. If a font isn't used, it looks for the TTF and
280 # then gives up, which returns a console error.
281 #
282 # I'm not going to save every variant of a font; I just want to know
283 # that my archive has a copy of this font somewhere.
284 font_err_prefix = "Not allowed to load local resource:"
285 if msg.text.startswith(font_err_prefix):
286 url = msg.location["url"]
287 if url == "":
288 url = urllib.parse.unquote(msg.text.split(font_err_prefix, 1)[1].strip())
290 # Has the browser loaded the font in a different format?
291 request_urls = {_path_only_url(req.url) for req in requests}
292 if set.intersection(request_urls, _alternative_font_urls(url)):
293 return False
295 # Is the font saved in a different format?
296 if any(_file_url_exists(u) for u in _alternative_font_urls(url)):
297 return False
299 # Ignore errors related to loading SVG files from file:/// URLs like:
300 #
301 # Unsafe attempt to load URL file:///Volumes/…/icons.svg#info
302 # from origin null. Domains, protocols and ports must match.
303 #
304 # This is blocked as a cross-origin request. Ignore it as long as
305 # the SVG exists on disk.
306 #
307 # See https://alexwlchan.net/2025/learning-how-to-make-websites/#file_uris
308 svg_err_prefix = "Unsafe attempt to load URL file:///"
309 svg_err_suffix = "from origin null. Domains, protocols and ports must match.\n"
310 if (
311 page_url.startswith("file:///")
312 and msg.text.startswith(svg_err_prefix)
313 and msg.text.endswith(svg_err_suffix)
314 ):
315 url = "file:///" + msg.text[len(svg_err_prefix) : -len(svg_err_suffix)]
317 if _file_url_exists(urllib.parse.unquote(url), suffixes={".svg"}):
318 return False
319 else: # pragma: no cover
320 assert 0, "missing svg test case"
322 # Ignore errors related to loading image files from file:/// URLs like:
323 #
324 # Origin null is not allowed by Access-Control-Allow-Origin.
325 # Status code: 0
326 #
327 # This is blocked as a cross-origin request. We don't get any more
328 # information about this request, so we have to treat it as okay.
329 if (
330 page_url.startswith("file:///")
331 and msg.text
332 == "Origin null is not allowed by Access-Control-Allow-Origin. Status code: 0"
333 ):
334 return False
336 if (
337 page_url.startswith("file:///")
338 and msg.text
339 == "Failed to load resource: Origin null is not allowed by Access-Control-Allow-Origin. Status code: 0" # noqa: E501
340 ):
341 url = urllib.parse.unquote(msg.location["url"])
342 if _file_url_exists(url, suffixes={".png", ".svg"}):
343 return False
345 return True
348def _is_external_request(req: Request, original_url: str) -> bool:
349 """
350 Check if a request has a different origin than the original URL.
352 A request is considered internal if:
353 - it matches the original URL exactly
354 - it has the same scheme, host, and port as the original URL
355 - it uses a `blob:` scheme (for example, in-memory media representations)
357 """
358 if req.url == original_url:
359 return False
361 # Compare the scheme/host of the request to that of the original URL.
362 org_url = urllib.parse.urlsplit(original_url)
363 req_url = urllib.parse.urlsplit(req.url)
365 if org_url.scheme == req_url.scheme and org_url.netloc == req_url.netloc:
366 return False
368 # Ignore blob: URLs, which are in-memory representation of some data,
369 # and not an external request.
370 #
371 # Playwright detects blob: URLs when loading media files; for example
372 # using the <audio> or <video> tag.
373 if req_url.scheme == "blob":
374 return False
376 # Fail open: if we can't decide if a request was internal or external,
377 # assume it was external.
378 return True