Files

298 lines
13 KiB
Python

"""Tests for the installable PWA (section 31 point 6).
The service worker caches only the shell, the manifest describes the app, and
every page links the manifest and the icon. The icon is the retro SVG of
section 32.1, listed first, with the 192 and 512 px PNGs beside it.
"""
from http.server import ThreadingHTTPServer
import json
import os
from pathlib import Path
import tempfile
import threading
import unittest
from urllib.request import urlopen
from app import ROOT, STATIC_FILES, AppHandler
from database import initialize_database
from server_session import SessionMixin
class ServiceWorkerTests(unittest.TestCase):
"""The service worker is served, registered, and limited to the shell."""
def setUp(self):
self.server = ThreadingHTTPServer(("127.0.0.1", 0), AppHandler)
self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)
self.thread.start()
self.base_url = f"http://127.0.0.1:{self.server.server_port}"
def tearDown(self):
self.server.shutdown()
self.server.server_close()
self.thread.join(timeout=2)
def read_static(self, filename):
return (ROOT / "static" / filename).read_text(encoding="utf-8")
def fetch_text(self, path):
# /sw.js is a static asset, so it needs no session (section 31 point 1).
with urlopen(f"{self.base_url}{path}") as response:
self.assertEqual(response.status, 200)
return response.read().decode("utf-8")
def test_the_service_worker_is_served_from_the_root(self):
# The scope of a service worker is bounded by its path, so it has to be
# served from the root.
body = self.fetch_text("/sw.js")
self.assertIn("vardkey-shell", body)
def test_the_service_worker_is_listed_in_static_files(self):
self.assertIn("/sw.js", STATIC_FILES)
def test_the_service_worker_never_caches_an_api_response(self):
# An allowlist means the worker does not name the API, the health
# endpoint or the login page at all, so none of them can ever be cached
# (section 31 point 6).
body = self.read_static("sw.js")
self.assertNotIn("/api/", body)
# The quoted path is what matters: "/health-check" is a shell path, while
# "/health" and "/login" are not, and must not appear.
self.assertNotIn('\"/health\"', body)
self.assertNotIn('"/login"', body)
# The shell it does cache is the five pages, their assets, and the
# manifest and icons the browser reads when the app is installed.
for path in (
"/",
"/setup",
"/settings",
"/health-check",
"/history",
"/styles.css",
"/manifest.webmanifest",
"/icon.svg",
"/icon-192.png",
"/icon-512.png",
):
self.assertIn(f'"{path}"', body)
def test_the_service_worker_only_stores_a_successful_same_origin_answer(self):
# A page fetched without a session answers 302 -> /login, and fetch
# follows it, so the login page would replace the cached shell unless the
# stored answer is checked first. The worker stores a response only when
# it is successful, same-origin and not redirected (section 31 point 6).
body = self.read_static("sw.js")
self.assertIn("isCacheable", body)
self.assertIn("response.ok", body)
self.assertIn("response.type", body)
self.assertIn("!response.redirected", body)
def test_the_robots_file_is_served_but_never_cached_as_shell(self):
# The crawler rule is a file the server answers, and it is deliberately
# not part of the PWA shell: the worker caches only what the app needs
# offline (sections 31 point 6 and 32.7 point 6).
self.assertIn("/robots.txt", STATIC_FILES)
self.assertNotIn('"/robots.txt"', self.read_static("sw.js"))
def test_the_dashboard_registers_the_service_worker(self):
body = self.read_static("app.js")
self.assertIn('serviceWorker.register("/sw.js")', body)
def test_the_dashboard_shows_an_offline_state(self):
# The shell may come from the cache while every fetch fails, so the UI
# says so plainly instead of leaving empty cards (section 31 point 6).
body = self.read_static("app.js")
self.assertIn('addEventListener("offline"', body)
self.assertIn("You are offline", body)
class IconTests(unittest.TestCase):
"""The favicon, the top-bar brand mark, and the two raster icons (32.1).
Every page links the icon, and the brand mark is the icon image itself. The
class name ``brand-mark`` is kept, because the stylesheet styles it by that
name. The PNGs are rasterized from the package icon at the repository root,
so the two SVG files have to carry the same drawing.
"""
PAGES = (
"index.html",
"setup.html",
"settings.html",
"health-check.html",
"history.html",
"login.html",
)
ICON_LINK = '<link rel="icon" type="image/svg+xml" href="/icon.svg">'
BRAND_MARK = '<img class="brand-mark" src="/icon.svg" alt="" aria-hidden="true">'
LETTER_MARK = '<span class="brand-mark" aria-hidden="true">V</span>'
PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
def read_static(self, filename):
return (ROOT / "static" / filename).read_text(encoding="utf-8")
def png_size(self, filename):
"""Return the width and height a PNG file declares in its IHDR chunk."""
data = (ROOT / "static" / filename).read_bytes()
self.assertEqual(data[:8], self.PNG_SIGNATURE, filename)
self.assertEqual(data[12:16], b"IHDR", filename)
return int.from_bytes(data[16:20], "big"), int.from_bytes(data[20:24], "big")
def test_every_page_links_the_icon(self):
# The favicon is the same retro drawing as the manifest icon, and every
# page links it, including the login page, which links no manifest
# (section 32.1).
for name in self.PAGES:
self.assertIn(self.ICON_LINK, self.read_static(name), name)
def test_every_page_shows_the_icon_in_the_top_bar(self):
for name in self.PAGES:
body = self.read_static(name)
self.assertIn(self.BRAND_MARK, body, name)
# The letter that used to stand there is gone.
self.assertNotIn(self.LETTER_MARK, body, name)
def test_the_brand_mark_is_styled_for_an_image(self):
styles = self.read_static("styles.css")
self.assertIn(".brand-mark {", styles)
# An 18 by 18 image on the raised face, kept crisp when it is scaled
# down. The rules that only made sense for the letter are gone.
self.assertIn("image-rendering: pixelated", styles)
self.assertNotIn("place-items: center", styles)
def test_the_stylesheet_keeps_the_footer_at_the_bottom(self):
# The page is a column that fills the window, so a short page still puts
# the footer at the bottom (section 32.1).
styles = self.read_static("styles.css")
self.assertIn("min-height: 100vh", styles)
self.assertIn("min-height: 100dvh", styles)
self.assertIn("flex-direction: column", styles)
self.assertIn("main { flex: 1 1 auto; }", styles)
def test_the_served_icon_carries_the_same_drawing_as_the_package_icon(self):
# The package icon at the repository root is the source of truth, and the
# file the PWA serves is the same drawing. Only the leading comment may
# differ, so the comparison starts at the root <svg> element
# (section 32.1).
root = (ROOT / "icon.svg").read_text(encoding="utf-8")
served = self.read_static("icon.svg")
self.assertEqual(root[root.index("<svg"):], served[served.index("<svg"):])
def test_the_png_icons_are_the_size_the_manifest_declares(self):
# A rasterizer asked for the wrong size still writes a valid PNG, so the
# size is read from the file itself instead of being trusted
# (section 32.1).
self.assertEqual(self.png_size("icon-192.png"), (192, 192))
self.assertEqual(self.png_size("icon-512.png"), (512, 512))
class ManifestTests(SessionMixin, unittest.TestCase):
"""The manifest and the icons that make the app installable."""
def setUp(self):
self.temp_dir = tempfile.TemporaryDirectory()
self.database_path = os.path.join(self.temp_dir.name, "test.sqlite3")
initialize_database(self.database_path)
self.previous_database_path = os.environ.get("DATABASE_PATH")
os.environ["DATABASE_PATH"] = self.database_path
self.server = ThreadingHTTPServer(("127.0.0.1", 0), AppHandler)
self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)
self.thread.start()
self.base_url = f"http://127.0.0.1:{self.server.server_port}"
# The manifest and the icon are open, but the page test below reads the
# five pages, and those need a session (section 31 point 1). Without
# one the server redirects to the login page and urllib follows it, so
# the assertion would read the login page's HTML instead.
self.authenticate()
def tearDown(self):
self.server.shutdown()
self.server.server_close()
self.thread.join(timeout=2)
if self.previous_database_path is None:
os.environ.pop("DATABASE_PATH", None)
else:
os.environ["DATABASE_PATH"] = self.previous_database_path
self.temp_dir.cleanup()
def fetch_text(self, path):
with self.get(path) as response:
self.assertEqual(response.status, 200)
return response.read().decode("utf-8")
def fetch_bytes(self, path):
with self.get(path) as response:
self.assertEqual(response.status, 200)
return response.read()
def test_the_manifest_is_served_and_describes_the_app(self):
body = self.fetch_text("/manifest.webmanifest")
manifest = json.loads(body)
self.assertEqual(manifest["name"], "VardKey")
self.assertEqual(manifest["short_name"], "VardKey")
self.assertEqual(manifest["description"], "Bitcoin Multisig Health Monitor")
self.assertEqual(manifest["start_url"], "/")
self.assertEqual(manifest["display"], "standalone")
# The colours are the ones the pages already declare in their
# theme-color meta and use as the page background. They follow the retro
# theme of section 32.2, so the two move together with the stylesheet.
self.assertEqual(manifest["theme_color"], "#c0c0c0")
self.assertEqual(manifest["background_color"], "#c0c0c0")
self.assertTrue(manifest["icons"])
def test_the_manifest_lists_the_served_icon(self):
manifest = json.loads(self.fetch_text("/manifest.webmanifest"))
entry = manifest["icons"][0]
self.assertEqual(entry["src"], "/icon.svg")
self.assertEqual(entry["type"], "image/svg+xml")
# The icon is served, so the manifest never points at a 404.
self.assertIn("svg", self.fetch_text(entry["src"]))
def test_the_manifest_lists_the_two_png_icons(self):
# The vector entry stays first, so the test above still reads it. The
# two PNGs follow, each with the size it really is (section 32.1).
manifest = json.loads(self.fetch_text("/manifest.webmanifest"))
self.assertEqual(manifest["icons"][0]["src"], "/icon.svg")
entries = {entry["src"]: entry for entry in manifest["icons"]}
for src, sizes in (("/icon-192.png", "192x192"), ("/icon-512.png", "512x512")):
self.assertIn(src, entries)
self.assertEqual(entries[src]["sizes"], sizes)
self.assertEqual(entries[src]["type"], "image/png")
def test_the_manifest_and_the_icon_are_listed_in_static_files(self):
# A file that is not listed answers 404, which would make the app
# uninstallable without failing a single page test.
self.assertIn("/manifest.webmanifest", STATIC_FILES)
self.assertIn("/icon.svg", STATIC_FILES)
self.assertIn("/icon-192.png", STATIC_FILES)
self.assertIn("/icon-512.png", STATIC_FILES)
def test_the_two_png_icons_are_served(self):
# A path that is missing from STATIC_FILES answers 404, so the manifest
# would point at a missing image without failing a page test.
for src in ("/icon-192.png", "/icon-512.png"):
body = self.fetch_bytes(src)
self.assertTrue(body.startswith(IconTests.PNG_SIGNATURE), src)
def test_every_page_links_the_manifest(self):
for path in ("/", "/setup", "/settings", "/health-check", "/history"):
body = self.fetch_text(path)
self.assertIn('<link rel="manifest" href="/manifest.webmanifest">', body)
if __name__ == "__main__":
unittest.main()