Add the Long Hikes static site (longhikes.org)
Validate / validate (push) Canceled after 0s

web/ is a static site generator for the dataset, in Python's standard
library only. `python3 web/build.py --out _site` writes a page for each
of the 138 records, a finder on the home page with a map of the 85
lines, region and route indexes, and the repository's documents as
pages. Each line is offered as the record's GeoJSON and as a GPX
simplified to 5 m, with two archives of everything.

The site's name and address are set in web/site.toml: Long Hikes, at
https://longhikes.org. The dataset keeps its own name.

netlify.toml and web/static/_headers configure the Netlify site
(content types, download dispositions, caching, a content security
policy with no inline script). It is deployed with the Netlify CLI
from a local build, because Netlify cannot build from this forge.

MapLibre GL JS and the two typefaces are vendored under web/assets/;
map tiles come from OpenFreeMap. Tests: python3 -m unittest discover
-s web/tests (164).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-13 12:20:32 -07:00
1 parent c42cfbbe73
commit abfbeb00bd
77 files changed
+9287

No files matched your search

+265
View File
@@ -0,0 +1,265 @@
import contextlib
import io
import json
import os
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
class CopyStaticTest(unittest.TestCase):
def test_copies_tree_verbatim(self):
with tempfile.TemporaryDirectory() as tmp:
static = os.path.join(tmp, "static")
out = os.path.join(tmp, "out")
contents = {
"_headers": "/*\n X-Content-Type-Options: nosniff\n",
os.path.join("assets", "site.css"): "body { margin: 0 }\n",
os.path.join("assets", "sub", "app.js"): "0;\n",
}
for rel, text in contents.items():
path = os.path.join(static, rel)
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "w", encoding="utf-8") as f:
f.write(text)
os.makedirs(out)
stats = build.Stats()
build.copy_static(static, out, stats)
self.assertEqual(stats.written, len(contents))
for rel, text in contents.items():
with open(os.path.join(out, rel), encoding="utf-8") as f:
self.assertEqual(f.read(), text)
def test_missing_static_dir_is_skipped(self):
with tempfile.TemporaryDirectory() as tmp:
out = os.path.join(tmp, "out")
os.makedirs(out)
stats = build.Stats()
build.copy_static(os.path.join(tmp, "nonexistent"), out, stats)
self.assertEqual(stats.written, 0)
self.assertEqual(os.listdir(out), [])
def test_cache_is_outside_the_publish_directory(self):
# The cache lives beside build.py, under web/, not under _site.
self.assertEqual(build.CACHE_DIR, os.path.join(build.HERE, ".cache"))
REAL_ROOT = build.ROOT
SMALL = ("batona", "avon", "canol")
class FakePages:
"""Stands in for olt.pages: records what render_site was given."""
calls = []
@classmethod
def render_site(cls, recs, out_dir, root):
cls.calls.append([r["id"] for r in recs])
class BuildTreeTest(unittest.TestCase):
"""Builds a few real trail directories into a throwaway tree."""
def setUp(self):
tmp = tempfile.TemporaryDirectory()
self.addCleanup(tmp.cleanup)
self.root = os.path.join(tmp.name, "repo")
self.out = os.path.join(tmp.name, "site")
os.makedirs(self.root)
for tid in SMALL:
shutil.copytree(os.path.join(REAL_ROOT, tid), os.path.join(self.root, tid))
for name in ("trails.csv", "index.geojson"):
shutil.copyfile(os.path.join(REAL_ROOT, name), os.path.join(self.root, name))
FakePages.calls = []
for p in (mock.patch.object(build, "ROOT", self.root),
mock.patch.object(build, "CACHE_DIR", os.path.join(tmp.name, "cache")),
mock.patch.object(build, "import_pages", lambda: FakePages)):
p.start()
self.addCleanup(p.stop)
def build(self, *extra):
err = io.StringIO()
with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(err):
build.main(["--out", self.out, *extra])
return err.getvalue()
def path(self, *parts):
return os.path.join(self.out, *parts)
def trails_json(self):
with open(self.path("data", "trails.json"), encoding="utf-8") as f:
return {r["id"]: r for r in json.load(f)}
def overview_ids(self):
with open(self.path("data", "overview.geojson"), encoding="utf-8") as f:
return sorted(ft["properties"]["id"] for ft in json.load(f)["features"])
def add_alternates(self, tid):
with open(os.path.join(self.root, tid, "line.geojson"), encoding="utf-8") as f:
parts = build.geo.parts_from_geojson(json.load(f))
alt = {"type": "Feature", "properties": {},
"geometry": {"type": "MultiLineString", "coordinates": parts[:1]}}
with open(os.path.join(self.root, tid, "alternates.geojson"), "w", encoding="utf-8") as f:
json.dump(alt, f)
def map_roles(self, tid):
with open(self.path("trails", tid, "map.json"), encoding="utf-8") as f:
return [ft["properties"]["role"] for ft in json.load(f)["features"]]
def test_deleted_line_file_removes_outputs_and_cache(self):
self.add_alternates("batona")
self.build()
self.assertEqual(self.map_roles("batona"), ["main", "alternate"])
self.assertIn("bbox", self.trails_json()["batona"]["derived"])
os.remove(os.path.join(self.root, "batona", "line.geojson"))
warnings = self.build()
self.assertIn("batona", warnings)
tdir = self.path("trails", "batona")
self.assertFalse(os.path.exists(os.path.join(tdir, "batona.geojson")))
self.assertFalse(os.path.exists(os.path.join(tdir, "batona.gpx")))
self.assertEqual(self.map_roles("batona"), ["alternate"])
derived = self.trails_json()["batona"]["derived"]
self.assertNotIn("bbox", derived)
self.assertEqual([d["role"] for d in derived["downloads"]], ["alternates"] * 2)
self.assertNotIn("batona", self.overview_ids())
os.remove(os.path.join(self.root, "batona", "alternates.geojson"))
self.build()
self.assertEqual(sorted(os.listdir(tdir)), [])
self.assertEqual(self.trails_json()["batona"]["derived"]["downloads"], [])
def test_pages_files_survive_cleanup(self):
self.build()
tdir = self.path("trails", "avon")
for name in ("index.html", "trail.toml", "release.txt"):
with open(os.path.join(tdir, name), "w") as f:
f.write("x")
os.remove(os.path.join(self.root, "avon", "line.geojson"))
self.build()
self.assertEqual(sorted(os.listdir(tdir)), ["index.html", "release.txt", "trail.toml"])
def test_removed_trail_directory_is_pruned(self):
self.build()
shutil.rmtree(os.path.join(self.root, "canol"))
self.build("--only", "avon")
self.assertTrue(os.path.isdir(self.path("trails", "canol"))) # --only never prunes
self.build()
self.assertFalse(os.path.exists(self.path("trails", "canol")))
self.assertTrue(os.path.isdir(self.path("trails", "avon")))
self.assertNotIn("canol", self.trails_json())
def test_only_keeps_site_wide_data_complete(self):
self.build()
full_ids = sorted(self.trails_json())
overview = self.overview_ids()
self.assertEqual(full_ids, sorted(SMALL))
self.build("--only", "avon")
self.assertEqual(sorted(self.trails_json()), full_ids)
self.assertEqual(self.overview_ids(), overview)
self.assertEqual(FakePages.calls[-1], sorted(SMALL))
# a non-selected trail with no cache entry is built, not dropped
shutil.rmtree(build.CACHE_DIR)
self.build("--only", "avon")
self.assertEqual(self.overview_ids(), overview)
self.assertIn("bbox", self.trails_json()["batona"]["derived"])
def test_empty_feature_collection_is_no_line(self):
self.build()
with open(os.path.join(self.root, "batona", "line.geojson"), "w") as f:
json.dump({"type": "FeatureCollection", "features": []}, f)
warnings = self.build()
self.assertEqual(len(warnings.splitlines()), 1)
self.assertIn("batona", warnings)
tdir = self.path("trails", "batona")
self.assertEqual([n for n in os.listdir(tdir) if n.endswith((".json", ".gpx", ".geojson"))], [])
derived = self.trails_json()["batona"]["derived"]
self.assertEqual(derived["downloads"], [])
self.assertNotIn("batona", self.overview_ids())
self.assertIn("avon", self.overview_ids())
def test_collapsed_line_after_rounding_is_no_line(self):
self.build()
with mock.patch.object(build.geo, "round_coords", lambda parts, decimals: []):
warnings = self.build("--force")
self.assertIn("batona", warnings)
self.assertFalse(os.path.exists(self.path("trails", "batona", "map.json")))
def test_map_bbox_contains_every_written_coordinate(self):
self.build()
for tid in SMALL:
with open(self.path("trails", tid, "map.json"), encoding="utf-8") as f:
fc = json.load(f)
w, s, e, n = fc["bbox"]
for ft in fc["features"]:
for part in ft["geometry"]["coordinates"]:
for c in part:
self.assertTrue(w <= c[0] <= e and s <= c[1] <= n, (tid, c, fc["bbox"]))
def test_bbox_is_computed_from_rounded_coordinates(self):
# 0.0000004 rounds to 0: the source box would poke past the published line.
line = {"type": "Feature", "properties": {}, "geometry": {
"type": "LineString", "coordinates": [[0.0000004, 0.0000004], [1.0000004, 1.0000004]]}}
with open(os.path.join(self.root, "avon", "line.geojson"), "w") as f:
json.dump(line, f)
self.build()
with open(self.path("trails", "avon", "map.json"), encoding="utf-8") as f:
self.assertEqual(json.load(f)["bbox"], [0.0, 0.0, 1.0, 1.0])
def test_unchanged_tree_is_up_to_date(self):
self.build()
out = io.StringIO()
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(io.StringIO()):
build.main(["--out", self.out])
self.assertIn("trails processed 0", out.getvalue())
def test_archives_rebuilt_only_when_an_input_is_newer(self):
self.build()
gpx, geojson = self.path("data", "all-gpx.zip"), self.path("data", "all-geojson.zip")
with zipfile.ZipFile(gpx) as zf:
names = zf.namelist()
readme = zf.read("README.txt").decode("utf-8")
self.assertEqual(names[0], "README.txt")
for tid in SMALL:
self.assertIn(f"{tid}/{tid}.gpx", names)
self.assertIn(f"{tid}/release.txt", names)
self.assertIn("trails.csv", names)
self.assertIn("5 m", readme)
with zipfile.ZipFile(geojson) as zf:
self.assertIn("avon/avon.geojson", zf.namelist())
self.assertIsNone(zf.testzip())
stamps = (os.path.getmtime(gpx), os.path.getmtime(geojson))
self.build()
self.assertEqual((os.path.getmtime(gpx), os.path.getmtime(geojson)), stamps)
# a trail gone from the dataset is gone from the archives, though no input is newer
shutil.rmtree(os.path.join(self.root, "canol"))
self.build()
with zipfile.ZipFile(gpx) as zf:
self.assertFalse(any(n.startswith("canol/") for n in zf.namelist()))
stamps = (os.path.getmtime(gpx), os.path.getmtime(geojson))
self.build()
self.assertEqual((os.path.getmtime(gpx), os.path.getmtime(geojson)), stamps)
# a newer input (here a release.txt) rebuilds both archives
later = max(stamps) + 10
os.utime(os.path.join(self.root, "avon", "release.txt"), (later, later))
self.build()
self.assertNotEqual(os.path.getmtime(gpx), stamps[0])
self.assertNotEqual(os.path.getmtime(geojson), stamps[1])
def test_missing_declared_line_warns(self):
os.remove(os.path.join(self.root, "avon", "line.geojson"))
warnings = self.build()
self.assertIn("avon", warnings)
self.assertEqual(self.trails_json()["avon"]["derived"]["downloads"], [])
if __name__ == "__main__":
unittest.main()
+334
View File
@@ -0,0 +1,334 @@
"""Tests for the added pages: regions, routes, sources, logos, about, data, SEO files,
the bulk archives and the response headers."""
import html
import os
import re
import subprocess
import sys
import unittest
import zipfile
WEB = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
ROOT = os.path.dirname(WEB)
sys.path.insert(0, WEB)
import serve # noqa: E402
from olt import docs, home, records, regions as regions_mod, seo, site, words # noqa: E402
OUT = os.path.join(WEB, ".cache", "test-site")
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)
def read_out(relpath):
with open(os.path.join(OUT, *relpath.split("/")), encoding="utf-8") as f:
return f.read()
def entry_ids(doc):
return re.findall(r'<li class="entry" data-id="([^"]+)"', doc)
class ExtraPagesTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.records = records.load_records(ROOT)
def test_every_region_code_has_a_page(self):
codes = {c for r in self.records for c in r.get("regions", [])
if c != words.ALL_CANADA}
for code in codes:
slug = words.region_key(code, "US").lower()
path = os.path.join(OUT, "regions", slug, "index.html")
self.assertTrue(os.path.isfile(path), f"{code} -> {slug}")
self.assertTrue(os.path.isfile(os.path.join(OUT, "regions", "index.html")))
def test_each_record_on_each_region_page(self):
for rec in self.records:
for code in rec.get("regions", []):
if code == words.ALL_CANADA:
page = read_out("regions/index.html")
else:
slug = words.region_key(code, rec["country"]).lower()
page = read_out(f"regions/{slug}/index.html")
self.assertIn(f'href="/trails/{rec["id"]}/"', page, f'{rec["id"]} in {code}')
def test_all_routes_on_routes_page(self):
routes = [r for r in self.records if r["derived"]["kind"] == "route"]
self.assertEqual(len(routes), 34)
page = read_out("routes/index.html")
import html as _html
text = _html.unescape(page)
for r in routes:
self.assertIn(f'href="/trails/{r["id"]}/"', page, r["id"])
self.assertIn(r["route"]["creator"], text, r["id"])
def test_every_logo_on_logos_page(self):
page = read_out("logos/index.html")
for r in self.records:
if "shield" in r["derived"]["files"]:
self.assertIn(f'href="/trails/{r["id"]}/"', page, r["id"])
self.assertIn("no-logo-exists", page)
self.assertIn("logo-not-found", page)
def test_added_pages_exist(self):
for rel in ("sources/index.html", "about/index.html", "data/index.html",
"data/schema/index.html", "data/changelog/index.html",
"licences/LICENSE", "licences/MIT.txt", "robots.txt"):
self.assertTrue(os.path.isfile(os.path.join(OUT, *rel.split("/"))), rel)
def test_no_dead_internal_links_in_added_pages(self):
import re
for rel in ("regions/index.html", "routes/index.html", "sources/index.html",
"logos/index.html", "about/index.html", "data/index.html",
"data/schema/index.html", "data/changelog/index.html"):
html = read_out(rel)
for url in re.findall(r'(?:href|src)="(/[^"]*)"', html):
path = url.split("#", 1)[0].split("?", 1)[0]
if not path:
continue
if path.endswith("/"):
path += "index.html"
target = os.path.join(OUT, *path.lstrip("/").split("/"))
self.assertTrue(os.path.isfile(target), f"{rel} -> {url}")
def test_region_map_limited_to_region_ids(self):
page = read_out("regions/us-vt/index.html")
self.assertIn('data-map="overview"', page)
self.assertIn("data-ids=", page)
self.assertIn("long-trail", page)
def test_home_region_links_point_to_region_pages(self):
page = read_out("index.html")
self.assertIn('href="/regions/us-vt/"', page)
def test_country_and_region_counts_match_the_regions_pages(self):
home_doc = read_out("index.html")
index = read_out("regions/index.html")
by_slug, canada_wide = regions_mod.collect_regions(self.records)
for country, label in (("US", "United States"), ("CA", "Canada")):
shown = int(re.search(rf'value="{country}"><span>{label} \((\d+)\)</span>', home_doc).group(1))
on_index = int(re.search(rf'data-country-count="{country}">(\d+)<', index).group(1))
listed = set()
for slug, info in by_slug.items():
if info["country"] == country:
listed |= set(entry_ids(read_out(f"regions/{slug}/index.html")))
if country == "CA":
listed |= {r["id"] for r in canada_wide}
self.assertEqual(shown, on_index, country)
self.assertEqual(shown, len(listed), country)
# every row of those records says it touches the country
for tid in listed:
attrs = re.search(rf'<li class="entry" data-id="{tid}"([^>]*)>', home_doc).group(1)
self.assertIn(country, re.search(r'data-countries="([^"]*)"', attrs).group(1).split(), tid)
self.assertIn('data-countries="US CA"', re.search(
r'<li class="entry" data-id="eastern-continental-trail"[^>]*>', home_doc).group(0))
self.assertIn('data-countries="US CA"', re.search(
r'<li class="entry" data-id="great-plains-trail"[^>]*>', home_doc).group(0))
# each region option's count is the number of records on that region's page
for value, n in re.findall(r'<option value="((?:US|CA)-[A-Z]{2})">[^<(]+\((\d+)\)</option>', home_doc):
page = read_out(f"regions/{value.lower()}/index.html")
self.assertEqual(int(n), len(entry_ids(page)), value)
canada = re.search(r'<option value="CA-\*">All provinces and territories \((\d+)\)</option>', home_doc)
self.assertEqual(int(canada.group(1)), len(canada_wide))
self.assertIn('href="/?region=CA-*"', index)
def test_list_pages_share_the_home_list(self):
for rel in ("index.html", "regions/us-co/index.html", "routes/index.html"):
doc = read_out(rel)
results = doc[doc.index('<div class="results">'):]
for part in ('<div class="list-head" aria-hidden="true">', '<ol class="entries"',
'name="units-list"', '<ul class="key"'):
self.assertIn(part, results, f"{rel}: {part}")
scale = re.search(r'<div class="list-head".*?</div>', results, re.S).group(0)
self.assertEqual(scale.count('class="len__km"'), 3, rel)
self.assertEqual(scale.count('class="len__mi"'), 3, rel)
self.assertNotIn('class="route-item"', read_out("routes/index.html"))
co = read_out("regions/us-co/index.html")
self.assertIn('<a href="/?region=US-CO&amp;line=1">With a line</a>', co)
def test_routes_page_rows_carry_their_guides(self):
doc = read_out("routes/index.html")
routes = [r for r in self.records if r["derived"]["kind"] == "route"]
self.assertEqual(sorted(entry_ids(doc)), sorted(r["id"] for r in routes))
for r in routes:
row = re.search(rf'<li class="entry" data-id="{r["id"]}".*?\n</li>', doc, re.S).group(0)
for g in r["guide"]:
self.assertIn(f'href="{html.escape(g["url"], quote=True)}"', row, r["id"])
def test_home_finder_layout(self):
doc = read_out("index.html")
form = doc[doc.index('<form class="filters"'):doc.index("</form>")]
self.assertIn('<details class="filters__more">', form)
self.assertNotIn("filters__more\" open", form)
# the line checkbox comes straight after the search field, outside the details
self.assertLess(form.index('name="line"'), form.index("<details"))
self.assertLess(form.index('id="q"'), form.index('name="line"'))
self.assertIn('<a class="button button--primary hero__cta" href="#q">Find a trail</a>', doc)
self.assertIn("No records match these filters.", doc)
steps = [int(v) for v in re.findall(r'<option value="(\d+)">', form[form.index('id="max"'):])]
self.assertGreaterEqual(steps[-1], max(r["length_km"] for r in self.records))
self.assertEqual(home.length_steps(self.records)[:11], list(home.LENGTH_STEPS))
def test_logos_page_shows_exactly_the_logo_files(self):
page = read_out("logos/index.html")
files = sorted(d for d in os.listdir(ROOT)
if any(os.path.isfile(os.path.join(ROOT, d, n)) for n in records.SHIELD_NAMES))
cards = re.findall(r'<li class="logo-card">.*?<h3><a href="/trails/([^/]+)/">', page, re.S)
self.assertEqual(sorted(cards), files)
for img in re.findall(r'<li class="logo-card">\s*<div class="plate[^"]*">(.*?)</div>', page, re.S):
self.assertIn('alt=""', img)
self.assertIn('class="vh"', img) # the link around the image still has a name
def test_sources_page_counts_measured_lines(self):
page = read_out("sources/index.html")
measured = sum(1 for r in self.records if r.get("verification", {}).get("verified"))
self.assertIn(f"<dt>Line measured</dt><dd>{measured}<", page)
self.assertIn("<dt>Source status: OpenStreetMap only</dt>", page)
self.assertEqual(page.count('<th scope="col">Trails and routes</th>'), 2)
self.assertNotRegex(page, r'<td><a href="/trails/[^"]+/">[^<]*</a>, <a')
def test_data_page_licences_from_the_records(self):
page = read_out("data/index.html")
self.assertNotIn("Pacific Crest line (PCTA)", page)
lines = [r for r in self.records if r["derived"]["has_line"]]
for lic in {r["source"]["licence"] for r in lines}:
n = sum(1 for r in lines if r["source"]["licence"] == lic)
label = html.escape(words.label(words.LICENCES, lic), quote=True)
self.assertIn(f"Lines licensed {label}: {n} record", page, lic)
for name in ("trails.json", "overview.geojson"):
self.assertRegex(page, rf'<a href="/data/{re.escape(name)}">')
for name in ("all-gpx.zip", "all-geojson.zip"):
size = words.fmt_bytes(os.path.getsize(os.path.join(OUT, "data", name)))
self.assertRegex(page, rf'/data/{re.escape(name)}</a></td><td>[^<]*</td><td class="num">{re.escape(size)}<')
self.assertIn(f'"contentUrl":"{site.load().base_url}/data/{name}"', page)
def test_archives_hold_every_line(self):
lines = [r for r in self.records if r["derived"]["has_line"]]
for name, ext in (("all-gpx.zip", ".gpx"), ("all-geojson.zip", ".geojson")):
with zipfile.ZipFile(os.path.join(OUT, "data", name)) as zf:
names = set(zf.namelist())
for doc in ("README.txt", "trails.csv", "SOURCES.md"):
self.assertIn(doc, names, name)
for r in lines:
self.assertIn(f'{r["id"]}/{r["id"]}{ext}', names, name)
self.assertIn(f'{r["id"]}/release.txt', names, name)
if "alternates" in r["derived"]["files"]:
self.assertIn(f'{r["id"]}/{r["id"]}-alternates{ext}', names, name)
self.assertTrue(all(n.endswith((ext, "release.txt")) or "/" not in n for n in names), name)
readme = zf.read("README.txt").decode("utf-8")
self.assertIn("release.txt", readme)
self.assertIn("trails.csv", readme)
self.assertIn("5 m", readme)
if ext == ".gpx":
self.assertIsNone(zf.testzip())
info = zf.getinfo(f"{lines[0]['id']}/{lines[0]['id']}.gpx")
self.assertEqual(info.compress_type, zipfile.ZIP_DEFLATED)
def test_document_requests_link_only_when_configured(self):
text = ("<p>Open an issue, or send a patch.</p><p>Ask by opening an issue in this repository, "
"or by writing to the repository maintainers through the contact.</p>")
self.assertEqual(docs.link_requests(text, site.Site("N", "T")), text)
out = docs.link_requests(text, site.Site("N", "T", repo_url="https://example.org/r"))
self.assertIn('<a href="https://example.org/r/issues">Open an issue</a>', out)
self.assertIn('<a href="https://example.org/r/issues">opening an issue</a>', out)
self.assertIn('<a href="https://example.org/r">writing to the repository maintainers</a>', out)
out = docs.link_requests(text, site.Site("N", "T", contact_url="mailto:a@example.org"))
self.assertIn('<a href="mailto:a@example.org">writing to the repository maintainers</a>', out)
self.assertIn('<a href="mailto:a@example.org">Open an issue</a>', out)
configured = site.load()
if not (configured.repo_url or configured.contact_url): # left as the documents have it
self.assertIn("<p>Open an issue, or send a patch", read_out("about/index.html"))
self.assertIn(" by opening an issue in this repository, or by writing to the repository maintainers ",
read_out("logos/index.html"))
class HeadersTest(unittest.TestCase):
"""The built _headers, read the way serve.py applies it, over every file in the built site."""
NETLIFY_DEFAULT_CACHE = "public, max-age=0, must-revalidate" # when no rule sets Cache-Control
@classmethod
def setUpClass(cls):
cls.rules = serve.parse_headers(os.path.join(OUT, "_headers"))
cls.paths = []
for base, _, names in os.walk(OUT):
for n in names:
cls.paths.append("/" + os.path.relpath(os.path.join(base, n), OUT).replace(os.sep, "/"))
def headers(self, path):
"""{lower name: value}, failing when two matching rules set the same header."""
out = {}
for pattern, headers in self.rules:
if pattern.match(path):
for name, value in headers:
self.assertNotIn(name.lower(), out, f"{path}: {name} set by two rules")
out[name.lower()] = value
return out
def test_pages_revalidate(self):
pages = [p for p in self.paths if p.endswith(".html")]
self.assertGreater(len(pages), 200)
clean = [p[:-len("index.html")] for p in pages if p.endswith("/index.html")]
for path in pages + clean:
cache = self.headers(path).get("cache-control", self.NETLIFY_DEFAULT_CACHE)
self.assertIn("max-age=0", cache, path)
for path in ("/data/", "/data/index.html", "/data/schema/", "/data/changelog/"):
self.assertIn("max-age=0", self.headers(path).get("cache-control", self.NETLIFY_DEFAULT_CACHE), path)
def test_line_files_and_licences_get_their_types(self):
seen = {".gpx": 0, ".geojson": 0}
for path in self.paths:
h = self.headers(path)
if path.startswith("/trails/") and path.endswith(".gpx"):
seen[".gpx"] += 1
self.assertEqual(h.get("content-type"), "application/gpx+xml", path)
elif path.startswith("/trails/") and path.endswith(".geojson"):
seen[".geojson"] += 1
self.assertEqual(h.get("content-type"), "application/geo+json", path)
elif path.startswith("/data/") and path.endswith(".zip"):
self.assertEqual(h.get("content-type"), "application/zip", path)
self.assertGreater(seen[".gpx"], 85)
self.assertGreater(seen[".geojson"], 85)
self.assertEqual(self.headers("/licences/LICENSE").get("content-type"), "text/plain; charset=utf-8")
self.assertIn("/licences/LICENSE", self.paths)
def test_fonts_are_same_origin(self):
csp = self.headers("/").get("content-security-policy", "")
font_src = re.search(r"font-src ([^;]*)", csp).group(1)
self.assertEqual(font_src.strip(), "'self'")
self.assertIn("https://tiles.openfreemap.org", re.search(r"connect-src ([^;]*)", csp).group(1))
class SeoTest(unittest.TestCase):
def test_sitemap_absent_without_base_url(self):
import tempfile
with tempfile.TemporaryDirectory() as tmp:
seo.write_seo_files(tmp, ["/"], site.Site("N", "T"))
self.assertFalse(os.path.exists(os.path.join(tmp, "sitemap.xml")))
with open(os.path.join(tmp, "robots.txt"), encoding="utf-8") as f:
self.assertNotIn("Sitemap:", f.read())
def test_sitemap_complete_with_base_url(self):
import tempfile
recs = records.load_records(ROOT)
by_slug, _ = regions_mod.collect_regions(recs)
region_paths = [f"/regions/{s}/" for s in sorted(by_slug)]
paths = seo.all_paths(recs, region_paths)
s = site.Site("N", "T", base_url="https://example.org")
with tempfile.TemporaryDirectory() as tmp:
seo.write_seo_files(tmp, paths, s)
with open(os.path.join(tmp, "sitemap.xml"), encoding="utf-8") as f:
xml = f.read()
for p in paths:
self.assertIn(f"<loc>https://example.org{p}</loc>", xml, p)
with open(os.path.join(tmp, "robots.txt"), encoding="utf-8") as f:
self.assertIn("Sitemap: https://example.org/sitemap.xml", f.read())
if __name__ == "__main__":
unittest.main()
+291
View File
@@ -0,0 +1,291 @@
import math
import os
import random
import sys
import unittest
import xml.etree.ElementTree as ET
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from olt import geo # noqa: E402
NS = "{http://www.topografix.com/GPX/1/1}"
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
M_PER_DEG = math.pi / 180.0 * geo.EARTH_R
def wiggly(n=2000):
"""A noisy west-east line near 45N, about 0.0001 degrees per step."""
return [[-110.0 + i * 0.0001, 45.0 + 0.00008 * math.sin(i / 7.0)
+ 0.00002 * ((i * 7919) % 13 - 6) / 6.0] for i in range(n)]
def offset(lon, lat, east_m, north_m):
"""Point east_m/north_m metres from (lon, lat), in degrees."""
return [lon + east_m / (M_PER_DEG * math.cos(math.radians(lat))),
lat + north_m / M_PER_DEG]
def synthetic_line(lon0, lat0, n=1200, step_m=4.0):
"""A straight-ish line east from (lon0, lat0), wiggling by up to ~15 m."""
out = []
for i in range(n):
north = (9.0 * math.sin(i / 13.0) + 4.0 * math.sin(i / 3.1)
+ 2.0 * math.sin(i / 0.7))
out.append(offset(lon0, lat0, i * step_m, north))
return out
def unit(lon, lat):
lo, la = math.radians(lon), math.radians(lat)
return (math.cos(la) * math.cos(lo), math.cos(la) * math.sin(lo), math.sin(la))
def cross(a, b):
return (a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2],
a[0] * b[1] - a[1] * b[0])
def dot(a, b):
return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
def angle(a, b):
return math.atan2(math.sqrt(dot(cross(a, b), cross(a, b))), dot(a, b))
def true_dist_to_segment_m(p, a, b):
"""Distance from p to the great-circle arc a-b, independent of any projection.
Uses 3D unit vectors on the sphere: the perpendicular distance is
asin(|p . n|) when the foot lies between a and b, otherwise the nearer end.
"""
P, A, B = unit(p[0], p[1]), unit(a[0], a[1]), unit(b[0], b[1])
n = cross(A, B)
nn = math.sqrt(dot(n, n))
if nn < 1e-15: # coincident ends: a zero-length segment
return min(angle(P, A), angle(P, B)) * geo.EARTH_R
n = (n[0] / nn, n[1] / nn, n[2] / nn)
s = dot(P, n)
q = (P[0] - s * n[0], P[1] - s * n[1], P[2] - s * n[2])
qn = math.sqrt(dot(q, q))
if qn < 1e-15:
return 90.0 * M_PER_DEG
q = (q[0] / qn, q[1] / qn, q[2] / qn)
if dot(cross(A, q), n) >= -1e-12 and dot(cross(q, B), n) >= -1e-12:
return abs(math.asin(max(-1.0, min(1.0, s)))) * geo.EARTH_R
return min(angle(P, A), angle(P, B)) * geo.EARTH_R
class SimplifyTest(unittest.TestCase):
def assert_dropped_within(self, line, out, limit_m):
"""Every dropped point must lie within limit_m of the kept polyline."""
positions = []
j = 0
for i, c in enumerate(line):
if j < len(out) and c == out[j]:
positions.append(i)
j += 1
self.assertEqual(j, len(out), "kept points must be a subsequence of the line")
self.assertEqual(positions[0], 0)
self.assertEqual(positions[-1], len(line) - 1)
for k in range(len(positions) - 1):
a, b = out[k], out[k + 1]
for i in range(positions[k] + 1, positions[k + 1]):
d = true_dist_to_segment_m(line[i], a, b)
self.assertLessEqual(
d, limit_m,
f"point {i} is {d:.2f} m from the kept segment "
f"({out[k]} -> {out[k + 1]}), limit {limit_m} m")
def test_keeps_end_points_and_only_drops_interior(self):
line = wiggly()
out = geo.simplify_part(line, 5.0)
self.assertEqual(out[0], line[0])
self.assertEqual(out[-1], line[-1])
self.assertLess(len(out), len(line))
it = iter(line)
self.assertTrue(all(any(c == o for c in it) for o in out)) # subsequence
def test_dropped_points_within_true_tolerance(self):
# Checked against spherical ground truth, not the simplification metric.
# At these longitudes the old Greenwich-centred projection sheared badly.
tol = 5.0
for lon0, lat0 in ((-130.0, 63.0), (-70.0, 45.0), (-81.0, 26.0)):
with self.subTest(lon=lon0, lat=lat0):
line = synthetic_line(lon0, lat0)
out = geo.simplify_part(line, tol)
self.assertLess(len(out), len(line))
self.assert_dropped_within(line, out, tol * 1.05)
def test_dropped_points_within_true_tolerance_on_real_line(self):
parts = geo.read_parts(os.path.join(ROOT, "canol", "line.geojson"))
line = max(parts, key=len)
out = geo.simplify_part(line, 5.0)
self.assertLess(len(out), len(line))
self.assert_dropped_within(line, out, 5.0 * 1.05)
def test_short_and_closed_parts(self):
self.assertEqual(geo.simplify_part([[0, 0], [1, 1]], 100), [[0, 0], [1, 1]])
loop = [[0, 0], [0, 0.01], [0.01, 0.01], [0.01, 0], [0, 0]]
out = geo.simplify_part(loop, 5.0)
self.assertEqual(out[0], out[-1])
self.assertGreaterEqual(len(out), 4)
def test_closed_loop_keeps_both_ends(self):
# First point equals last: the initial segment is degenerate, so the
# algorithm must split on the farthest point and keep both ends.
lon0, lat0 = -81.0, 26.0
loop = [offset(lon0, lat0, 400.0 * math.cos(2 * math.pi * i / 720),
400.0 * math.sin(2 * math.pi * i / 720))
for i in range(721)]
out = geo.simplify_part(loop, 5.0)
self.assertEqual(out[0], loop[0])
self.assertEqual(out[-1], loop[-1])
self.assertEqual(out[0], out[-1])
self.assertLess(len(out), len(loop))
self.assert_dropped_within(loop, out, 5.0 * 1.05)
def test_huge_part_does_not_recurse(self):
line = [[-100 + i * 1e-5, 40 + (i % 2) * 1e-6] for i in range(300000)]
out = geo.simplify_part(line, 5.0)
self.assertEqual((out[0], out[-1]), (line[0], line[-1]))
def test_long_north_south_part_keeps_true_tolerance(self):
# A part spanning ~3 degrees of latitude: a single cosine for the
# whole part would be wrong at one end.
line = [offset(-130.0, 61.0, 4.0 * math.sin(i / 5.0), i * 400.0)
for i in range(900)]
out = geo.simplify_part(line, 5.0)
self.assertLess(len(out), len(line))
self.assert_dropped_within(line, out, 5.0 * 1.05)
def test_long_north_south_segment_does_not_understate_distance(self):
# A 780 km segment with the only deviation near its southern end: the
# cosine at the segment's mean latitude would compute 5.5 m as < 5 m
# and drop a point that is really too far from the kept line.
line = [offset(-130.0, 61.0, 0.0, 0.0),
offset(-130.0, 61.001, 5.5, 0.0),
offset(-130.0, 68.0, 0.0, 0.0)]
out = geo.simplify_part(line, 5.0)
self.assertEqual(len(out), 3, "a point 5.5 m off must not be dropped")
self.assert_dropped_within(line, out, 5.0 * 1.05)
def test_elevation_kept(self):
out = geo.simplify_part([[0, 0, 5], [0.0005, 0.0005, 6], [0.001, 0.001, 7]], 1.0)
self.assertEqual(out, [[0, 0, 5], [0.001, 0.001, 7]])
class MeasureTest(unittest.TestCase):
def test_length_one_degree_of_latitude(self):
self.assertAlmostEqual(geo.length_km([[[0, 0], [0, 1]]]), 111.195, delta=0.01)
def test_length_known_pair(self):
# one degree of longitude at 60N is half of one at the equator
km = geo.length_km([[[10, 60], [11, 60]]])
self.assertAlmostEqual(km, 55.6, delta=0.1)
def test_bbox(self):
self.assertEqual(geo.bbox([[[1, 2], [3, 4]], [[-1, 9], [0, 0]]]), [-1, 0, 3, 9])
def test_round_coords_drops_repeats_keeps_ele(self):
out = geo.round_coords([[[1.000001, 2.0, 7], [1.000002, 2.0, 8], [2.0, 3.0, 9]]], 4)
self.assertEqual(out, [[[1.0, 2.0, 7], [2.0, 3.0, 9]]])
def test_round_coords_drops_a_part_that_collapses(self):
collapsing = [[-81.503841, 36.648341], [-81.503849, 36.648349]]
self.assertEqual(geo.round_coords([collapsing], 4), [])
def test_round_coords_surviving_part_keeps_its_ends(self):
collapsing = [[-81.503841, 36.648341], [-81.503849, 36.648349]]
line = [[1.234561, 2.345678], [1.234562, 2.345679], [3.5, 4.5]]
out = geo.round_coords([collapsing, line], 4)
self.assertEqual(len(out), 1)
self.assertEqual(out[0][0], [1.2346, 2.3457])
self.assertEqual(out[0][-1], [3.5, 4.5])
def test_round_coords_all_parts_collapse(self):
collapsing = [[-81.503841, 36.648341], [-81.503849, 36.648349]]
out = geo.round_coords([collapsing, collapsing], 4)
self.assertEqual(out, [])
# Callers in geo.py must cope with no parts left.
self.assertIsNone(geo.bbox(out))
self.assertEqual(geo.join_parts(out), [])
root = ET.fromstring(geo.gpx_text(out, "x"))
self.assertEqual(root.findall(f".//{NS}trkseg"), [])
def test_join_parts(self):
a = [[0, 0], [0, 0.01]]
b = [[0, 0.02], [0, 0.0100005]] # reversed, starts far, ends near a's end
out = geo.join_parts([a, b], 100.0)
self.assertEqual(len(out), 1)
self.assertEqual(len(out[0]), 4)
class JoinPartsTest(unittest.TestCase):
@staticmethod
def aligned_pair(lat, gap_m, bearing, far_m=300.0):
"""Two parts whose near ends are gap_m apart, their far ends harmless.
The whole assembly is laid out along one bearing, which exercises the
bucket grid in every direction (including mostly north-south, where a
longitude bucket shrunk by cos(lat) is easy to get wrong).
"""
east, north = math.sin(bearing), math.cos(bearing)
base = [-110.0, lat]
near = offset(base[0], base[1], gap_m * east, gap_m * north)
a = [offset(base[0], base[1], -far_m * east, -far_m * north), base]
b = [near, offset(base[0], base[1], (gap_m + far_m) * east,
(gap_m + far_m) * north)]
return a, b
def test_joins_95m_gap_at_all_latitudes(self):
rnd = random.Random(20261110)
for lat in (30.0, 49.0, 62.0, 65.25, 68.0):
for _ in range(200):
a, b = self.aligned_pair(lat, 95.0, rnd.uniform(0.0, 2.0 * math.pi))
out = geo.join_parts([a, b], 100.0)
self.assertEqual(len(out), 1, f"95 m gap not joined at lat {lat}")
self.assertEqual(len(out[0]), 4)
def test_does_not_join_150m_gap(self):
rnd = random.Random(7)
for lat in (30.0, 49.0, 62.0, 65.25, 68.0):
for _ in range(50):
a, b = self.aligned_pair(lat, 150.0, rnd.uniform(0.0, 2.0 * math.pi))
out = geo.join_parts([a, b], 100.0)
self.assertEqual(len(out), 2, f"150 m gap joined at lat {lat}")
class GpxTest(unittest.TestCase):
def test_gpx_segments_and_metadata(self):
parts = [[[-105.1, 40.1], [-105.2, 40.2]], [[-106.0, 41.0], [-106.1, 41.1], [-106.2, 41.2]]]
text = geo.gpx_text(parts, "A & B <Trail>", url="https://example.org/?a=1&b=2",
attribution='Me "and" you', licence="ODbL-1.0",
licence_text="ODbL 1.0 text")
root = ET.fromstring(text)
self.assertEqual(root.get("version"), "1.1")
trks = root.findall(NS + "trk")
self.assertEqual(len(trks), 1)
segs = trks[0].findall(NS + "trkseg")
self.assertEqual([len(s.findall(NS + "trkpt")) for s in segs], [2, 3])
meta = root.find(NS + "metadata")
self.assertEqual(meta.find(NS + "name").text, "A & B <Trail>")
self.assertEqual(meta.find(NS + "link").get("href"), "https://example.org/?a=1&b=2")
self.assertEqual(meta.find(NS + "copyright").get("author"), 'Me "and" you')
self.assertIn("ODbL 1.0 text", meta.find(NS + "desc").text)
self.assertIsNone(root.find(f".//{NS}ele"))
def test_gpx_elevation_only_when_present(self):
root = ET.fromstring(geo.gpx_text([[[1, 2, 300.5], [1.000001, 2.000001, 301]]], "x"))
eles = [e.text for e in root.iter(NS + "ele")]
self.assertEqual(eles, ["300.5", "301"])
def test_no_exponent_in_numbers(self):
root = ET.fromstring(geo.gpx_text([[[0.000001, 0.0], [0.5, 0.5]]], "x"))
pt = root.find(f".//{NS}trkpt")
self.assertEqual(pt.get("lon"), "0.000001")
if __name__ == "__main__":
unittest.main()
+431
View File
@@ -0,0 +1,431 @@
import html.parser
import os
import sys
import unittest
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from olt import md # noqa: E402
ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
DOCS = ["README.md", "SOURCES.md", "NOTICE.md",
"CONTRIBUTING.md", "CHANGELOG.md", "docs/schema.md"]
def read_doc(name):
with open(os.path.join(ROOT, name), encoding="utf-8") as f:
return f.read()
class TagBalance(html.parser.HTMLParser):
VOID = {"hr", "br", "img", "meta", "link", "input", "col"}
def __init__(self):
super().__init__(convert_charrefs=True)
self.stack = []
self.errors = []
self.hrefs = []
def handle_starttag(self, tag, attrs):
if tag in self.VOID:
return
self.stack.append(tag)
if tag == "a":
self.hrefs.append(dict(attrs).get("href", ""))
def handle_startendtag(self, tag, attrs):
pass
def handle_endtag(self, tag):
if tag in self.VOID:
return
if self.stack and self.stack[-1] == tag:
self.stack.pop()
else:
self.errors.append("unmatched </%s>, open=%r" % (tag, self.stack))
def check_well_formed(html):
checker = TagBalance()
checker.feed(html)
checker.close()
return checker
class TableCounter(html.parser.HTMLParser):
def __init__(self):
super().__init__(convert_charrefs=True)
self.counts = []
self.in_tbody = False
def handle_starttag(self, tag, attrs):
if tag == "tbody":
self.in_tbody = True
self.counts.append(0)
elif tag == "tr" and self.in_tbody:
self.counts[-1] += 1
def handle_endtag(self, tag):
if tag == "tbody":
self.in_tbody = False
class HeadingsTest(unittest.TestCase):
def test_levels(self):
self.assertEqual(md.render("# One"), '<h1 id="one">One</h1>')
self.assertEqual(md.render("### Three"), '<h3 id="three">Three</h3>')
self.assertEqual(md.render("###### Six"), '<h6 id="six">Six</h6>')
def test_offset(self):
self.assertEqual(md.render("# One", heading_offset=1),
'<h2 id="one">One</h2>')
self.assertEqual(md.render("### Three", heading_offset=2),
'<h5 id="three">Three</h5>')
def test_offset_capped_at_h6(self):
self.assertTrue(md.render("### Three", heading_offset=9)
.startswith("<h6 "))
self.assertTrue(md.render("# One", heading_offset=5)
.startswith("<h6 "))
def test_heading_without_space_is_paragraph(self):
self.assertEqual(md.render("#nospace"), "<p>#nospace</p>")
def test_headings_values(self):
self.assertEqual(md.headings("# Hello, World!\n\n## B *c*"),
[(1, "Hello, World!", "hello-world"),
(2, "B c", "b-c")])
def test_duplicate_slugs_numbered(self):
self.assertEqual(
[slug for _, _, slug in md.headings("# A\n# A\n# A")],
["a", "a-2", "a-3"])
def test_render_uses_same_slugs_as_headings(self):
text = "# Repeat\n\n# Repeat\n"
html = md.render(text)
for _, _, slug in md.headings(text):
self.assertIn('id="%s"' % slug, html)
def test_heading_inline_markup_excluded_from_slug(self):
self.assertEqual(md.headings("## Use `code` here"),
[(2, "Use code here", "use-code-here")])
class SectionsTest(unittest.TestCase):
def test_basic_split(self):
self.assertEqual(
md.split_sections("# Title\n\nintro\n\n## One\nbody one\n## Two\nbody two"),
[("One", "body one"), ("Two", "body two")])
def test_preamble_excluded(self):
sections = md.split_sections("# Title\n\nintro\n\n## One\nbody\n")
self.assertEqual(sections, [("One", "body")])
def test_subheadings_stay_in_body(self):
sections = md.split_sections("## One\ntext\n### Sub\nmore\n## Two\nend\n")
self.assertEqual(sections, [("One", "text\n### Sub\nmore"),
("Two", "end")])
def test_default_level_is_two(self):
self.assertEqual(len(md.split_sections("# T\n\n# U")), 0)
self.assertEqual(len(md.split_sections("# T\n\n## U")), 1)
def test_bad_level_rejected(self):
with self.assertRaises(ValueError):
md.split_sections("text", level=0)
with self.assertRaises(ValueError):
md.split_sections("text", level=7)
def test_readme_inclusion_rule(self):
sections = dict(md.split_sections(read_doc("README.md")))
self.assertIn("Inclusion rule", sections)
self.assertIn("A long trail here is a named, continuous walking route",
sections["Inclusion rule"])
self.assertEqual(len(sections), 10)
class ParagraphsTest(unittest.TestCase):
def test_simple_paragraph(self):
self.assertEqual(md.render("Hello world."), "<p>Hello world.</p>")
def test_blocks_separated(self):
self.assertEqual(md.render("One.\n\nTwo."),
"<p>One.</p>\n<p>Two.</p>")
def test_raw_html_is_escaped(self):
html = md.render("Use <id>/trail.toml and <n> trails.")
self.assertIn("&lt;id&gt;/trail.toml", html)
self.assertIn("&lt;n&gt;", html)
self.assertNotIn("<id>", html)
def test_ampersand_escaped(self):
self.assertIn("a &amp; b", md.render("a & b"))
class ListsTest(unittest.TestCase):
def test_unordered(self):
self.assertEqual(md.render("- a\n- b"),
"<ul>\n<li>a</li>\n<li>b</li>\n</ul>")
def test_ordered(self):
self.assertEqual(md.render("1. one\n2. two"),
"<ol>\n<li>one</li>\n<li>two</li>\n</ol>")
def test_ordered_paren_marker(self):
self.assertIn("<ol>", md.render("1) one\n2) two"))
def test_nested(self):
html = md.render("- a\n - b\n- c")
self.assertIn("<li>a\n<ul>\n<li>b</li>\n</ul></li>", html)
def test_multiline_item_joined(self):
html = md.render("1. first line\n second line\n2. next")
self.assertIn("<li>first line\nsecond line</li>", html)
def test_loose_list_keeps_paragraphs(self):
html = md.render("- a\n\n- b")
self.assertIn("<li><p>a</p></li>", html)
self.assertIn("<li><p>b</p></li>", html)
def test_markup_inside_items(self):
html = md.render("- `code` and **bold**")
self.assertIn("<li><code>code</code> and <strong>bold</strong></li>",
html)
class TablesTest(unittest.TestCase):
def test_header_and_body(self):
html = md.render("| a | b |\n| --- | --- |\n| 1 | 2 |")
self.assertIn("<thead>", html)
self.assertIn("<tbody>", html)
self.assertIn('<th scope="col">a</th>', html)
self.assertIn("<td>1</td>", html)
def test_right_align_gets_num_class(self):
html = md.render("| a | b |\n| --- | ---: |\n| 1 | 2 |")
self.assertIn('<th scope="col" class="num">b</th>', html)
self.assertIn('<td class="num">2</td>', html)
self.assertIn('<th scope="col">a</th>', html)
def test_no_inline_styles(self):
html = md.render("| a |\n| ---: |\n| 1 |")
self.assertNotIn("style=", html)
def test_needs_alignment_row(self):
self.assertNotIn("<table>", md.render("| a | b |\n| 1 | 2 |"))
def test_links_and_parens_urls_in_cells(self):
html = md.render(
"| T |\n| --- |\n"
"| [source page](https://e.com/POHE_Trail_(Public_NPMap)/0) |")
self.assertIn('<a href="https://e.com/POHE_Trail_(Public_NPMap)/0">'
"source page</a>", html)
def test_pipe_in_code_does_not_split(self):
html = md.render("| a | b |\n| --- | --- |\n| `x|y` | 2 |")
self.assertEqual(html.count("<td>"), 2)
self.assertIn("<code>x|y</code>", html)
def test_escaped_pipe_does_not_split(self):
html = md.render("| a |\n| --- |\n| x\\|y |")
self.assertEqual(html.count("<td>"), 1)
self.assertIn("x|y", html)
def test_underscores_in_cell_urls_untouched(self):
html = md.render("| a |\n| --- |\n"
"| [p](https://e.com/a_b_c/0) |")
self.assertIn('href="https://e.com/a_b_c/0"', html)
class CodeTest(unittest.TestCase):
def test_fenced_with_language(self):
html = md.render("```toml\nid = \"x\"\n```")
self.assertEqual(html, '<pre><code class="language-toml">'
'id = &quot;x&quot;</code></pre>')
def test_fenced_without_language(self):
html = md.render("```\nplain\n```")
self.assertEqual(html, "<pre><code>plain</code></pre>")
def test_fence_content_not_parsed(self):
html = md.render("```text\n**no** [link](https://e.com) `x`\n```")
self.assertNotIn("<strong>", html)
self.assertNotIn("<a ", html)
self.assertIn("**no** [link](https://e.com) `x`", html)
def test_fence_content_escaped(self):
self.assertIn("&lt;id&gt;", md.render("```\n<id>\n```"))
def test_inline_code(self):
self.assertEqual(md.render("Use `trail.toml` here."),
"<p>Use <code>trail.toml</code> here.</p>")
def test_code_not_parsed(self):
html = md.render("`*not* [em](https://e.com/x_(y))`")
self.assertNotIn("<em>", html)
self.assertNotIn("<a ", html)
class InlineTest(unittest.TestCase):
def test_bold(self):
self.assertEqual(md.render("a **bold** b"),
"<p>a <strong>bold</strong> b</p>")
def test_italic(self):
self.assertEqual(md.render("a *italic* b"),
"<p>a <em>italic</em> b</p>")
def test_italic_in_bold(self):
self.assertEqual(md.render("**a *b* c**"),
"<p><strong>a <em>b</em> c</strong></p>")
def test_unmatched_markers_literal(self):
self.assertEqual(md.render("a ** b"), "<p>a ** b</p>")
self.assertEqual(md.render("a * b"), "<p>a * b</p>")
def test_intraword_underscore_literal(self):
self.assertIn("agol_flt", md.render("hosts its line as 'agol_flt'"))
def test_link(self):
self.assertEqual(md.render("[text](https://e.com/x)"),
'<p><a href="https://e.com/x">text</a></p>')
def test_link_rewrite(self):
html = md.render("[schema](docs/schema.md)",
link_rewrite=lambda h: "/data/schema/")
self.assertIn('<a href="/data/schema/">schema</a>', html)
def test_link_rewrite_none_keeps_the_text_only(self):
drop = lambda h: None if h.startswith("tools/") else h # noqa: E731
html = md.render("See [the tools](tools/build_index.py) and "
"[schema](/data/schema/), <https://e.com/a>.",
link_rewrite=lambda h: None if h != "/data/schema/" else h)
self.assertEqual(html, '<p>See the tools and <a href="/data/schema/">schema</a>, '
'https://e.com/a.</p>')
html = md.render("| a |\n| --- |\n| [*x* y](tools/x.py) https://e.com/b |",
link_rewrite=drop)
self.assertIn("<td><em>x</em> y ", html)
self.assertIn('<a href="https://e.com/b">https://e.com/b</a>', html)
self.assertNotIn("tools/", html)
def test_link_url_with_parens(self):
html = md.render("[p](https://e.com/a_(b)_/c)")
self.assertIn('href="https://e.com/a_(b)_/c"', html)
def test_bare_url(self):
html = md.render("see https://www.example.com/x for more")
self.assertIn('<a href="https://www.example.com/x">'
"https://www.example.com/x</a>", html)
def test_angle_autolink(self):
self.assertIn('<a href="https://e.com/x">https://e.com/x</a>',
md.render("<https://e.com/x>"))
def test_non_link_angle_escaped(self):
html = md.render("a <n> b")
self.assertIn("&lt;n&gt;", html)
self.assertNotIn("<a ", html)
def test_escape(self):
html = md.render("a \\* b \\` c")
self.assertIn("a * b ` c", html)
self.assertNotIn("<em>", html)
def test_comment_dropped(self):
self.assertEqual(md.render("a <!-- note --> b"), "<p>a b</p>")
def test_comment_lines_dropped(self):
html = md.render("<!-- BEGIN -->\n\ntext\n\n<!-- END -->")
self.assertEqual(html, "<p>text</p>")
self.assertNotIn("<!--", html)
def test_comment_inside_fence_kept(self):
html = md.render("```\n<!-- keep -->\n```")
self.assertIn("&lt;!-- keep --&gt;", html)
class BlocksTest(unittest.TestCase):
def test_blockquote(self):
html = md.render("> quoted **text**")
self.assertEqual(html, "<blockquote>\n<p>quoted "
"<strong>text</strong></p>\n</blockquote>")
def test_multiline_blockquote(self):
html = md.render("> one\n> two")
self.assertIn("one\ntwo", html)
def test_hr(self):
self.assertEqual(md.render("---"), "<hr>")
self.assertEqual(md.render("a\n\n***\n\nb"),
"<p>a</p>\n<hr>\n<p>b</p>")
class RealDocumentsTest(unittest.TestCase):
def test_all_documents_well_formed(self):
for name in DOCS:
with self.subTest(doc=name):
checker = check_well_formed(md.render(read_doc(name)))
self.assertEqual(checker.errors, [])
self.assertEqual(checker.stack, [])
def test_all_link_hrefs_non_empty(self):
linked = {"README.md", "SOURCES.md", "NOTICE.md"}
for name in DOCS:
with self.subTest(doc=name):
checker = check_well_formed(md.render(read_doc(name)))
if name in linked:
self.assertTrue(checker.hrefs,
"no links found in %s" % name)
for href in checker.hrefs:
self.assertTrue(href, "empty href in %s" % name)
def test_no_comments_survive(self):
for name in DOCS:
with self.subTest(doc=name):
self.assertNotIn("<!--", md.render(read_doc(name)))
def test_no_inline_styles(self):
for name in DOCS:
with self.subTest(doc=name):
self.assertNotIn("style=", md.render(read_doc(name)))
def test_readme_table_row_counts(self):
counter = TableCounter()
counter.feed(md.render(read_doc("README.md")))
counter.close()
self.assertEqual(counter.counts, [104, 34])
def test_readme_num_class_present(self):
self.assertIn('class="num"', md.render(read_doc("README.md")))
def test_readme_headings(self):
top = md.headings(read_doc("README.md"))[0]
self.assertEqual(top, (1, "Open Long Trails", "open-long-trails"))
def test_readme_offset(self):
html = md.render(read_doc("README.md"), heading_offset=1)
self.assertNotIn("<h1", html)
self.assertIn('<h2 id="open-long-trails">Open Long Trails</h2>', html)
def test_rewrite_called_for_every_real_link(self):
seen = []
html = md.render(read_doc("README.md"),
link_rewrite=lambda h: seen.append(h) or h)
self.assertTrue(seen)
for href in seen:
self.assertTrue(href)
def test_rewrite_changes_real_hrefs(self):
plain = md.render(read_doc("SOURCES.md"))
rewritten = md.render(read_doc("SOURCES.md"),
link_rewrite=lambda h: "/go/?u=" + h)
self.assertNotEqual(plain, rewritten)
self.assertNotIn('href="https://', rewritten)
checker = check_well_formed(rewritten)
self.assertEqual(checker.errors, [])
self.assertEqual(checker.stack, [])
if __name__ == "__main__":
unittest.main()
+451
View File
@@ -0,0 +1,451 @@
"""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.
"""
import html
import os
import re
import subprocess
import sys
import tempfile
import tomllib
import unittest
from html.parser import HTMLParser
WEB = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
ROOT = os.path.dirname(WEB)
sys.path.insert(0, WEB)
from olt import layout, pages, records, site, trail, words # noqa: E402
OUT = os.path.join(WEB, ".cache", "test-site")
# Linked from the shared navigation and footer; written by other page modules.
# Remove a path from this set once its page exists.
PENDING_PAGES = set()
class Tags(HTMLParser):
"""Collect every start tag with its attributes, and <script> contents."""
def __init__(self):
super().__init__(convert_charrefs=True)
self.tags = []
self.scripts = []
self._in_script = None
def handle_starttag(self, tag, attrs):
a = dict(attrs)
self.tags.append((tag, a))
if tag == "script":
self._in_script = [a, ""]
def handle_data(self, data):
if self._in_script is not None:
self._in_script[1] += data
def handle_endtag(self, tag):
if tag == "script" and self._in_script is not None:
self.scripts.append(tuple(self._in_script))
self._in_script = None
def parse(path):
p = Tags()
with open(path, encoding="utf-8") as f:
p.feed(f.read())
return p
def html_files(out):
for base, _, names in os.walk(out):
for n in names:
if n.endswith(".html"):
yield os.path.join(base, n)
def resolve(out, url):
"""File for a root-relative URL, or None when the URL is not a local path."""
if not url.startswith("/") or url.startswith("//"):
return None
path = url.split("#", 1)[0].split("?", 1)[0]
if path.endswith("/"):
path += "index.html"
return os.path.join(out, *path.lstrip("/").split("/"))
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)
cls.records = records.load_records(ROOT)
cls.pages = {}
for rec in cls.records:
with open(os.path.join(OUT, "trails", rec["id"], "index.html"), encoding="utf-8") as f:
cls.pages[rec["id"]] = f.read()
def test_one_detail_page_per_record(self):
found = [d for d in os.listdir(os.path.join(OUT, "trails"))
if os.path.isfile(os.path.join(OUT, "trails", d, "index.html"))]
self.assertEqual(len(self.records), 138)
self.assertEqual(sorted(found), sorted(r["id"] for r in self.records))
self.assertTrue(os.path.isfile(os.path.join(OUT, "index.html")))
def test_record_files_copied(self):
for rec in self.records:
tdir = os.path.join(OUT, "trails", rec["id"])
self.assertTrue(os.path.isfile(os.path.join(tdir, "trail.toml")), rec["id"])
has_release = os.path.isfile(os.path.join(ROOT, rec["id"], "release.txt"))
self.assertEqual(os.path.isfile(os.path.join(tdir, "release.txt")), has_release, rec["id"])
def test_internal_links_resolve(self):
missing = set()
for path in html_files(OUT):
for tag, a in parse(path).tags:
for key in ("href", "src"):
url = a.get(key)
if not url or url.split("?")[0].split("#")[0] in PENDING_PAGES:
continue
target = resolve(OUT, url)
if target and not os.path.isfile(target):
missing.add((os.path.relpath(path, OUT), url))
self.assertFalse(url.startswith(("http://", "https://")) and tag in ("script", "link")
and a.get("rel") != "canonical", f"external asset {url} in {path}")
self.assertEqual(sorted(missing)[:20], [])
def test_no_inline_scripts(self):
for path in html_files(OUT):
for a, body in parse(path).scripts:
if a.get("type") in ("application/json", "application/ld+json"):
continue
self.assertTrue(a.get("src"), f"inline script in {path}")
self.assertEqual(body.strip(), "", f"script with src and a body in {path}")
def test_style_attributes_only_carry_custom_properties(self):
# The CSP allows style="" (style-src-attr) only for data passed to CSS.
for path in html_files(OUT):
for tag, a in parse(path).tags:
if "style" in a:
self.assertRegex(a["style"], r"^\s*--[a-z-]+:\s*[-0-9.%]+;?\s*$", f"{tag} in {path}")
def test_record_only_pages_have_no_line_downloads(self):
for rec in self.records:
if rec["derived"]["has_line"]:
continue
for tag, a in parse(os.path.join(OUT, "trails", rec["id"], "index.html")).tags:
href = a.get("href", "")
line_file = href.startswith("/trails/") and href.endswith((".gpx", ".geojson"))
self.assertFalse(line_file or "download" in a, f"{rec['id']} links {href}")
def test_line_pages_offer_every_download(self):
for rec in self.records:
if not rec["derived"]["has_line"]:
continue
page = self.pages[rec["id"]]
names = trail_downloads(rec["id"])
self.assertTrue(names, rec["id"])
for name in names:
self.assertIn(f'href="/trails/{rec["id"]}/{name}"', page, rec["id"])
self.assertIn("simplified to 5 m", html.unescape(page), rec["id"])
def test_every_field_appears(self):
"""Each field the record carries is on its page (text or number, in some written form)."""
for rec in self.records:
with open(os.path.join(ROOT, rec["id"], "trail.toml"), "rb") as f:
raw = tomllib.load(f)
text = page_text(self.pages[rec["id"]])
for field, value in leaves(raw):
if field.endswith(("line_file", "logo_file")) and value == "":
continue # shown as "None included"
for form in written_forms(value):
if form.lower() in text.lower():
break
else:
self.fail(f"{rec['id']}: {field} = {value!r} not on the page")
def test_partial_line_notice_and_row_note_for_exactly_the_partial_records(self):
"""Decided from the TOML alone: a line, measured, more than 15% from the published length."""
expected = set()
for rec in self.records:
with open(os.path.join(ROOT, rec["id"], "trail.toml"), "rb") as f:
raw = tomllib.load(f)
v = raw.get("verification", {})
if raw["source"].get("line_file") and v.get("verified") and abs(v.get("difference_percent", 0)) > 15:
expected.add(rec["id"])
self.assertEqual(len(expected), 15)
self.assertIn("voyageur", expected)
for rec in self.records:
page = self.pages[rec["id"]]
has_notice = 'class="notice notice--partial"' in page
self.assertEqual(has_notice, rec["id"] in expected, rec["id"])
if has_notice: # the notice is inside the download panel, above the buttons
panel = page[page.index('<section class="panel" id="download"'):]
self.assertLess(panel.index("notice--partial"), panel.index('<ul class="downloads">'), rec["id"])
v = rec["verification"]
text = page_text(panel[:panel.index('<ul class="downloads">')])
self.assertIn(f"measures {v['measured_km']:,.1f} km against a published "
f"{rec['length_km']:,} km ({words.fmt_percent(v['difference_percent'])})", text)
self.assertIn(re.sub(r"\s+", " ", rec["source"]["length_gap_note"]), text, rec["id"])
short = rec["id"] in expected and rec["verification"]["difference_percent"] < 0
self.assertEqual("In the dataset, partial" in page, short, rec["id"])
if rec["derived"]["has_line"]:
self.assertRegex(page, r'<dt>Line</dt><dd><a href="#download">In the dataset', rec["id"])
rows_seen = set()
for path in html_files(OUT):
with open(path, encoding="utf-8") as f:
doc = f.read()
rel = os.path.relpath(path, OUT)
for m in re.finditer(r'<li class="entry" data-id="([^"]+)"([^>]*)>(.*?)\n</li>', doc, re.S):
tid, attrs, row = m.groups()
self.assertEqual('data-partial="yes"' in attrs, tid in expected, f"{rel}: {tid}")
self.assertEqual(row.count('class="entry__partial"'), 1 if tid in expected else 0, f"{rel}: {tid}")
if tid in expected:
rows_seen.add(tid)
self.assertRegex(page_text(row), r"Line measures [\d,.]+ km (of|against) [\d,]+ km published")
entries = len(re.findall(r'<li class="entry" ', doc))
partial_rows = len(re.findall(r'<li class="entry" [^>]*data-partial="yes"', doc))
self.assertEqual(doc.count('class="entry__partial"'), partial_rows, rel)
if not entries:
self.assertNotIn("entry__partial", doc, rel)
if not rel.startswith("trails" + os.sep):
self.assertNotIn("notice--partial", doc, rel)
self.assertEqual(rows_seen, expected)
def test_gpx_first_and_primary_in_every_download_group(self):
groups = 0
for rec in self.records:
for group in re.findall(r'<li class="download">(.*?)</li>', self.pages[rec["id"]], re.S):
groups += 1
label = html.unescape(re.search(r'<strong id="[^"]+">(.*?)</strong>', group).group(1))
links = re.findall(r'<a class="([^"]*)" href="[^"]+\.(gpx|geojson)"[^>]*>(.*?)</a>', group, re.S)
kinds = [k for _, k, _ in links]
self.assertTrue(kinds, rec["id"])
if "gpx" in kinds:
self.assertEqual(kinds[0], "gpx", f"{rec['id']}: {label}")
self.assertIn("button--primary", links[0][0], rec["id"])
self.assertEqual(sorted(kinds, key=lambda k: k != "gpx"), kinds, rec["id"])
for cls, kind, inner in links:
# the accessible name: the link's text, visually hidden parts included
name = re.sub(r"\s+", " ", html.unescape(re.sub(r"<[^>]+>", "", inner))).strip()
fmt = "GPX" if kind == "gpx" else "GeoJSON"
self.assertRegex(name, rf"^{re.escape(label)}: {fmt}, [\d.,]+ [KM]?B$", rec["id"])
self.assertEqual("button--primary" in cls, kind == "gpx", rec["id"])
if label.startswith("Extract"):
self.assertNotIn("swatch", group, rec["id"])
self.assertGreater(groups, 85)
def test_raw_record_table_holds_every_field(self):
for rec in self.records:
with open(os.path.join(ROOT, rec["id"], "trail.toml"), "rb") as f:
raw = tomllib.load(f)
page = self.pages[rec["id"]]
self.assertIn('<details class="rawrecord">', page, rec["id"])
# the last block of the page's main column
tail = page[page.index('<details class="rawrecord">'):]
self.assertNotIn('<section class="block"', tail, rec["id"])
table = re.search(r'<table class="rawrecord__table">(.*?)</table>', tail, re.S).group(1)
rows = {html.unescape(f): re.sub(r"\s+", " ", html.unescape(v)).strip()
for f, v in re.findall(r'<tr><th scope="row"><code>(.*?)</code></th><td>(.*?)</td></tr>', table, re.S)}
fields = dict(leaves(raw))
self.assertEqual(set(rows), set(fields), rec["id"])
for field, value in fields.items():
self.assertEqual(rows[field], re.sub(r"\s+", " ", trail.raw_value(value)).strip(), f"{rec['id']}: {field}")
def test_no_raw_tokens_in_the_main_flow(self):
for rec in self.records:
page = self.pages[rec["id"]]
main = page[page.index('<div class="detail__main">'):page.index('<details class="rawrecord">')]
codes = set(html.unescape(c) for c in re.findall(r'<code class="raw">(.*?)</code>', main))
self.assertLessEqual(codes, {rec["id"]}, rec["id"])
# main-column sections are not landmarks; the aside panels are
self.assertNotIn('<section class="block" aria-labelledby', page, rec["id"])
self.assertIn('<section class="panel" aria-labelledby="links-title">', page, rec["id"])
def test_record_without_a_line_says_so_once(self):
for rec in self.records:
page = self.pages[rec["id"]]
main = page_text(page[page.index('<div class="detail__main">'):page.index('<details class="rawrecord">')])
helper = "Where to ask for the line: a layer or relation page"
if rec["derived"]["has_line"]:
self.assertEqual(helper in main, bool(rec["source"].get("url")), rec["id"])
continue
self.assertNotIn(helper, main, rec["id"])
for gone in ("none (no line included)", "None (no line included)", "No line to measure", "None recorded"):
self.assertNotIn(gone, main, rec["id"])
for row in ("Coordinates", "May be passed on", "OpenStreetMap only", "Line source",
"Line in this dataset", "Why there is no line"):
self.assertNotIn(f"<dt>{row}</dt>", page, rec["id"])
if not rec["derived"]["files"].get("shield"):
logo = re.search(r'<h2 id="logo-title">Logo</h2>(.*?)</section>', page, re.S).group(1)
self.assertEqual(logo.count("<p"), 1, rec["id"])
self.assertNotIn("<dl", logo, rec["id"])
def test_all_guides_button_only_with_more_than_one_guide(self):
for rec in self.records:
page = self.pages[rec["id"]]
if rec["derived"]["has_line"] or rec["derived"]["kind"] != "route":
continue
frame = page[page.index('<figure class="mapfig mapfig--empty'):page.index("</figure>")]
self.assertEqual(">All guides<" in frame, len(rec.get("guide", [])) > 1
and rec["route"]["line_policy"] == "open"
and any(g.get("access") == "free" for g in rec["guide"]), rec["id"])
def test_names_marked_with_their_language(self):
langs = site.load().name_lang
self.assertEqual(langs, {"traversee-charlevoix": "fr", "sentier-national": "fr",
"sentier-international-appalaches": "fr"})
with open(os.path.join(OUT, "index.html"), encoding="utf-8") as f:
home = f.read()
by_id = {r["id"]: r for r in self.records}
for tid, lang in langs.items():
marked = f'<span lang="{lang}">{html.escape(by_id[tid]["name"], quote=True)}</span>'
self.assertIn(f'<a href="/trails/{tid}/">{marked}</a>', home, tid)
page = self.pages[tid]
self.assertIn(f"<h1>{marked}", page, tid)
self.assertIn(f'<li aria-current="page">{marked}</li>', page, tid)
for path in html_files(OUT):
with open(path, encoding="utf-8") as f:
for m in re.finditer(r'<span lang="([^"]+)">([^<]*)</span>', f.read()):
names = {html.escape(by_id[t]["name"], quote=True) for t in langs}
self.assertIn(m.group(2), names, path)
def test_every_table_head_cell_has_col_scope(self):
for path in html_files(OUT):
with open(path, encoding="utf-8") as f:
doc = f.read()
for head in re.findall(r"<thead>(.*?)</thead>", doc, re.S):
for th in re.findall(r"<th\b[^>]*>", head):
self.assertIn('scope="col"', th, path)
def test_app_script_loads_before_maplibre(self):
with open(os.path.join(OUT, "index.html"), encoding="utf-8") as f:
doc = f.read()
app, maplibre = doc.index('src="/assets/app.js" defer'), doc.index('maplibre-gl.js" defer')
self.assertLess(app, maplibre)
def test_not_found_page_has_a_search_form(self):
with open(os.path.join(OUT, "404.html"), encoding="utf-8") as f:
doc = f.read()
form = re.search(r'<form class="notfound-search" action="/" method="get"[^>]*>(.*?)</form>', doc, re.S)
self.assertIsNotNone(form)
field = re.search(r'<input class="input" id="([^"]+)" name="q"', form.group(1))
self.assertIsNotNone(field)
self.assertIn(f'<label class="field__label" for="{field.group(1)}">', form.group(1))
self.assertIn('type="submit"', form.group(1))
self.assertNotIn("&lt;id&gt;", doc)
def test_titles_and_descriptions(self):
name = site.load().name
for path in html_files(OUT):
p = parse(path)
metas = [a for t, a in p.tags if t == "meta" and a.get("name") == "description"]
self.assertEqual(len(metas), 1, path)
self.assertTrue(metas[0].get("content"), path)
with open(path, encoding="utf-8") as f:
doc = f.read()
self.assertRegex(doc, r"<title>[^<]+</title>", path)
self.assertIn(html.escape(name), doc, path)
def trail_downloads(tid):
tdir = os.path.join(OUT, "trails", tid)
return [n for n in os.listdir(tdir) if n.endswith((".gpx", ".geojson"))]
def page_text(doc):
"""Visible text and attribute values of a page, unescaped, with whitespace collapsed."""
doc = re.sub(r"<[^>]+?(?:href|title|cite)=\"([^\"]*)\"[^>]*>", lambda m: " " + m.group(1) + " " + m.group(0), doc)
text = html.unescape(re.sub(r"<[^>]+>", " ", doc))
return re.sub(r"\s+", " ", text)
def leaves(obj, prefix=""):
if isinstance(obj, dict):
for k, v in obj.items():
yield from leaves(v, f"{prefix}.{k}" if prefix else k)
elif isinstance(obj, list):
for i, v in enumerate(obj):
yield from leaves(v, f"{prefix}[{i}]")
else:
yield prefix, obj
def written_forms(value):
"""The ways a value may be written on a page."""
if isinstance(value, bool):
return [str(value).lower()]
if isinstance(value, (int, float)):
forms = [str(value), words.fmt_km(value), words.fmt_percent(value), f"{abs(value):.1f}"]
return forms
text = re.sub(r"\s+", " ", str(value)).strip()
return [text, text.replace("`", "")]
class RenderUnitTest(unittest.TestCase):
def test_names_are_escaped(self):
rec = sample_record(name='Trail & "Quotes" <b>bold</b>')
_, description, body, _ = trail.render(rec, site.Site("Site & Co", "Tag"))
doc = layout.layout(rec["name"], body, path="/trails/x/", description=description,
site=site.Site("Site & Co", "Tag"))
self.assertIn("Trail &amp; &quot;Quotes&quot; &lt;b&gt;bold&lt;/b&gt;", doc)
self.assertNotIn("<b>bold</b>", doc)
self.assertNotIn("<script>alert", doc)
self.assertIn("Site &amp; Co", doc)
self.assertIn('href="https://example.org/?a=1&amp;b=2"', doc)
def test_canonical_only_with_base_url(self):
doc = layout.layout("T", "", path="/trails/x/", site=site.Site("N", "T"))
self.assertNotIn('rel="canonical"', doc)
doc = layout.layout("T", "", path="/trails/x/", site=site.Site("N", "T", base_url="https://example.org/"))
self.assertIn('<link rel="canonical" href="https://example.org/trails/x/">', doc)
def test_site_name_comes_from_settings(self):
doc = layout.layout("", "", path="/", site=site.Site("Another Name", "A tagline"))
self.assertIn("<title>Another Name: A tagline</title>", doc)
self.assertNotIn("Long Hikes", doc)
def test_report_links_need_repo_url(self):
self.assertNotIn("/issues", layout.footer(site.Site("N", "T")))
self.assertIn("https://example.org/repo/issues", layout.footer(site.Site("N", "T", repo_url="https://example.org/repo")))
def test_render_site_on_a_synthetic_record(self):
with tempfile.TemporaryDirectory() as tmp:
repo, out = os.path.join(tmp, "repo"), os.path.join(tmp, "out")
os.makedirs(os.path.join(repo, "x"))
with open(os.path.join(repo, "x", "trail.toml"), "w", encoding="utf-8") as f:
f.write('id = "x"\n')
rec = sample_record(name="A & B")
n = pages.render_site([rec], out, repo, site=site.Site("N", "T"))
# trail page + home + 404 + regions index + 1 region + routes,
# sources, logos, about, data, schema, changelog
self.assertEqual(n, 12)
with open(os.path.join(out, "trails", "x", "index.html"), encoding="utf-8") as f:
self.assertIn("A &amp; B", f.read())
with open(os.path.join(out, "index.html"), encoding="utf-8") as f:
self.assertIn('href="/trails/x/"', f.read())
def sample_record(name):
return {
"id": "x", "name": name, "short_name": "X", "country": "US", "regions": ["AZ"],
"length_km": 100, "length_note": "about 62 mi", "tier": "regional", "designation": "A & B Association",
"wave": 1,
"source": {"status": "none", "publisher": "P", "url": "https://example.org/?a=1&b=2", "format": "None",
"crs": "EPSG:4326", "licence": "none-stated", "licence_text": "None.", "attribution": "none",
"osm_only": False, "mainline": "None", "source_checked": "2026-11-10", "redistributable": True,
"line_source": "none (no line included)", "line_file": "",
"line_absent_reason": "No line is included. <script>alert(1)</script>"},
"osm": {"relation": 0, "note": "None"},
"shield": {"status": "no-logo-exists", "logo_source": "", "contact": "P", "note": "None",
"logo_file": "", "logo_owner": "P"},
"verification": {"verified": False, "note": "No line to measure."},
"derived": {"kind": "designated", "has_line": False, "length_mi": 62, "files": {},
"status": "record-only", "downloads": []},
}
if __name__ == "__main__":
unittest.main()
+48
View File
@@ -0,0 +1,48 @@
import os
import sys
import unittest
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from olt import records # noqa: E402
class RecordsTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.recs = records.load_records()
def test_counts(self):
self.assertEqual(len(self.recs), 138)
self.assertEqual(sum(r["derived"]["kind"] == "route" for r in self.recs), 34)
self.assertEqual(sum(r["derived"]["kind"] == "designated" for r in self.recs), 104)
self.assertEqual(sum(r["derived"]["has_line"] for r in self.recs), 85)
def test_sorted_by_id(self):
ids = [r["id"] for r in self.recs]
self.assertEqual(ids, sorted(ids))
def test_derived_fields(self):
by_id = {r["id"]: r for r in self.recs}
ct = by_id["colorado-trail"]
self.assertEqual(ct["derived"]["status"], "included")
self.assertEqual(ct["derived"]["length_mi"], 486)
self.assertEqual(sorted(ct["derived"]["files"]["extracts"]), ["osm", "usfs"])
self.assertEqual(ct["derived"]["files"]["line"], "colorado-trail/line.geojson")
self.assertEqual(ct["name"], "Colorado Trail") # TOML fields unchanged
def test_status_matches_csv(self):
import csv
path = os.path.join(records.ROOT, "trails.csv")
with open(path, encoding="utf-8", newline="") as f:
status = {row["id"]: row["status"] for row in csv.DictReader(f)}
for r in self.recs:
self.assertEqual(r["derived"]["status"], status[r["id"]])
def test_line_file_exists_when_has_line(self):
for r in self.recs:
self.assertEqual(r["derived"]["has_line"], "line" in r["derived"]["files"])
if __name__ == "__main__":
unittest.main()
+163
View File
@@ -0,0 +1,163 @@
"""Logo thumbnails: the committed web/thumbs, what the built pages show, and the fallback."""
import contextlib
import io
import os
import shutil
import subprocess
import sys
import tempfile
import unittest
from html.parser import HTMLParser
WEB = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
ROOT = os.path.dirname(WEB)
sys.path.insert(0, WEB)
from olt import records, thumbs # noqa: E402
OUT = os.path.join(WEB, ".cache", "test-site")
MAX_SIDE = 256
class Imgs(HTMLParser):
def __init__(self):
super().__init__(convert_charrefs=True)
self.imgs = []
def handle_starttag(self, tag, attrs):
if tag == "img":
self.imgs.append(dict(attrs))
def page_imgs(path):
p = Imgs()
with open(path, encoding="utf-8") as f:
p.feed(f.read())
return p.imgs
def html_files(out):
for base, _, names in os.walk(out):
for n in names:
if n.endswith(".html"):
yield os.path.join(base, n)
def repository_png_logos():
"""{id: path} for each <id>/shield.png directly under the repository root."""
found = {}
for name in os.listdir(ROOT):
path = os.path.join(ROOT, name, "shield.png")
if not name.startswith((".", "_")) and os.path.isfile(path):
found[name] = path
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_png_logo_has_a_thumbnail_no_larger_than_256(self):
logos = repository_png_logos()
self.assertTrue(logos)
for tid in logos:
thumb = os.path.join(WEB, "thumbs", f"{tid}.png")
self.assertTrue(os.path.isfile(thumb), f"{tid}: no {thumb}")
w, h = thumbs.png_size(thumb)
self.assertLessEqual(w, MAX_SIDE, tid)
self.assertLessEqual(h, MAX_SIDE, tid)
self.assertGreater(min(w, h), 0, tid)
def test_no_thumbnail_without_a_source(self):
logos = repository_png_logos()
thumbs_dir = os.path.join(WEB, "thumbs")
for name in os.listdir(thumbs_dir):
self.assertIn(name[:-len(".png")], logos, f"orphan thumbnail {name}")
def test_fallback_to_full_size_when_no_thumbnail(self):
tid = "x"
with tempfile.TemporaryDirectory() as tmp:
repo, out, empty = (os.path.join(tmp, n) for n in ("repo", "out", "thumbs"))
os.makedirs(os.path.join(repo, tid))
os.makedirs(empty)
src = repository_png_logos()["cohos"]
shutil.copyfile(src, os.path.join(repo, tid, "shield.png"))
os.makedirs(os.path.join(out, "trails", tid))
rec = {"id": tid, "derived": {"files": {"shield": f"{tid}/shield.png"}}}
err = io.StringIO()
with contextlib.redirect_stderr(err):
thumbs.prepare(rec, out, repo, thumb_dir=empty)
self.assertIn(f"{tid}:", err.getvalue())
self.assertEqual(err.getvalue().count("warning"), 1)
logo = rec["derived"]["logo_img"]
self.assertEqual(logo["src"], f"/trails/{tid}/shield.png")
self.assertEqual((logo["width"], logo["height"]), thumbs.png_size(src))
self.assertFalse(os.path.exists(os.path.join(out, "trails", tid, thumbs.THUMB_NAME)))
def test_svg_logo_gets_no_thumbnail(self):
rec = {"id": "x", "derived": {"files": {"shield": "x/shield.svg"}, "logo_img": {"src": "stale"}}}
with tempfile.TemporaryDirectory() as tmp:
thumbs.prepare(rec, tmp, tmp, thumb_dir=tmp)
self.assertNotIn("logo_img", rec["derived"])
class BuiltPagesTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
os.makedirs(os.path.dirname(OUT), exist_ok=True)
build()
cls.records = records.load_records(ROOT)
cls.png = [r["id"] for r in cls.records
if r["derived"]["files"].get("shield", "").endswith(".png")]
cls.all_imgs = [(path, img) for path in html_files(OUT) for img in page_imgs(path)]
def test_list_pages_show_thumbnails_not_full_size_pngs(self):
for path, img in self.all_imgs:
self.assertFalse(img.get("src", "").endswith("/shield.png"), f"{path} shows {img.get('src')}")
for page in ("index.html", os.path.join("logos", "index.html")):
with open(os.path.join(OUT, page), encoding="utf-8") as f:
doc = f.read()
for tid in self.png:
self.assertIn(f'src="/trails/{tid}/shield-thumb.png"', doc, f"{page} for {tid}")
def test_thumbnail_width_and_height_match_the_file(self):
seen = 0
for path, img in self.all_imgs:
src = img.get("src", "")
if not src.endswith("/" + thumbs.THUMB_NAME):
continue
seen += 1
w, h = thumbs.png_size(os.path.join(OUT, src.lstrip("/")))
self.assertEqual((img.get("width"), img.get("height")), (str(w), str(h)), path)
self.assertEqual(img.get("decoding"), "async", path)
self.assertGreaterEqual(seen, len(self.png) * 2)
def test_record_header_logo_is_eager_and_links_full_size(self):
for tid in self.png:
with open(os.path.join(OUT, "trails", tid, "index.html"), encoding="utf-8") as f:
doc = f.read()
self.assertIn(f'<a href="/trails/{tid}/shield.png"><img src="/trails/{tid}/shield-thumb.png"', doc, tid)
header = [i for i in page_imgs(os.path.join(OUT, "trails", tid, "index.html"))
if i.get("src") == f"/trails/{tid}/shield-thumb.png"]
self.assertEqual(len(header), 1, tid)
self.assertNotIn("loading", header[0], tid)
def test_logos_page_links_full_size_and_is_lazy(self):
for tid in self.png:
with open(os.path.join(OUT, "logos", "index.html"), encoding="utf-8") as f:
doc = f.read()
self.assertIn(f'<a href="/trails/{tid}/shield.png"><img src="/trails/{tid}/shield-thumb.png"', doc, tid)
for img in page_imgs(os.path.join(OUT, "logos", "index.html")):
if img.get("src", "").endswith(thumbs.THUMB_NAME):
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)
if __name__ == "__main__":
unittest.main()