Build the site and run its tests several times faster, with the output unchanged
Mirror to forge / mirror (push) Canceled after 0s
Validate / validate (push) Canceled after 0s
Validate / history (push) Canceled after 0s
Validate / site (push) Canceled after 0s
Validate / deploy (push) Canceled after 0s

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-20 18:02:25 -07:00
commit 4a89833162
28 files changed
+1256 -185

No files matched your search

+16 -1
View File
@@ -55,7 +55,22 @@ jobs:
# Standard library only: no packages to install, and no ImageMagick.
# web/tools/make_thumbs.py and make_cards.py are manual tools; web/thumbs/ and
# web/cards/ are committed and the build only copies them (web/olt/thumbs.py, cards.py).
- run: python3 -m unittest discover -s web/tests
#
# The build's store (web/build.py) keeps each trail's derived files under a hash of
# everything they are made from, so a restored store can only ever save work: an entry is
# used when its hash is the hash of the files now in the checkout, and is otherwise ignored
# and replaced. The cache key follows the trails' files and the build's code, so a change
# to either makes a new cache from the nearest old one.
- uses: actions/cache@v4
with:
path: web/.cache/store
key: site-store-${{ hashFiles('*/trail.toml', '*/*.geojson', '*/shield.*', '*/elevation.json', 'web/build.py', 'web/olt/geo.py', 'web/olt/hike.py', 'web/olt/records.py', 'web/olt/words.py', 'web/olt/elevation.py', 'web/olt/markup.py', 'web/site.toml') }}
restore-keys: site-store-
# The same tests as `python3 -m unittest discover -s web/tests`, with the modules run side
# by side and the site built once for all of them (web/tests/run.py).
- run: python3 web/tests/run.py
# The plain build, as Netlify runs it: this is the second build of the job, so the store the
# tests filled makes it quick.
- run: python3 web/build.py --out _site
# Netlify builds the site from this repository when asked to. Asking only
+6
View File
@@ -1,5 +1,11 @@
# Changelog
## 2026-11-20 - Faster builds and tests, and reproducible downloads
- The site builds in about a quarter of the time on a warm cache and the whole test suite runs in about a quarter of its former time. The pages are unchanged: every file of a build matches a build of the previous version except the two bulk downloads (all GPX, all GeoJSON).
- The two bulk downloads (`all-gpx.zip`, `all-geojson.zip`) now carry a fixed time on every member and are the same bytes whenever they are made from the same files. Their contents are unchanged; the bytes change once, with this release.
- For contributors: `python3 web/tests/run.py` runs the same tests as `python3 -m unittest discover -s web/tests`, side by side. `LONGHIKES_JOBS=1` makes the build use one process. A build worker that fails now stops the build with its error.
## 2026-11-20 - Every trail now has a season
- All 223 trails now have a season. 148 come from a page that states one. 3 were set by judgement from pages of at least two publishers that disagree, none of them the trail's own, its association's or its route author's. The other 72 are estimates, because no page states a season for them; three of those (the Finger Lakes Trail, the Ice Age Trail and the Ozark Trail) have a page that contradicts itself or two pages from one publisher that differ, and the note says so.
+401 -80
View File
@@ -9,11 +9,15 @@ import sys
sys.dont_write_bytecode = True
import argparse
import concurrent.futures
import hashlib
import json
import multiprocessing
import os
import shutil
import time
import zipfile
import zlib
HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.dirname(HERE)
@@ -28,7 +32,15 @@ OVERVIEW_TOL_M = 750.0
CODE_FILES = [os.path.join(HERE, "build.py"),
os.path.join(HERE, "olt", "geo.py"),
os.path.join(HERE, "olt", "hike.py"),
os.path.join(HERE, "olt", "records.py")]
os.path.join(HERE, "olt", "records.py"),
# what those import (a test, test_build.py, keeps this list closed under imports)
os.path.join(HERE, "olt", "words.py"),
os.path.join(HERE, "olt", "elevation.py"),
os.path.join(HERE, "olt", "markup.py"),
# and what build.py itself imports (the pages step, olt.pages, is not trail code)
os.path.join(HERE, "olt", "fingerprint.py"),
os.path.join(HERE, "olt", "redirects.py"),
os.path.join(HERE, "olt", "site.py")]
# Incremental-build cache, deliberately outside the publish directory.
CACHE_DIR = os.path.join(HERE, ".cache")
# Files copied verbatim into the root of the publish directory (_headers, ...).
@@ -78,13 +90,13 @@ def mtime(path):
return os.path.getmtime(path)
def dir_mtime(path):
"""Newest mtime of the files directly inside a directory."""
return max(mtime(os.path.join(path, n)) for n in os.listdir(path)
if os.path.isfile(os.path.join(path, n)))
_WARNINGS = None # in a worker process: the warnings it raised, which the parent prints
def warn(message):
if _WARNINGS is not None:
_WARNINGS.append(message)
return
print(f"warning: {message}", file=sys.stderr)
@@ -165,22 +177,21 @@ def read_cache(cache_path):
return cache if isinstance(cache, dict) else None
def up_to_date(rec, files, tdir, cache_path, code_mtime):
"""True when the outputs are complete, newer than the sources, and the cache
records exactly the set of outputs this record now calls for."""
def up_to_date(rec, files, tdir, cache_path, key):
"""True when the outputs are complete, were made from the trail's content as it is now (the
key the cache entry holds is the trail's current key: modification times are not consulted,
so a file put back to an older time is still seen), and the cache records exactly the set of
outputs this record now calls for."""
names = trail_outputs(rec["id"], files, rec)
cache = read_cache(cache_path)
if cache is None or cache.get("outputs") != sorted(names):
if cache is None or cache.get("outputs") != sorted(names) or cache.get("key") != key:
return False
if cache.get("creator") != gpx_creator(): # the site was renamed: the GPX creator is stale
return False
if "line" in files and "bbox" not in cache:
return False
paths = [os.path.join(tdir, n) for n in names] + [cache_path]
if not all(os.path.isfile(p) for p in paths):
return False
newest_in = max(code_mtime, dir_mtime(os.path.join(ROOT, rec["id"])))
return all(mtime(p) >= newest_in for p in paths)
return all(os.path.isfile(p) for p in paths)
def download(tdir, name, role, note, fmt):
@@ -192,8 +203,9 @@ def build_set(tid, key, path, stem, gpx_name, tdir, gpx_args, stats):
"""Write one line file's outputs. Returns (parts, map parts), or None when
the file has no line (or nothing is left of it after rounding)."""
parts = geo.read_parts(path)
simple = geo.round_coords(geo.simplify(parts, GPX_TOL_M), 6)
small = geo.round_coords(geo.simplify(parts, MAP_TOL_M), 5)
fine, coarse = geo.simplify_multi(parts, [GPX_TOL_M, MAP_TOL_M]) # one walk serves both
simple = geo.round_coords(fine, 6)
small = geo.round_coords(coarse, 5)
if not parts or not simple or not small:
warn(f"{tid}: the {key} file {os.path.relpath(path, ROOT)} has no line; "
f"treated as having no {key}")
@@ -204,9 +216,151 @@ def build_set(tid, key, path, stem, gpx_name, tdir, gpx_args, stats):
return parts, small
def build_trail(rec, out_dir, code_mtime, force, stats):
def compute_trail(rec, files, tdir, stats):
"""Write the outputs of one trail from its source files. Returns (files, cache): the files
that produced output, and what the pages need of the line (bbox, point count, elevation)."""
tid = rec["id"]
src = rec.get("source", {})
cache = {}
gpx_args = dict(url=src.get("url", ""), attribution=src.get("attribution", ""),
licence=src.get("licence", ""), licence_text=src.get("licence_text", ""),
creator=gpx_creator(),
permission=({k: src[k] for k in ("permission_quote", "permission_by", "permission_date", "permission_url")
if k in src} if src.get("licence") == "stated-permission" else None))
maps = []
if "line" in files:
built = build_set(tid, "line", os.path.join(ROOT, files["line"]), tid,
rec["name"], tdir, gpx_args, stats)
if built is None:
del files["line"]
else:
parts, small = built
maps.append(multiline_feature(small, {"role": "main"}))
cache = {"bbox": geo.bbox(parts), "points": geo.point_count(parts),
"elevation": geo.has_elevation(parts)}
if "alternates" in files:
built = build_set(tid, "alternates", os.path.join(ROOT, files["alternates"]),
f"{tid}-alternates", rec["name"] + " (alternates)",
tdir, gpx_args, stats)
if built is None:
del files["alternates"]
else:
maps.append(multiline_feature(built[1], {"role": "alternate"}))
if maps:
# The bbox covers the coordinates as published (rounded), not the source's.
box = geo.merge_bbox([geo.bbox(m["geometry"]["coordinates"]) for m in maps])
fc = {"type": "FeatureCollection", "bbox": box, "features": maps}
write_json(os.path.join(tdir, "map.json"), fc, stats)
sketches = termini_features(rec) if "line" not in files else []
if sketches:
box = hike.sketch_bbox(hike.sketch_points(rec), pad=True)
write_json(os.path.join(tdir, "sketch.json"),
{"type": "FeatureCollection", "bbox": box, "features": sketches}, stats)
return files, cache
def copy_sources(tid, files, tdir, stats):
"""Copy the trail's files that are published as they are (the full-resolution GeoJSON,
the extracts and the logo) from the repository."""
for key, stem in (("line", tid), ("alternates", f"{tid}-alternates")):
if key in files:
copy_file(os.path.join(ROOT, files[key]), os.path.join(tdir, f"{stem}.geojson"), stats)
for source, rel in files.get("extracts", {}).items():
copy_file(os.path.join(ROOT, rel), os.path.join(tdir, f"{tid}-{source}.geojson"), stats)
if "shield" in files:
name = os.path.basename(files["shield"])
copy_file(os.path.join(ROOT, files["shield"]), os.path.join(tdir, name), stats)
# What the trail's derived outputs are made from: these files' contents (and those of the trail's
# own directory) decide them, so a change to any of them makes a new key. Kept by content, not by
# modification time, so a store restored from a CI cache or made in another checkout is as good as one
# made here.
STORE_VERSION = "2" # 2: archives have fixed member times
_code_digest = None
def code_digest():
global _code_digest
if _code_digest is None:
h = hashlib.sha256(STORE_VERSION.encode())
for path in CODE_FILES:
with open(path, "rb") as f:
h.update(hashlib.sha256(f.read()).digest())
_code_digest = h.hexdigest()
return _code_digest
def trail_key(tid):
"""Hash of everything the trail's derived outputs depend on."""
h = hashlib.sha256(code_digest().encode())
h.update(gpx_creator().encode())
d = os.path.join(ROOT, tid)
for name in sorted(os.listdir(d)):
path = os.path.join(d, name)
if os.path.isfile(path):
h.update(name.encode() + b"\0")
with open(path, "rb") as f:
h.update(hashlib.sha256(f.read()).digest())
return h.hexdigest()
def store_dir():
return os.path.join(CACHE_DIR, "store")
def derived_names(names):
"""The outputs that are computed (the rest are copies of repository files)."""
return [n for n in names if n.endswith(".gpx") or n in ("map.json", "sketch.json")]
def restore_from_store(tid, key, tdir):
"""Copy the trail's stored derived outputs into tdir. Returns the stored meta
{"files", "cache", "warnings"}, or None when there is no entry for this key."""
entry = os.path.join(store_dir(), tid, key)
try:
with open(os.path.join(entry, "meta.json"), encoding="utf-8") as f:
meta = json.load(f)
for name in meta["derived"]:
shutil.copyfile(os.path.join(entry, name), os.path.join(tdir, name))
except (OSError, ValueError, KeyError):
return None
return meta
def save_to_store(tid, key, tdir, names, files, cache, warnings):
"""Keep the trail's derived outputs under their key; older keys of the trail are dropped.
Written beside and moved into place, so a half-written entry is never read."""
base = os.path.join(store_dir(), tid)
tmp = os.path.join(base, f".tmp-{os.getpid()}")
try:
shutil.rmtree(tmp, ignore_errors=True)
os.makedirs(tmp)
derived = derived_names(names)
for name in derived:
shutil.copyfile(os.path.join(tdir, name), os.path.join(tmp, name))
with open(os.path.join(tmp, "meta.json"), "w", encoding="utf-8") as f:
json.dump({"derived": derived, "files": files, "cache": cache, "warnings": warnings}, f)
final = os.path.join(base, key)
if not os.path.isdir(final):
os.rename(tmp, final)
for name in os.listdir(base):
if name != key and not name.startswith(".tmp-"):
shutil.rmtree(os.path.join(base, name), ignore_errors=True)
except OSError:
pass # the store is only a shortcut
finally:
shutil.rmtree(tmp, ignore_errors=True)
def build_trail(rec, out_dir, force, stats):
"""Write one trail's files. Returns (downloads, cache). The record's
derived.files is replaced by the files that actually produced output."""
derived.files is replaced by the files that actually produced output.
A trail whose outputs are already in out_dir and were made from its present content is left alone;
one whose sources and code are unchanged since the store (CACHE_DIR/store) last saw them
has its derived outputs copied from there; any other is computed."""
global _WARNINGS
tid = rec["id"]
files = dict(rec["derived"]["files"])
src = rec.get("source", {})
@@ -222,53 +376,35 @@ def build_trail(rec, out_dir, code_mtime, force, stats):
if not names:
pass # record only: nothing to write
elif not force and up_to_date(rec, files, tdir, cache_path, code_mtime):
elif not force and up_to_date(rec, files, tdir, cache_path, trail_key(tid)):
stats.skipped_trails += 1
stats.skipped += len(names)
cache = read_cache(cache_path)
else:
stats.processed += 1
gpx_args = dict(url=src.get("url", ""), attribution=src.get("attribution", ""),
licence=src.get("licence", ""), licence_text=src.get("licence_text", ""),
creator=gpx_creator(),
permission=({k: src[k] for k in ("permission_quote", "permission_by", "permission_date", "permission_url")
if k in src} if src.get("licence") == "stated-permission" else None))
maps = []
if "line" in files:
built = build_set(tid, "line", os.path.join(ROOT, files["line"]), tid,
rec["name"], tdir, gpx_args, stats)
if built is None:
del files["line"]
else:
parts, small = built
maps.append(multiline_feature(small, {"role": "main"}))
cache = {"bbox": geo.bbox(parts), "points": geo.point_count(parts),
"elevation": geo.has_elevation(parts)}
if "alternates" in files:
built = build_set(tid, "alternates", os.path.join(ROOT, files["alternates"]),
f"{tid}-alternates", rec["name"] + " (alternates)",
tdir, gpx_args, stats)
if built is None:
del files["alternates"]
else:
maps.append(multiline_feature(built[1], {"role": "alternate"}))
for source, rel in files.get("extracts", {}).items():
copy_file(os.path.join(ROOT, rel), os.path.join(tdir, f"{tid}-{source}.geojson"), stats)
if maps:
# The bbox covers the coordinates as published (rounded), not the source's.
box = geo.merge_bbox([geo.bbox(m["geometry"]["coordinates"]) for m in maps])
fc = {"type": "FeatureCollection", "bbox": box, "features": maps}
write_json(os.path.join(tdir, "map.json"), fc, stats)
sketches = termini_features(rec) if "line" not in files else []
if sketches:
box = hike.sketch_bbox(hike.sketch_points(rec), pad=True)
write_json(os.path.join(tdir, "sketch.json"),
{"type": "FeatureCollection", "bbox": box, "features": sketches}, stats)
if "shield" in files:
name = os.path.basename(files["shield"])
copy_file(os.path.join(ROOT, files["shield"]), os.path.join(tdir, name), stats)
key = trail_key(tid)
meta = None if force else restore_from_store(tid, key, tdir)
if meta is not None:
stats.skipped_trails += 1
files, cache = meta["files"], meta["cache"]
for message in meta["warnings"]:
warn(message)
copy_sources(tid, files, tdir, stats)
else:
stats.processed += 1
outer, _WARNINGS = _WARNINGS, []
try:
files, cache = compute_trail(rec, files, tdir, stats)
raised = _WARNINGS
finally:
_WARNINGS = outer
for message in raised:
warn(message)
copy_sources(tid, files, tdir, stats)
names = trail_outputs(tid, files, rec)
cache = dict(cache, outputs=sorted(names), creator=gpx_creator())
cache = dict(cache, outputs=sorted(names), creator=gpx_creator(), key=key)
if meta is None and names:
save_to_store(tid, key, tdir, names, files,
{k: v for k, v in cache.items() if k not in ("outputs", "creator", "key")}, raised)
if names:
with open(cache_path, "w", encoding="utf-8") as f:
json.dump(cache, f)
@@ -299,29 +435,55 @@ def build_trail(rec, out_dir, code_mtime, force, stats):
return downloads, cache or {}
def read_main_map_parts(tdir):
def overview_parts(tdir):
"""A trail's line for the overview map: its 30 m map line, joined, simplified to 750 m.
Kept in the store by the content of the map file, which is all it comes from."""
try:
with open(os.path.join(tdir, "map.json"), encoding="utf-8") as f:
fc = json.load(f)
with open(os.path.join(tdir, "map.json"), "rb") as f:
raw = f.read()
except OSError:
return []
for feat in fc["features"]:
tid = os.path.basename(tdir)
kept = os.path.join(store_dir(), "overview", f"{tid}.{hashlib.sha256(code_digest().encode() + raw).hexdigest()}.json")
try:
with open(kept, encoding="utf-8") as f:
return json.load(f)
except (OSError, ValueError):
pass
parts = []
for feat in json.loads(raw)["features"]:
if feat["properties"].get("role") == "main":
return feat["geometry"]["coordinates"]
return []
parts = feat["geometry"]["coordinates"]
break
parts = geo.join_parts(parts) # many trails are thousands of short parts
parts = geo.round_coords(geo.simplify(parts, OVERVIEW_TOL_M), 4)
try:
folder = os.path.dirname(kept)
os.makedirs(folder, exist_ok=True)
for old in os.listdir(folder):
if old.startswith(tid + ".") and old.count(".") == 2:
os.remove(os.path.join(folder, old))
with open(kept + f".{os.getpid()}", "w", encoding="utf-8") as f:
json.dump(parts, f)
os.replace(kept + f".{os.getpid()}", kept)
except OSError:
pass # the store is only a shortcut
return parts
def overview_geojson(recs, out_dir):
def overview_geojson(recs, out_dir, parts_of=None):
"""One MultiLineString per included trail, simplified from the 30 m map line.
A trail with no track but a known start or end appears as sketch features."""
A trail with no track but a known start or end appears as sketch features.
parts_of: {id: overview_parts(...)} already worked out (in a worker process)."""
features = []
for rec in recs:
if "line" not in rec["derived"]["files"]:
features.extend(sketch_features(rec))
continue
parts = read_main_map_parts(os.path.join(out_dir, "trails", rec["id"]))
parts = geo.join_parts(parts) # many trails are thousands of short parts
parts = geo.round_coords(geo.simplify(parts, OVERVIEW_TOL_M), 4)
if parts_of is not None and rec["id"] in parts_of:
parts = parts_of[rec["id"]]
else:
parts = overview_parts(os.path.join(out_dir, "trails", rec["id"]))
if not parts:
continue
props = {"id": rec["id"], "name": rec["name"], "kind": rec["derived"]["kind"],
@@ -406,6 +568,9 @@ def archive_readme(name):
f"{resolution}")
ARCHIVE_TIME = (1980, 1, 1, 0, 0, 0) # the earliest time a zip can hold
def build_archive(name, recs, out_dir, stats):
"""Write /data/<name> (zip, deflate) unless it already holds exactly these files
and is newer than every one of them and than this script."""
@@ -422,15 +587,49 @@ def build_archive(name, recs, out_dir, stats):
return
except (OSError, zipfile.BadZipFile):
pass
# The store keeps an archive by what goes into it, so one whose files have not changed (in
# content: it does not matter when they were written) is copied, not compressed again.
digest = hashlib.sha256(code_digest().encode() + archive_readme(name).encode())
for arc, src in members:
digest.update(arc.encode() + b"\0")
with open(src, "rb") as f:
digest.update(hashlib.sha256(f.read()).digest())
kept = os.path.join(store_dir(), "archives", f"{name}.{digest.hexdigest()}")
tmp = path + ".tmp" # written beside, then moved over: never a half-written archive
try:
try:
shutil.copyfile(kept, tmp)
with zipfile.ZipFile(tmp) as zf:
restored = zf.namelist() == expected and zf.testzip() is None # whole, not just named right
except (OSError, zipfile.BadZipFile, zlib.error, EOFError, NotImplementedError):
restored = False
if restored:
os.replace(tmp, path)
stats.skipped += 1
return
with zipfile.ZipFile(tmp, "w", compression=zipfile.ZIP_DEFLATED) as zf:
info = zipfile.ZipInfo("README.txt", date_time=time.localtime(mtime(__file__))[:6])
# Every member gets the same fixed time and mode, so the same files always make the
# same bytes, whenever and wherever the archive is made (and so the store can hand
# one made elsewhere to a build here).
info = zipfile.ZipInfo("README.txt", date_time=ARCHIVE_TIME)
info.compress_type = zipfile.ZIP_DEFLATED
info.external_attr = 0o644 << 16
info.external_attr = 0o100644 << 16
zf.writestr(info, archive_readme(name))
for arc, src in members:
zf.write(src, arc)
info = zipfile.ZipInfo(arc, date_time=ARCHIVE_TIME)
info.compress_type = zipfile.ZIP_DEFLATED
info.external_attr = 0o100644 << 16
with open(src, "rb") as source, zf.open(info, "w") as member:
shutil.copyfileobj(source, member, 1 << 20)
try:
os.makedirs(os.path.dirname(kept), exist_ok=True)
for old in os.listdir(os.path.dirname(kept)):
if old.startswith(name + "."):
os.remove(os.path.join(os.path.dirname(kept), old))
shutil.copyfile(tmp, kept + ".tmp")
os.replace(kept + ".tmp", kept)
except OSError:
pass # the store is only a shortcut
os.replace(tmp, path)
finally:
if os.path.exists(tmp):
@@ -466,6 +665,127 @@ def describe_site():
return f"the {name} site" if name else "the static site"
# Several trails at once ---------------------------------------------------------------------
# The work on a trail (reading its track, simplifying it twice, writing GPX) is the bulk of a
# cold build, and trails do not depend on one another, so they are spread over worker processes.
# The workers are forked, so they share the loaded records; a result is what the parent needs
# back, and the parent applies it in record order, so the output is the same as one process's.
PARALLEL_FROM = 16 # fewer trails than this: not worth the workers
_JOB = None
def usable_cores():
"""The cores this process may run on (os.process_cpu_count is new in Python 3.13)."""
try:
return len(os.sched_getaffinity(0)) or 1
except AttributeError:
return os.cpu_count() or 1
def job_count():
"""Worker processes: LONGHIKES_JOBS if set, else the cores this process may use (at most 8)."""
env = os.environ.get("LONGHIKES_JOBS", "")
if env.isdigit():
return max(1, int(env))
return min(usable_cores(), 8)
def fork_context():
if "fork" in multiprocessing.get_all_start_methods():
return multiprocessing.get_context("fork")
return None
def build_one(rec, out_dir, force, stats):
"""build_trail, and the trail's line for the overview map when it has one."""
downloads, cache = build_trail(rec, out_dir, force, stats)
parts = None
if "line" in rec["derived"]["files"]:
parts = overview_parts(os.path.join(out_dir, "trails", rec["id"]))
return downloads, cache, parts
def _trail_job(i):
global _WARNINGS
recs, out_dir, force_all, only = _JOB
rec = recs[i]
_WARNINGS = []
stats = Stats()
result = build_one(rec, out_dir, force_all or rec["id"] in only, stats)
return i, result, rec["derived"]["files"], vars(stats), _WARNINGS
def tree_size(tid):
return sum(e.stat().st_size for e in os.scandir(os.path.join(ROOT, tid)) if e.is_file())
def build_trails(recs, out_dir, args, only, stats):
"""[(downloads, cache, overview parts)] for every record, in record order."""
ctx = fork_context()
jobs = min(job_count(), len(recs))
if ctx is None or jobs < 2 or len(recs) < PARALLEL_FROM:
return [build_one(rec, out_dir, args.force or rec["id"] in only, stats)
for rec in recs]
global _JOB
_JOB = (recs, out_dir, args.force, only)
results = [None] * len(recs)
order = sorted(range(len(recs)), key=lambda i: -tree_size(recs[i]["id"])) # biggest first
# A process pool, not multiprocessing.Pool: a worker that raises, or is killed, makes the
# build fail (BrokenProcessPool) where Pool would wait for it for ever.
try:
with concurrent.futures.ProcessPoolExecutor(jobs, mp_context=ctx) as pool:
try:
futures = [pool.submit(_trail_job, i) for i in order]
for done in concurrent.futures.as_completed(futures):
i, result, files, counts, warnings = done.result()
recs[i]["derived"]["files"] = files
results[i] = result
for name, n in counts.items():
setattr(stats, name, getattr(stats, name) + n)
for message in warnings:
warn(message)
except BaseException:
pool.shutdown(wait=False, cancel_futures=True)
raise
finally:
_JOB = None
return results
def _archive_job(name):
stats = Stats()
build_archive(name, _JOB[0], _JOB[1], stats)
return vars(stats)
def start_archives(recs, out_dir, stats):
"""Build the bulk archives, in worker processes when they can be. Returns what finish_archives needs."""
global _JOB
ctx = fork_context()
if ctx is None or job_count() < 2:
for name in ARCHIVES:
build_archive(name, recs, out_dir, stats)
return None
_JOB = (recs, out_dir)
pool = concurrent.futures.ProcessPoolExecutor(min(len(ARCHIVES), job_count()), mp_context=ctx)
return pool, [pool.submit(_archive_job, name) for name in ARCHIVES]
def finish_archives(started, stats):
global _JOB
if started is None:
return
pool, pending = started
try:
for result in pending:
for name, n in result.result().items():
setattr(stats, name, getattr(stats, name) + n)
finally:
pool.shutdown(wait=True, cancel_futures=True)
_JOB = None
def main(argv=None):
ap = argparse.ArgumentParser(description=f"Build the data and pages for {describe_site()}.")
ap.add_argument("--out", default="_site", help="output directory (default _site)")
@@ -482,7 +802,6 @@ def main(argv=None):
if unknown:
raise SystemExit(f"unknown trail id(s): {', '.join(sorted(unknown))}")
code_mtime = max(mtime(p) for p in CODE_FILES)
stats = Stats()
os.makedirs(os.path.join(out_dir, "data"), exist_ok=True)
# Older builds kept the cache in the publish directory; it must never ship.
@@ -493,11 +812,12 @@ def main(argv=None):
# Every trail goes through build_trail so the site-wide files are complete.
# --only forces a rebuild of the chosen trails; the rest are rebuilt only
# when stale or missing from the cache.
for rec in recs:
force = args.force or rec["id"] in only
downloads, cache = build_trail(rec, out_dir, code_mtime, force, stats)
overview = {}
for rec, (downloads, cache, parts) in zip(recs, build_trails(recs, out_dir, args, only, stats)):
d = rec["derived"]
d["downloads"] = downloads
if parts is not None:
overview[rec["id"]] = parts
if cache.get("bbox"):
box = cache["bbox"]
d["bbox"] = box
@@ -508,12 +828,12 @@ def main(argv=None):
prune_removed_trails(out_dir, {r["id"] for r in recs})
write_json(os.path.join(out_dir, "data", "overview.geojson"),
overview_geojson(recs, out_dir), stats)
overview_geojson(recs, out_dir, overview), stats)
write_json(os.path.join(out_dir, "data", "trails.json"), recs, stats)
for name in ("trails.csv", "index.geojson"):
copy_file(os.path.join(ROOT, name), os.path.join(out_dir, "data", name), stats)
for name in ARCHIVES:
build_archive(name, recs, out_dir, stats)
# The archives need only the trails' files, which are all written: they are made alongside the pages.
archives = start_archives(recs, out_dir, stats)
copy_static(STATIC_DIR, out_dir, stats)
# The guessable trail addresses (/trails/pacific-crest-trail/) follow the fixed ones in _redirects.
@@ -528,6 +848,7 @@ def main(argv=None):
# (olt/fingerprint.py); this writes those files, under /immutable/.
fingerprint.publish(out_dir)
finish_archives(archives, stats)
total = 0
for base, _, names in os.walk(out_dir):
total += sum(os.path.getsize(os.path.join(base, n)) for n in names)
+23
View File
@@ -15,6 +15,7 @@ A list with a `noun` also has a page for each state or province where at least
MIN_SIZE of its trails are, and fewer than MAX_SHARE of that place's (olt/placefacets.py).
A list belongs to a `group` (GROUPS), the heading it sits under on /lists/.
"""
import contextlib
import re
from dataclasses import dataclass
from typing import Callable, Optional
@@ -287,13 +288,35 @@ def is_shown(n, total, least=0, capped=True):
return n >= max(MIN_SIZE, least) and (not capped or n <= MAX_SHARE * total)
_SHOWN_MEMO = None # while a site is being rendered: {id(records): (records, shown)}
@contextlib.contextmanager
def remembering_shown():
"""Within this block shown() works each list of records out once. A site render asks
for it from every state, place and list page; the records do not change meanwhile."""
global _SHOWN_MEMO
outer, _SHOWN_MEMO = _SHOWN_MEMO, {}
try:
yield
finally:
_SHOWN_MEMO = outer
def shown(records):
"""[(list, its trails)] for every list that passes is_shown, in LISTS order."""
if _SHOWN_MEMO is not None:
held = _SHOWN_MEMO.get(id(records))
if held is not None and held[0] is records:
return list(held[1])
out = []
for lst in LISTS:
recs = members(lst, records)
if is_shown(len(recs), len(records), lst.min_size, lst.capped):
out.append((lst, recs))
if _SHOWN_MEMO is not None:
_SHOWN_MEMO[id(records)] = (records, out)
return list(out)
return out
+38 -13
View File
@@ -150,8 +150,14 @@ def join_parts(parts, gap_m=100.0):
return out
def simplify_part(coords, tol_m):
"""Douglas-Peucker with an explicit stack; tol_m is in metres.
def simplify_part_multi(coords, tols_m):
"""Douglas-Peucker with an explicit stack, for several tolerances at once (metres).
Returns one simplified part per tolerance, in the order given, each exactly what a run with
that tolerance alone would give. The point a segment splits at does not depend on the
tolerance, only whether it splits does, and a larger tolerance splits a subset of what a
smaller one splits; so one walk of the smallest tolerance's tree, noting at each split which
of the tolerances it clears, serves them all.
Distances are measured on a local equirectangular plane for the segment
being tested, scaled by the mean cosine at its two ends. A single scale for
@@ -174,19 +180,21 @@ def simplify_part(coords, tol_m):
"""
n = len(coords)
if n < 3:
return list(coords)
return [list(coords) for _ in tols_m]
k = math.pi / 180.0 * EARTH_R
lons = [c[0] for c in coords]
lats = [c[1] for c in coords]
# Metres per degree of longitude (ck) and metres north (ys), per point.
ck = [math.cos(math.radians(lat)) * k for lat in lats]
ys = [lat * k for lat in lats]
tol2 = tol_m * tol_m
keep = bytearray(n)
keep[0] = keep[n - 1] = 1
stack = [(0, n - 1)]
order = sorted(range(len(tols_m)), key=lambda j: tols_m[j]) # ascending tolerance
tol2 = [tols_m[j] * tols_m[j] for j in order]
keeps = [bytearray(n) for _ in tol2]
for keep in keeps:
keep[0] = keep[n - 1] = 1
stack = [(0, n - 1, len(tol2))] # (first, last, how many tolerances still reach this segment)
while stack:
a, b = stack.pop()
a, b, live = stack.pop()
if b - a < 2:
continue
la, lb = lons[a], lons[b]
@@ -221,11 +229,28 @@ def simplify_part(coords, tol_m):
d2 = cross * cross / len2
if d2 > best:
best, idx = d2, i
if best > tol2:
keep[idx] = 1
stack.append((a, idx))
stack.append((idx, b))
return [c for c, k_ in zip(coords, keep) if k_]
reach = 0
while reach < live and best > tol2[reach]:
keeps[reach][idx] = 1
reach += 1
if reach:
stack.append((a, idx, reach))
stack.append((idx, b, reach))
out = [None] * len(tols_m)
for pos, j in enumerate(order):
out[j] = [c for c, k_ in zip(coords, keeps[pos]) if k_]
return out
def simplify_part(coords, tol_m):
"""Douglas-Peucker for one tolerance; see simplify_part_multi."""
return simplify_part_multi(coords, [tol_m])[0]
def simplify_multi(parts, tols_m):
"""One simplified line per tolerance (a list of lists of parts), for a line's parts."""
per_part = [simplify_part_multi(p, tols_m) for p in parts]
return [[pp[j] for pp in per_part] for j in range(len(tols_m))]
def simplify(parts, tol_m):
+5
View File
@@ -90,6 +90,11 @@ def not_found_page(site):
def render_site(records, out_dir, repo_root, site=None):
"""Write every HTML page for the given records. Returns the number of pages written."""
with browse.remembering_shown():
return _render_site(records, out_dir, repo_root, site)
def _render_site(records, out_dir, repo_root, site=None):
site = site or site_settings.load()
copy_assets(out_dir)
sketch.use(out_dir) # the maps' static drawings are read from the track files written here
+7 -1
View File
@@ -186,7 +186,13 @@ class _Crumbs(HTMLParser):
def visible_breadcrumbs(body):
"""[(text, href)] of the breadcrumb a page body shows; the last item has no href."""
parser = _Crumbs()
parser.feed(str(body))
text = str(body)
# The breadcrumb is near the top of a body: feed it in pieces and stop once its nav has
# closed, rather than parsing a whole page of rows.
for i in range(0, len(text), 8192):
parser.feed(text[i:i + 8192])
if parser._done:
break
return parser.items
+14 -1
View File
@@ -43,6 +43,7 @@ def use(out_dir):
global DATA_DIR
DATA_DIR = out_dir or ""
_cache.clear()
_JOINED.clear()
def _read(*parts):
@@ -121,10 +122,22 @@ class Plane:
return ((point[0] * RAD - self.x0) * self.k, (self.y1 - _merc(point[1])) * self.k)
_JOINED = {} # {ids of the parts: (the parts, them joined)}: the same track is drawn on many pages
def _joined(parts):
"""geo.join_parts(parts), kept for the same parts (by identity); many trails are thousands of short parts."""
key = tuple(id(p) for p in parts)
held = _JOINED.get(key)
if held is None or len(held[0]) != len(parts) or any(a is not b for a, b in zip(held[0], parts)):
held = _JOINED[key] = (list(parts), geo.join_parts(parts))
return held[1]
def _path(plane, parts, tol=TOL):
"""One relative SVG path for the parts: whole-number steps, simplified to tol units."""
out = []
for part in geo.simplify(geo.join_parts(parts), tol * plane.m_per_unit):
for part in geo.simplify(_joined(parts), tol * plane.m_per_unit):
pts = []
for p in part:
x, y = plane.xy(p)
+167
View File
@@ -0,0 +1,167 @@
"""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 is made new: whatever was there is removed first,
so nothing in it can be a page an earlier build (of another branch, say) wrote and this one
does not. Raises when the build fails."""
shutil.rmtree(out, ignore_errors=True)
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(len(os.sched_getaffinity(0)) if hasattr(os, "sched_getaffinity") else (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
+117
View File
@@ -0,0 +1,117 @@
#!/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
need no build 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():
try:
return len(os.sched_getaffinity(0)) or 1 # the cores this process may use
except AttributeError:
return 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):
"""True for a module that reads the shared site or builds the site itself (test_google_tag):
it starts when the shared build has finished, so its own builds find the store full."""
with open(os.path.join(HERE, module + ".py"), encoding="utf-8") as f:
text = f.read()
return "builtsite" in text or "start_build" in text
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())
+27
View File
@@ -260,6 +260,33 @@ class BuildTreeTest(unittest.TestCase):
self.assertNotEqual(os.path.getmtime(gpx), stamps[0])
self.assertNotEqual(os.path.getmtime(geojson), stamps[1])
def test_archive_members_are_regular_files_with_the_usual_mode(self):
self.build()
for name in ("all-gpx.zip", "all-geojson.zip"):
with zipfile.ZipFile(self.path("data", name)) as zf:
for info in zf.infolist():
self.assertEqual(info.external_attr >> 16, 0o100644, f"{name}: {info.filename}")
def test_a_damaged_stored_archive_is_not_restored(self):
self.build()
gpx = self.path("data", "all-gpx.zip")
with open(gpx, "rb") as f:
good = f.read()
kept = os.path.join(build.CACHE_DIR, "store", "archives")
stored = [os.path.join(kept, n) for n in os.listdir(kept) if n.startswith("all-gpx.zip.")]
self.assertEqual(len(stored), 1)
with open(stored[0], "rb") as f:
damaged = bytearray(f.read())
damaged[len("README.txt") + 30 + 4] ^= 0xFF # inside the first member's data; the names stay
with open(stored[0], "wb") as f:
f.write(damaged)
os.remove(gpx) # so the store is where the archive comes from
self.build()
with zipfile.ZipFile(gpx) as zf:
self.assertIsNone(zf.testzip())
with open(gpx, "rb") as f:
self.assertEqual(f.read(), good)
def test_missing_declared_line_warns(self):
os.remove(os.path.join(self.root, "avon", "line.geojson"))
warnings = self.build()
+284
View File
@@ -0,0 +1,284 @@
"""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 time
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))
def olt_imports(path):
"""The olt modules a file imports, by any statement anywhere in it (inside a function too):
`from . import x`, `from .x import y`, `from olt import x`, `from olt.x import y`, `import olt.x`."""
with open(path, encoding="utf-8") as f:
tree = ast.parse(f.read())
found = set()
for node in ast.walk(tree):
if isinstance(node, ast.ImportFrom):
if node.level == 1:
found.update([node.module] if node.module else [a.name for a in node.names])
elif node.level == 0 and node.module == "olt":
found.update(a.name for a in node.names)
elif node.level == 0 and (node.module or "").startswith("olt."):
found.add(node.module.split(".")[1])
elif isinstance(node, ast.Import):
found.update(a.name.split(".")[1] for a in node.names if a.name.startswith("olt."))
return found
class CodeFilesTest(unittest.TestCase):
# Not part of a trail's derived files: pages renders the site's pages from the finished records.
NOT_TRAIL_CODE = {"pages"}
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}
self.assertIn(os.path.abspath(build.__file__), listed)
for path in sorted(listed):
if os.path.dirname(path) != olt and os.path.basename(path) != "build.py":
continue
for name in sorted(olt_imports(path) - self.NOT_TRAIL_CODE):
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 test_the_scan_sees_every_kind_of_import(self):
with tempfile.TemporaryDirectory() as tmp:
path = os.path.join(tmp, "m.py")
with open(path, "w", encoding="utf-8") as f:
f.write("from . import a\nfrom .b import x\nfrom olt import c, d\nfrom olt.e import y\n"
"import olt.f\nimport os\n\ndef g():\n from olt import h\n")
self.assertEqual(olt_imports(path), set("abcdefh"))
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_the_worker_count_follows_the_cores_this_process_may_use_and_the_setting(self):
with mock.patch.dict(os.environ, {"LONGHIKES_JOBS": ""}):
with mock.patch.object(os, "sched_getaffinity", lambda pid: {0}):
self.assertEqual(build.job_count(), 1)
with mock.patch.object(os, "sched_getaffinity", lambda pid: set(range(32))):
self.assertEqual(build.job_count(), 8)
with mock.patch.dict(os.environ, {"LONGHIKES_JOBS": "1"}):
self.assertEqual(build.job_count(), 1)
def test_a_worker_that_raises_fails_the_build_and_leaves_no_site(self):
out, cache = self.dirs("raises")
real = build.compute_trail
def broken(rec, files, tdir, stats):
if rec["id"] == self.ids[3]:
raise RuntimeError("worker trouble")
return real(rec, files, tdir, stats)
for jobs in (1, 4):
with self.subTest(jobs=jobs), mock.patch.object(build, "compute_trail", broken):
with self.assertRaisesRegex(RuntimeError, "worker trouble"):
self.build(out, cache + str(jobs), jobs)
self.assertFalse(os.path.exists(os.path.join(out, "index.html")))
self.assertFalse(os.path.exists(os.path.join(out, "data", "trails.json")))
def test_a_worker_that_dies_fails_the_build_instead_of_hanging(self):
out, cache = self.dirs("dies")
def dying(rec, files, tdir, stats):
os._exit(3)
with mock.patch.object(build, "compute_trail", dying):
started = time.time()
with self.assertRaises(Exception):
self.build(out, cache, 4)
self.assertLess(time.time() - started, 120)
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)
def test_a_rebuild_into_the_same_directory_follows_content_not_modification_times(self):
out, cache = self.dirs("same")
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()
stat = os.stat(line)
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)
long_ago = time.mktime((2020, 1, 1, 0, 0, 0, 0, 0, -1))
os.utime(line, (long_ago, long_ago))
os.utime(os.path.join(self.root, tid), (long_ago, long_ago))
self.build(out, cache, 1) # the same directory, the same cache
fresh, empty = self.dirs("same-fresh")
self.build(fresh, empty, 1)
same_tree(self, out, fresh)
finally:
with open(line, "w", encoding="utf-8") as f:
f.write(original)
os.utime(line, ns=(stat.st_atime_ns, stat.st_mtime_ns))
if __name__ == "__main__":
unittest.main()
+41
View File
@@ -0,0 +1,41 @@
"""The shared test build is always a fresh one: nothing in the directory tests read can be left over
from an earlier build, such as a page that another branch wrote and this one does not."""
import os
import subprocess
import sys
import tempfile
import unittest
from unittest import mock
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import builtsite # noqa: E402
class FreshBuildTest(unittest.TestCase):
def test_a_page_left_by_an_earlier_build_is_not_there_when_the_next_build_starts(self):
with tempfile.TemporaryDirectory() as tmp:
out = os.path.join(tmp, "site")
os.makedirs(os.path.join(out, "regions", "gone"))
for rel in (os.path.join("regions", "gone", "index.html"), "old.json"):
with open(os.path.join(out, rel), "w") as f:
f.write("left over")
seen = []
def fake_build(cmd, **kwargs):
seen.append(sorted(os.listdir(out)) if os.path.isdir(out) else None)
os.makedirs(out, exist_ok=True)
return subprocess.CompletedProcess(cmd, 0, "", "")
with mock.patch.object(builtsite.subprocess, "run", fake_build):
builtsite.build(out)
self.assertIn(seen[0], (None, []))
self.assertEqual(os.listdir(out), [])
def test_the_shared_site_is_in_a_directory_named_for_this_process(self):
if not builtsite.PREBUILT:
self.assertTrue(builtsite.OUT.endswith(f"test-site-{os.getpid()}"))
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)
+4 -5
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):
+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):
@@ -333,9 +334,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:
+8 -2
View File
@@ -22,6 +22,7 @@ ROOT = os.path.dirname(WEB)
sys.path.insert(0, WEB)
sys.path.insert(0, os.path.join(ROOT, "tools"))
import builtsite # noqa: E402
from olt import browse, facets, home, layout, leftout, regions, site, standing, views, words # noqa: E402
from olt import records as recordsmod # noqa: E402
@@ -33,6 +34,11 @@ def read(*parts):
return f.read()
def built_page(*parts):
"""A page of the shared site build (builtsite.py), as text."""
return read(builtsite.ensure(), *parts, "index.html")
def form_of(body):
body = str(body)
if 'id="finder-form"' not in body:
@@ -80,7 +86,7 @@ class WhichPagesHaveTheBarTest(unittest.TestCase):
small = [k for k, v in by_slug.items() if len(v["records"]) < 10]
self.assertGreater(len(small), 40)
for key in small:
body = regions.region_page(key, self.records, SITE)[2]
body = built_page("regions", key)
self.assertIn('id="finder-form"', str(body), key)
self.assertIn("data-finder", str(body), key)
small_lists = [k for k, recs in self.shown.items() if len(recs) < 10 and k != "routes"]
@@ -93,7 +99,7 @@ class WhichPagesHaveTheBarTest(unittest.TestCase):
two = [k for k, v in by_slug.items() if len(v["records"]) == 2]
self.assertTrue(two)
for key in two:
form = form_of(regions.region_page(key, self.records, SITE)[2])
form = form_of(built_page("regions", key))
self.assertIn('name="q"', form, key)
for sel in re.findall(r"<select[^>]*>(.*?)</select>", form, re.S):
self.assertNotIn("<select></select>", sel)
+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):
+26 -15
View File
@@ -15,7 +15,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 +31,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 +69,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 +148,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 +195,20 @@ 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)
gone = os.path.join(again, "trails", self.png[0], thumbs.THUMB_NAME)
os.remove(gone) # one the second build must put back
# build.py itself, on the copy as it stands: builtsite.build removes its target first
done = subprocess.run([sys.executable, os.path.join(builtsite.WEB, "build.py"), "--out", again],
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
self.assertEqual(done.returncode, 0, done.stderr[-2000:])
self.assertIn("trails processed 0,", done.stdout) # it was a second build, not a first
self.assertTrue(os.path.isfile(gone))
for tid in self.png:
self.assertTrue(os.path.isfile(os.path.join(again, "trails", tid, thumbs.THUMB_NAME)), tid)
if __name__ == "__main__":
+4 -2
View File
@@ -21,6 +21,7 @@ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from olt import (authors, browse, common, datafiles, facets, placefacets, records, reference, regions, site, standing, # noqa: E402
summary, views, words)
import builtsite # noqa: E402
from test_hike import fake # noqa: E402
SITE = site.Site("Long Hikes", "T", repo_url="https://github.com/o/r")
@@ -718,8 +719,9 @@ class RealDataTest(unittest.TestCase):
def test_every_place_page_has_a_summary_paragraph(self):
by_slug, _ = regions.collect_regions(self.records)
for slug in by_slug:
_, _, body, _ = regions.region_page(slug, self.records, SITE)
self.assertIn('class="browse-about"', str(body))
with open(os.path.join(builtsite.ensure(), "regions", slug, "index.html"), encoding="utf-8") as f:
body = f.read()
self.assertIn('class="browse-about"', body)
if len(by_slug[slug]["records"]) > 1:
# "The longest is" where every trail is wholly in the place, else "passes through" (olt/summary.py)
self.assertTrue("The longest is" in str(body) or "The longest trail that passes through" in str(body))