Build the site once per test run, and split every page into tags once, for all the tests that read built pages

Twelve test modules each ran the whole build, and each of them walked every page with its own
parser. They now share one build (web/tests/builtsite.py), made in a directory of the run's own,
and one recording of each page, made on all the cores. test_thumbs's second build and
test_google_tag's two builds still build, on their own, as before; the google tag builds run
side by side. web/tests/run.py runs the modules side by side. test_extra's elevation tile check
now compares with the last entry of connect-src, which is where the tile path is since the Google
tag added three before it. New tests keep the build's shortcuts honest (test_build_store.py).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Sonnet 5.5 committed 2026-11-20 16:07:33 -07:00
1 parent 84d5770e13
commit 7c321c6e15
16 files changed
+561 -87

No files matched your search

+164
View File
@@ -0,0 +1,164 @@
"""One build of the real site per test run, shared by every test that reads built pages.
Building the site is the slowest thing the suite does, and the pages and files it writes do not
change from one test to the next, so a run builds it once, into a directory of its own, and each
test module reads from there. Nothing in the suite writes into it. The directory is under
web/.cache (ignored by git), is named for the process that made it, and is removed when that
process ends, so two runs never share one and none leaves one behind. (run.py builds it for
the processes it starts and removes it itself, and says so in LONGHIKES_TEST_SITE.)
import builtsite
OUT = builtsite.OUT # where the site will be; a path, nothing is built yet
builtsite.ensure() # builds it, the first time this is called in the process
The build is the one a person runs (web/build.py), in a process of its own: the build sets module
state in olt (the authors, the place names, the map drawings) that the tests that call olt
directly must not inherit. It uses the build's store (web/.cache/store), so a build after a change
that touches no trail's files does not work the tracks out again.
"""
import atexit
import os
import shutil
import subprocess
import sys
WEB = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
CACHE = os.path.join(WEB, ".cache")
# A runner that has built the site already (web/tests/run.py, which runs the modules in
# processes of their own) names it here, and no process then builds or removes one.
PREBUILT = os.environ.get("LONGHIKES_TEST_SITE", "")
OUT = PREBUILT or os.path.join(CACHE, f"test-site-{os.getpid()}")
_built = bool(PREBUILT)
def build(out, *extra, env=None):
"""Run the site build into out (a directory that need not exist). Raises when it fails."""
done = subprocess.run([sys.executable, os.path.join(WEB, "build.py"), "--out", out, *extra],
stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, text=True, env=env)
if done.returncode:
raise RuntimeError(f"the site build failed ({done.returncode}):\n{done.stderr[-2000:]}")
def _alive(pid):
try:
os.kill(pid, 0)
except ProcessLookupError:
return False
except PermissionError:
return True
return True
def _remove_left_behind():
"""Sites of runs that were killed before they could remove their own."""
for name in os.listdir(CACHE):
pid = name[len("test-site-"):].removesuffix(".scans")
if name.startswith("test-site-") and pid.isdigit() and not _alive(int(pid)):
shutil.rmtree(os.path.join(CACHE, name), ignore_errors=True)
def ensure():
"""Build the shared site if this process has not yet; returns its directory."""
global _built
if not _built:
os.makedirs(CACHE, exist_ok=True)
_remove_left_behind()
atexit.register(shutil.rmtree, OUT, ignore_errors=True)
build(OUT)
atexit.register(shutil.rmtree, SCANS, ignore_errors=True)
warm()
_built = True
return OUT
# Reading the pages -------------------------------------------------------------------------
# Several tests walk every built page with an html.parser handler of their own. Splitting a page
# into tags is the slow part (the whole site takes about 8 s), and it is the same for all of them,
# so it is done once per page, by all the cores together, right after the build: each page's calls
# are written beside the site (OUT + ".scans"), and a handler is then given the same calls, in the
# same order, from there.
import marshal # noqa: E402
import multiprocessing # noqa: E402
from html.parser import HTMLParser # noqa: E402
SCANS = OUT + ".scans"
_CALLS = ("handle_starttag", "handle_endtag", "handle_startendtag", "handle_data",
"handle_comment", "handle_decl", "handle_pi", "unknown_decl")
_recordings = {}
class _Recorder(HTMLParser):
def __init__(self):
super().__init__(convert_charrefs=True)
self.calls = []
def _recording(name):
def record(self, *args):
self.calls.append((name, args))
return record
for _name in _CALLS:
setattr(_Recorder, _name, _recording(_name))
def _record(key):
"""((size, mtime), the calls html.parser makes for the page at key)."""
stat = os.stat(key)
recorder = _Recorder()
with open(key, encoding="utf-8") as f:
recorder.feed(f.read())
return (stat.st_size, stat.st_mtime_ns), recorder.calls
def _scan_file(key):
rel = os.path.relpath(key, OUT)
return os.path.join(SCANS, rel.replace(os.sep, "__") + ".bin")
def _scan_one(key):
stamp, calls = _record(key)
path = _scan_file(key)
with open(path + ".tmp", "wb") as f:
marshal.dump((stamp, calls), f)
os.replace(path + ".tmp", path)
def warm(workers=None):
"""Record every page of the site, on all the cores; feed() reads the recordings."""
keys = [os.path.join(base, n) for base, _, names in os.walk(OUT) for n in names if n.endswith(".html")]
if "fork" not in multiprocessing.get_all_start_methods():
return
os.makedirs(SCANS, exist_ok=True)
count = workers or min(getattr(os, "process_cpu_count", os.cpu_count)() or 1, 8)
with multiprocessing.get_context("fork").Pool(count) as pool:
for _ in pool.imap_unordered(_scan_one, keys, chunksize=8):
pass
def _saved(key, stamp):
try:
with open(_scan_file(key), "rb") as f:
kept_stamp, calls = marshal.load(f)
except (OSError, ValueError, EOFError):
return None
return calls if kept_stamp == stamp else None
def feed(path, handler):
"""Give `handler` (an HTMLParser with convert_charrefs=True) the page at `path`, as
handler.feed(open(path).read()) would. Returns the handler."""
assert handler.convert_charrefs, "a recording replays what convert_charrefs=True gives"
key = os.path.abspath(path)
stat = os.stat(key)
stamp = (stat.st_size, stat.st_mtime_ns)
held = _recordings.get(key)
if held is None or held[0] != stamp:
calls = _saved(key, stamp) if key.startswith(OUT + os.sep) else None
if calls is None:
calls = _record(key)[1]
held = _recordings[key] = (stamp, calls)
for name, args in held[1]:
getattr(handler, name)(*args)
return handler
+111
View File
@@ -0,0 +1,111 @@
#!/usr/bin/env python3
"""Run the site's tests with the test modules in processes of their own, side by side.
python3 web/tests/run.py [-j N] [module ...]
It runs exactly the tests `python3 -m unittest discover -s web/tests` runs (every test_*.py here),
and fails when any of them fails, any module cannot be loaded or no test runs. What it adds is time:
the site is built once, up front, into a directory it names to every module it starts
(LONGHIKES_TEST_SITE, see builtsite.py), and the modules, which share no files that they write, run
together, N at a time (the cores this process may use, at most 8, unless -j says). The tests that
read no built page start at once, while the site is being built. Python 3 standard library only.
"""
import argparse
import concurrent.futures
import glob
import os
import re
import shutil
import subprocess
import sys
import time
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import builtsite # noqa: E402
# The slowest modules start first, so that none is left running alone at the end.
SLOW_FIRST = ("test_thumbs", "test_google_tag", "test_pages", "test_saved", "test_images", "test_short_links",
"test_fingerprint", "test_extra", "test_structured_data", "test_views", "test_onward_order")
def cores():
return getattr(os, "process_cpu_count", os.cpu_count)() or 1
def modules_under(only):
names = sorted(os.path.basename(p)[:-3] for p in glob.glob(os.path.join(HERE, "test_*.py")))
if only:
unknown = [m for m in only if m not in names]
if unknown:
raise SystemExit(f"no such test module: {', '.join(unknown)}")
names = [m for m in names if m in only]
return sorted(names, key=lambda m: (SLOW_FIRST.index(m) if m in SLOW_FIRST else len(SLOW_FIRST), m))
def reads_the_site(module):
with open(os.path.join(HERE, module + ".py"), encoding="utf-8") as f:
return "builtsite" in f.read()
def build_and_scan(site):
"""Build the site, then split every page into its tags once, on all the cores (builtsite.warm)."""
assert site == builtsite.OUT
builtsite.build(site)
builtsite.warm()
def run_module(module, site):
"""(module, tests run, passed, seconds, output) for one module run in a process of its own."""
start = time.time()
done = subprocess.run([sys.executable, "-m", "unittest", "discover", "-s", HERE, "-p", module + ".py"],
capture_output=True, text=True,
env=dict(os.environ, LONGHIKES_TEST_SITE=site) if site else os.environ)
ran = re.search(r"^Ran (\d+) tests? in", done.stderr, re.M)
return module, int(ran.group(1)) if ran else 0, done.returncode == 0 and bool(ran), \
time.time() - start, done.stderr + done.stdout
def main(argv=None):
ap = argparse.ArgumentParser(description="Run the site's tests, modules side by side.")
ap.add_argument("modules", nargs="*", help="test modules to run (default: all)")
ap.add_argument("-j", "--jobs", type=int, default=min(cores(), 8), help="modules at a time")
args = ap.parse_args(argv)
start = time.time()
modules = modules_under(args.modules)
wants_site = [m for m in modules if reads_the_site(m)]
site = ""
results = []
with concurrent.futures.ThreadPoolExecutor(max_workers=max(1, args.jobs) + 1) as pool:
building = None
if wants_site:
site = os.path.join(builtsite.CACHE, f"test-site-{os.getpid()}")
os.makedirs(builtsite.CACHE, exist_ok=True)
building = pool.submit(build_and_scan, site)
try:
lanes = concurrent.futures.ThreadPoolExecutor(max_workers=max(1, args.jobs))
with lanes:
waiting = [lanes.submit(run_module, m, "") for m in modules if m not in wants_site]
if building is not None:
building.result() # a failed build stops the run
waiting += [lanes.submit(run_module, m, site) for m in modules if m in wants_site]
for job in concurrent.futures.as_completed(waiting):
results.append(job.result())
module, ran, ok, seconds, _ = results[-1]
print(f"{'ok ' if ok else 'FAIL'} {module:<32} {ran:>4} tests {seconds:6.1f} s", flush=True)
finally:
if site:
shutil.rmtree(site, ignore_errors=True)
shutil.rmtree(builtsite.SCANS, ignore_errors=True)
failed = [r for r in results if not r[2]]
for module, ran, ok, seconds, output in sorted(failed):
print(f"\n{'=' * 70}\n{module}\n{output}")
total = sum(r[1] for r in results)
print(f"\nRan {total} tests in {len(results)} modules in {time.time() - start:.1f} s: "
+ (f"FAILED in {', '.join(sorted(r[0] for r in failed))}" if failed else "OK"))
return 1 if failed or not total else 0
if __name__ == "__main__":
sys.exit(main())
+194
View File
@@ -0,0 +1,194 @@
"""The build's shortcuts must never change what it writes: simplifying for two tolerances at once,
the workers that build the trails side by side, and the store that keeps a trail's derived files
(web/build.py). Each is checked against doing the work the slow way."""
import ast
import contextlib
import filecmp
import io
import json
import os
import random
import shutil
import sys
import tempfile
import unittest
import zipfile
from unittest import mock
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import build # noqa: E402
from olt import geo, records # noqa: E402
REAL_ROOT = build.ROOT
class FakePages:
@staticmethod
def render_site(recs, out_dir, root):
pass
def walk(path, tol_walk=0.0004, n=3000, seed=1):
rnd = random.Random(seed)
lon, lat, out = -110.0, 40.0, []
for _ in range(n):
lon += rnd.gauss(0, tol_walk)
lat += rnd.gauss(0.0001, tol_walk)
out.append([round(lon, 6), round(lat, 6), round(rnd.uniform(1000, 3000), 1)])
return out
class SimplifyTogetherTest(unittest.TestCase):
def test_both_tolerances_in_one_walk_equal_two_walks(self):
parts = [walk("a", seed=1), walk("b", 0.0001, 5000, 2), walk("c", 0.002, 800, 3), [[0, 0], [1, 1]]]
for tols in ([5.0, 30.0], [30.0, 5.0], [750.0, 5.0, 30.0], [5.0, 5.0], [0.0, 1.0]):
together = geo.simplify_multi(parts, tols)
for tol, got in zip(tols, together):
self.assertEqual(got, geo.simplify(parts, tol), tol)
def test_a_real_track_gives_the_same_points(self):
parts = geo.read_parts(os.path.join(REAL_ROOT, "batona", "line.geojson"))
a, b = geo.simplify_multi(parts, [build.GPX_TOL_M, build.MAP_TOL_M])
self.assertEqual(a, geo.simplify(parts, build.GPX_TOL_M))
self.assertEqual(b, geo.simplify(parts, build.MAP_TOL_M))
self.assertLess(geo.point_count(b), geo.point_count(a))
class CodeFilesTest(unittest.TestCase):
def test_the_files_a_trail_is_built_from_are_closed_under_their_imports(self):
# The store's key is made of these files: one that is missing would let a change to it
# leave stale files in the store.
olt = os.path.join(build.HERE, "olt")
listed = {os.path.abspath(p) for p in build.CODE_FILES}
for path in sorted(listed):
if os.path.dirname(path) != olt:
continue
with open(path, encoding="utf-8") as f:
tree = ast.parse(f.read())
for node in ast.walk(tree):
if isinstance(node, ast.ImportFrom) and node.level == 1:
names = [node.module] if node.module else [a.name for a in node.names]
for name in names:
self.assertIn(os.path.join(olt, name + ".py"), listed,
f"{os.path.basename(path)} imports olt.{name}, which the build's key does not cover")
def tree_files(root):
found = {}
for base, _, names in os.walk(root):
for n in names:
found[os.path.relpath(os.path.join(base, n), root)] = os.path.join(base, n)
return found
def same_tree(case, a, b):
"""Every file the same, byte for byte; a zip by its members (their dates are the time they were written)."""
fa, fb = tree_files(a), tree_files(b)
case.assertEqual(sorted(fa), sorted(fb))
for rel in fa:
if rel.endswith(".zip"):
za, zb = zipfile.ZipFile(fa[rel]), zipfile.ZipFile(fb[rel])
case.assertEqual(za.namelist(), zb.namelist(), rel)
for name in za.namelist():
case.assertEqual(za.read(name), zb.read(name), f"{rel}: {name}")
else:
case.assertTrue(filecmp.cmp(fa[rel], fb[rel], shallow=False), rel)
class BuildShortcutsTest(unittest.TestCase):
"""A small repository of real trails: the smallest PARALLEL_FROM + 2 of them."""
@classmethod
def setUpClass(cls):
cls.tmp = tempfile.TemporaryDirectory()
cls.root = os.path.join(cls.tmp.name, "repo")
os.makedirs(cls.root)
sizes = sorted((build.tree_size(d), d) for d in os.listdir(REAL_ROOT)
if os.path.isfile(os.path.join(REAL_ROOT, d, "trail.toml")))
cls.ids = [d for _, d in sizes if "line" in records.load_record(REAL_ROOT, d)["derived"]["files"]][:build.PARALLEL_FROM + 2]
cls.ids += [d for _, d in sizes if d not in cls.ids][:2] # and two that may have no track
for tid in cls.ids:
shutil.copytree(os.path.join(REAL_ROOT, tid), os.path.join(cls.root, tid))
for name in ("trails.csv", "index.geojson"):
shutil.copyfile(os.path.join(REAL_ROOT, name), os.path.join(cls.root, name))
@classmethod
def tearDownClass(cls):
cls.tmp.cleanup()
def build(self, out, cache, jobs, *extra):
err = io.StringIO()
patches = (mock.patch.object(build, "ROOT", self.root), mock.patch.object(build, "CACHE_DIR", cache),
mock.patch.object(build, "import_pages", lambda: FakePages),
mock.patch.dict(os.environ, {"LONGHIKES_JOBS": str(jobs)}))
with contextlib.ExitStack() as stack:
for p in patches:
stack.enter_context(p)
stack.enter_context(contextlib.redirect_stdout(io.StringIO()))
stack.enter_context(contextlib.redirect_stderr(err))
build.main(["--out", out, *extra])
return err.getvalue()
def key(self, tid):
with mock.patch.object(build, "ROOT", self.root):
return build.trail_key(tid)
def dirs(self, name):
base = os.path.join(self.tmp.name, name)
return os.path.join(base, "site"), os.path.join(base, "cache")
def test_workers_write_what_one_process_writes(self):
self.assertGreaterEqual(len(self.ids), build.PARALLEL_FROM)
(one, c1), (many, c2) = self.dirs("one"), self.dirs("many")
w1 = self.build(one, c1, 1)
w2 = self.build(many, c2, 4)
same_tree(self, one, many)
self.assertEqual(sorted(w1.splitlines()), sorted(w2.splitlines()))
with open(os.path.join(many, "data", "trails.json"), encoding="utf-8") as f:
self.assertEqual(sorted(r["id"] for r in json.load(f)), sorted(self.ids))
def test_files_from_the_store_are_the_files_that_were_worked_out(self):
(first, cache), (again, _) = self.dirs("store1"), self.dirs("store2")
self.build(first, cache, 1)
kept = os.path.join(cache, "store")
self.assertTrue(os.path.isdir(kept))
self.build(again, cache, 1, "--force") # worked out again, nothing read from the store
shutil.rmtree(again)
os.remove(os.path.join(cache, self.ids[0] + ".json"))
for name in os.listdir(cache): # the store alone: no per-trail cache files
if name.endswith(".json"):
os.remove(os.path.join(cache, name))
self.build(again, cache, 1) # a new directory, filled from the store
same_tree(self, first, again)
def test_a_changed_source_is_worked_out_again(self):
out, cache = self.dirs("change")
self.build(out, cache, 1)
tid = next(t for t in self.ids if os.path.isfile(os.path.join(self.root, t, "line.geojson")))
line = os.path.join(self.root, tid, "line.geojson")
with open(line, encoding="utf-8") as f:
original = f.read()
with open(os.path.join(out, "trails", tid, f"{tid}.gpx"), encoding="utf-8") as f:
gpx_before = f.read()
key_before = self.key(tid)
try:
moved = [[[c[0] + 0.5, *c[1:]] for c in part] for part in geo.parts_from_geojson(json.loads(original))]
with open(line, "w", encoding="utf-8") as f:
json.dump({"type": "Feature", "properties": {},
"geometry": {"type": "MultiLineString", "coordinates": moved}}, f)
self.assertNotEqual(self.key(tid), key_before)
(with_store, _), (without, empty) = self.dirs("change2"), self.dirs("change3")
self.build(with_store, cache, 1) # the store holds the old track's files, under the old key
self.build(without, empty, 1) # nothing kept
same_tree(self, with_store, without)
with open(os.path.join(with_store, "trails", tid, f"{tid}.gpx"), encoding="utf-8") as f:
self.assertNotEqual(f.read(), gpx_before)
finally:
with open(line, "w", encoding="utf-8") as f:
f.write(original)
self.assertEqual(self.key(tid), key_before)
if __name__ == "__main__":
unittest.main()
+4 -1
View File
@@ -23,7 +23,9 @@ except Exception: # Pillow, fontTools or brotli missing
from olt import cards, records, site # noqa: E402
SITE = os.path.join(WEB, ".cache", "test-site")
import builtsite # noqa: E402
SITE = builtsite.OUT
GAP = 6 # px of clear space between two lines of text
TRACK_GAP = 24 # px between the text column and the track
EDGE = 40 # px between the track and the card's edges
@@ -47,6 +49,7 @@ def track_parts(tid):
class CardLayout(unittest.TestCase):
@classmethod
def setUpClass(cls):
builtsite.ensure()
cls.tmp = tempfile.TemporaryDirectory()
cls.fonts = make_cards.load_fonts(cls.tmp.name)
cls.measure = make_cards.Measure(cls.fonts)
+5 -6
View File
@@ -4,7 +4,6 @@ import html
import json
import os
import re
import subprocess
import sys
import unittest
import zipfile
@@ -16,13 +15,13 @@ sys.path.insert(0, WEB)
import serve # noqa: E402
from olt import common, docs, facets, home, records, regions as regions_mod, seo, site, words # noqa: E402
OUT = os.path.join(WEB, ".cache", "test-site")
import builtsite # noqa: E402
OUT = builtsite.OUT
def setUpModule():
os.makedirs(os.path.dirname(OUT), exist_ok=True)
subprocess.run([sys.executable, os.path.join(WEB, "build.py"), "--out", OUT],
check=True, stdout=subprocess.DEVNULL)
builtsite.ensure()
def read_out(relpath):
@@ -407,7 +406,7 @@ class HeadersTest(unittest.TestCase):
self.assertIn("img-src 'self' data: blob: https://*.google-analytics.com https://*.googletagmanager.com;", csp)
with open(os.path.join(WEB, "assets", "map", "outdoor.json"), encoding="utf-8") as f:
dem = json.load(f)["sources"]["olt-dem"]["tiles"][0]
self.assertTrue(dem.startswith(connect[2]), dem)
self.assertTrue(dem.startswith(connect[-1]), dem)
class SeoTest(unittest.TestCase):
+4 -5
View File
@@ -8,7 +8,6 @@ The fixture tests need no built site; BuiltVocabularyTest builds it (as test_pag
import html
import os
import re
import subprocess
import sys
import unittest
@@ -20,7 +19,9 @@ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from olt import facets, home, records, trail, words # noqa: E402
from test_hike import GH, fake, text, top_part # noqa: E402
OUT = os.path.join(WEB, ".cache", "test-site")
import builtsite # noqa: E402
OUT = builtsite.OUT
def route(i=1, policy="sold", **kw):
@@ -258,9 +259,7 @@ def site_words(doc):
class BuiltVocabularyTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
os.makedirs(os.path.dirname(OUT), exist_ok=True)
subprocess.run([sys.executable, os.path.join(WEB, "build.py"), "--out", OUT],
check=True, stdout=subprocess.DEVNULL)
builtsite.ensure()
def read(self, rel):
with open(os.path.join(OUT, *rel.split("/")), encoding="utf-8") as f:
+5 -8
View File
@@ -4,7 +4,6 @@ import hashlib
import os
import re
import shutil
import subprocess
import sys
import tempfile
import unittest
@@ -17,7 +16,9 @@ sys.path.insert(0, WEB)
from olt import fingerprint, layout # noqa: E402
import serve # noqa: E402
OUT = os.path.join(WEB, ".cache", "test-site")
import builtsite # noqa: E402
OUT = builtsite.OUT
NAME = re.compile(r"^/immutable/[a-z0-9.-]+\.[0-9a-f]{10}\.[a-z0-9]+$")
@@ -135,9 +136,7 @@ class Refs(HTMLParser):
class BuiltSiteTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
os.makedirs(os.path.dirname(OUT), exist_ok=True)
subprocess.run([sys.executable, os.path.join(WEB, "build.py"), "--out", OUT],
check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
builtsite.ensure()
cls.pages = []
for base, _, names in os.walk(OUT):
for n in names:
@@ -149,9 +148,7 @@ class BuiltSiteTest(unittest.TestCase):
originals = set(fingerprint.FILES)
used = 0
for page in self.pages:
refs = Refs()
with open(page, encoding="utf-8") as f:
refs.feed(f.read())
refs = builtsite.feed(page, Refs())
for key, url in refs.urls:
self.assertNotIn(url, originals, f"{page}: {url}")
if url.startswith("/immutable/"):
+8 -4
View File
@@ -24,7 +24,8 @@ def html_files(root):
yield os.path.join(base, n)
def build(out, tag):
def start_build(out, tag):
"""Start a build of the site into out with this tag in site.toml (none when tag is empty)."""
cfg = os.path.join(os.path.dirname(out), "site.toml")
with open(os.path.join(WEB, "site.toml"), encoding="utf-8") as f:
text = re.sub(r'(?m)^google_tag = .*\n', "", f.read())
@@ -33,17 +34,20 @@ def build(out, tag):
code = ("import sys; sys.path.insert(0, %r); from olt import site; "
"site.SITE_TOML = %r; site.load.cache_clear(); import build; build.main(['--out', %r])"
% (WEB, cfg, out))
subprocess.run([sys.executable, "-c", code], check=True, cwd=WEB,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
return subprocess.Popen([sys.executable, "-c", code], cwd=WEB,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
class GoogleTagTest(unittest.TestCase):
def test_every_built_page_has_the_tag_once_and_none_without_the_setting(self):
with tempfile.TemporaryDirectory() as tmp:
on, off = os.path.join(tmp, "on", "site"), os.path.join(tmp, "off", "site")
started = []
for out, tag in ((on, TAG_ID), (off, "")):
os.makedirs(os.path.dirname(out))
build(out, tag)
started.append(start_build(out, tag)) # both at once: they share nothing
for proc in started:
self.assertEqual(proc.wait(), 0)
pages_on = list(html_files(on))
self.assertGreater(len(pages_on), 200)
for name in ("404.html", os.path.join("saved", "index.html"), "index.html"):
+12 -9
View File
@@ -2,7 +2,6 @@
and the logos of the first screen are not lazy-loaded while the rest are."""
import os
import re
import subprocess
import sys
import tempfile
import unittest
@@ -14,7 +13,9 @@ sys.path.insert(0, WEB)
from olt import home, thumbs # noqa: E402
OUT = os.path.join(WEB, ".cache", "test-site")
import builtsite # noqa: E402
OUT = builtsite.OUT
class Imgs(HTMLParser):
@@ -32,11 +33,15 @@ class Imgs(HTMLParser):
self.imgs.append(a)
_imgs = {}
def page_imgs(path):
p = Imgs()
with open(path, encoding="utf-8") as f:
p.feed(f.read())
return p.imgs
"""The <img> tags of a page, read once per run (the tests only look at the result)."""
stamp = (os.path.abspath(path), os.stat(path).st_mtime_ns)
if stamp not in _imgs:
_imgs[stamp] = builtsite.feed(path, Imgs()).imgs
return _imgs[stamp]
class SvgSizeTest(unittest.TestCase):
@@ -63,9 +68,7 @@ class SvgSizeTest(unittest.TestCase):
class BuiltSiteTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
os.makedirs(os.path.dirname(OUT), exist_ok=True)
subprocess.run([sys.executable, os.path.join(WEB, "build.py"), "--out", OUT],
check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
builtsite.ensure()
cls.pages = []
for base, _, names in os.walk(OUT):
for n in names:
+4 -5
View File
@@ -5,7 +5,6 @@ import ast
import json
import os
import re
import subprocess
import sys
import unittest
@@ -15,16 +14,16 @@ sys.path.insert(0, WEB)
from olt import common, layout, records # noqa: E402
OUT = os.path.join(WEB, ".cache", "test-site")
import builtsite # noqa: E402
OUT = builtsite.OUT
STYLE = os.path.join(WEB, "assets", "map", "outdoor.json")
VENDOR = os.path.join(WEB, "assets", "vendor")
MAP_FONTS = {"Noto Sans Regular", "Noto Sans Italic", "Noto Sans Bold"} # served by OpenFreeMap
def setUpModule():
os.makedirs(os.path.dirname(OUT), exist_ok=True)
subprocess.run([sys.executable, os.path.join(WEB, "build.py"), "--out", OUT],
check=True, stdout=subprocess.DEVNULL)
builtsite.ensure()
def read(*parts):
+13 -11
View File
@@ -1,12 +1,10 @@
"""Tests for the generated HTML pages (web/olt/pages.py and friends).
The first run builds the whole site into web/.cache/test-site (about a minute:
every line is simplified); later runs are incremental and take seconds.
The whole site is built once per run, by builtsite.py, and read from there.
"""
import html
import os
import re
import subprocess
import sys
import tempfile
import tomllib
@@ -19,7 +17,9 @@ sys.path.insert(0, WEB)
from olt import home, layout, pages, records, regions, site, trail, words # noqa: E402
OUT = os.path.join(WEB, ".cache", "test-site")
import builtsite # noqa: E402
OUT = builtsite.OUT
# Linked from the shared navigation and footer; written by other page modules.
# Remove a path from this set once its page exists.
@@ -51,11 +51,15 @@ class Tags(HTMLParser):
self._in_script = None
_parsed = {}
def parse(path):
p = Tags()
with open(path, encoding="utf-8") as f:
p.feed(f.read())
return p
"""The tags and scripts of a page, read once per run (the tests only look at the result)."""
stamp = (os.path.abspath(path), os.stat(path).st_mtime_ns)
if stamp not in _parsed:
_parsed[stamp] = builtsite.feed(path, Tags())
return _parsed[stamp]
def html_files(out):
@@ -78,9 +82,7 @@ def resolve(out, url):
class BuiltSiteTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
os.makedirs(os.path.dirname(OUT), exist_ok=True)
subprocess.run([sys.executable, os.path.join(WEB, "build.py"), "--out", OUT],
check=True, stdout=subprocess.DEVNULL)
builtsite.ensure()
cls.records = records.load_records(ROOT)
cls.pages = {}
for rec in cls.records:
+4 -6
View File
@@ -3,7 +3,6 @@ files, description endings, guessable-address redirects, the print rules, the ex
list-size logo thumbnails."""
import os
import re
import subprocess
import sys
import unittest
@@ -14,14 +13,13 @@ sys.path.insert(0, WEB)
import serve # noqa: E402
from olt import common, records, redirects, thumbs # noqa: E402
OUT = os.path.join(WEB, ".cache", "test-site")
import builtsite # noqa: E402
OUT = builtsite.OUT
def setUpModule():
if not os.path.isfile(os.path.join(OUT, "_redirects")):
os.makedirs(os.path.dirname(OUT), exist_ok=True)
subprocess.run([sys.executable, os.path.join(WEB, "build.py"), "--out", OUT],
check=True, stdout=subprocess.DEVNULL)
builtsite.ensure()
def read(relpath):
+5 -6
View File
@@ -9,7 +9,6 @@ indexed and is not in the sitemap; nothing is inline. The behaviour itself
import html
import os
import re
import subprocess
import sys
import unittest
from html.parser import HTMLParser
@@ -20,13 +19,13 @@ sys.path.insert(0, WEB)
from olt import common, home, layout, records, saved, seo, site # noqa: E402
OUT = os.path.join(WEB, ".cache", "test-site")
import builtsite # noqa: E402
OUT = builtsite.OUT
def setUpModule():
os.makedirs(os.path.dirname(OUT), exist_ok=True)
subprocess.run([sys.executable, os.path.join(WEB, "build.py"), "--out", OUT],
check=True, stdout=subprocess.DEVNULL)
builtsite.ensure()
def read_out(relpath):
@@ -129,7 +128,7 @@ class HeaderOnEveryPageTest(unittest.TestCase):
doc = read_out(rel)
self.assertNotIn("<style", doc, rel)
inline = 0
for tag, a, _ in tree(doc).tags:
for tag, a, _ in builtsite.feed(os.path.join(OUT, *rel.split("/")), Tree()).tags:
self.assertFalse([k for k in a if k.startswith("on")], f"{tag} in {rel}")
if tag == "script" and not (a.get("src") or a.get("type") in ("application/json", "application/ld+json")):
inline += 1
+4 -4
View File
@@ -24,7 +24,9 @@ import trail_numbers # noqa: E402
from olt import records, saved # noqa: E402
NODE = shutil.which("node")
OUT = os.path.join(WEB, ".cache", "test-site")
import builtsite # noqa: E402
OUT = builtsite.OUT
# The owner's own list of 49 trails, in the order saved: a real fixture.
OWNER = ("eastern-sierra-high-route,sierra-high-route,southern-sierra-high-route,uinta-highline,grand-moab-route,"
@@ -130,9 +132,7 @@ class CodeTest(unittest.TestCase):
class NumbersOnThePageTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
os.makedirs(os.path.dirname(OUT), exist_ok=True)
subprocess.run([sys.executable, os.path.join(WEB, "build.py"), "--out", OUT],
check=True, stdout=subprocess.DEVNULL)
builtsite.ensure()
with open(os.path.join(OUT, "saved", "index.html"), encoding="utf-8") as f:
cls.page = f.read()
+5 -6
View File
@@ -3,13 +3,12 @@ robots headers, the 404, the Atom feed, llms.txt and the favicon.
The JSON-LD is checked against the properties schema.org and Google Search Central document
for each type (REQUIRED below, read 2026-11); Google's Rich Results Test itself cannot be run
here. The site is built into web/.cache/test-site, as the other page tests do.
here. The site is the one built once per run by builtsite.py, as for the other page tests.
"""
import html
import json
import os
import re
import subprocess
import sys
import unittest
import xml.etree.ElementTree as ET
@@ -21,7 +20,9 @@ sys.path.insert(0, WEB)
import serve # noqa: E402
from olt import browse, cards, common, docs, feed, records, regions, seo, site, thumbs # noqa: E402
OUT = os.path.join(WEB, ".cache", "test-site")
import builtsite # noqa: E402
OUT = builtsite.OUT
SITE = site.load()
BASE = SITE.base_url
@@ -120,9 +121,7 @@ def visible_crumbs(doc):
def setUpModule():
os.makedirs(os.path.dirname(OUT), exist_ok=True)
subprocess.run([sys.executable, os.path.join(WEB, "build.py"), "--out", OUT],
check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
builtsite.ensure()
class RequiredPropertiesTest(unittest.TestCase):
+19 -16
View File
@@ -3,7 +3,6 @@ import contextlib
import io
import os
import shutil
import subprocess
import sys
import tempfile
import unittest
@@ -15,7 +14,9 @@ sys.path.insert(0, WEB)
from olt import records, thumbs # noqa: E402
OUT = os.path.join(WEB, ".cache", "test-site")
import builtsite # noqa: E402
OUT = builtsite.OUT
MAX_SIDE = 256
@@ -29,11 +30,15 @@ class Imgs(HTMLParser):
self.imgs.append(dict(attrs))
_imgs = {}
def page_imgs(path):
p = Imgs()
with open(path, encoding="utf-8") as f:
p.feed(f.read())
return p.imgs
"""The <img> tags of a page, read once per run (the tests only look at the result)."""
stamp = (os.path.abspath(path), os.stat(path).st_mtime_ns)
if stamp not in _imgs:
_imgs[stamp] = builtsite.feed(path, Imgs()).imgs
return _imgs[stamp]
def html_files(out):
@@ -63,11 +68,6 @@ def repository_logos():
return found
def build():
subprocess.run([sys.executable, os.path.join(WEB, "build.py"), "--out", OUT],
check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
class ThumbFilesTest(unittest.TestCase):
def test_every_repository_logo_has_a_thumbnail_no_larger_than_256(self):
logos = repository_logos()
@@ -147,8 +147,7 @@ class ThumbFilesTest(unittest.TestCase):
class BuiltPagesTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
os.makedirs(os.path.dirname(OUT), exist_ok=True)
build()
builtsite.ensure()
cls.records = records.load_records(ROOT)
cls.png = [r["id"] for r in cls.records
if r["derived"]["files"].get("shield", "").endswith(".png")]
@@ -195,9 +194,13 @@ class BuiltPagesTest(unittest.TestCase):
self.assertEqual(img.get("loading"), "lazy")
def test_thumbnails_survive_a_second_build(self):
build()
for tid in self.png:
self.assertTrue(os.path.isfile(os.path.join(OUT, "trails", tid, thumbs.THUMB_NAME)), tid)
# A build over a site that is already built, on a copy: the shared one is never written to.
with tempfile.TemporaryDirectory() as tmp:
again = os.path.join(tmp, "site")
shutil.copytree(OUT, again)
builtsite.build(again)
for tid in self.png:
self.assertTrue(os.path.isfile(os.path.join(again, "trails", tid, thumbs.THUMB_NAME)), tid)
if __name__ == "__main__":