Add 130 views of the same records, speed up map pages, and say who maintains the site
- New pages built from the records: lists by length, time to walk, month, kind of walking and holder; place-by-list pages; a Triple Crown table and key-figure tables for the National Scenic and Recreation Trails; highest points, most climbing and climb per mile; a page for every route author, with the authors of three or more routes leading the authors page; connected trails; recently added and changed; a glossary and a method page. Every place page opens with a summary. - Trail pages open with an "In brief" paragraph generated from the record and show when the record was last checked. The About page says who maintains the site and how to reach them. - The map starts when it is reached, not with the page. The site's own CSS, scripts and fonts are fingerprinted and cached for a year. Every image has its dimensions. - Titles are held to 60 characters and share previews get their own shorter description. - Social cards are redrawn so a long name can no longer push text into the footer, and the site-wide card takes its wording from the site settings instead of an old hand-made image. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
1 parent
5b80fccd1e
commit
f2d3b71810
266 files changed
+4658
-252
No files matched your search
@@ -0,0 +1,128 @@
|
||||
"""The social cards' layout, measured: no two text boxes overlap, nothing leaves the safe area,
|
||||
and the text column and the track never meet, for every record's card and the site card.
|
||||
|
||||
The boxes come from the same layout code that draws the cards (web/tools/make_cards.py), so a
|
||||
card cannot pass here and be drawn differently. Needs Pillow and fontTools (with brotli); the
|
||||
test is skipped where they are not installed."""
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
WEB = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
ROOT = os.path.dirname(WEB)
|
||||
sys.path.insert(0, WEB)
|
||||
sys.path.insert(0, os.path.join(WEB, "tools"))
|
||||
|
||||
try:
|
||||
import make_cards # noqa: E402
|
||||
from fontTools.ttLib import TTFont # noqa: E402
|
||||
HAVE = True
|
||||
except Exception: # Pillow, fontTools or brotli missing
|
||||
HAVE = False
|
||||
|
||||
from olt import cards, records, site # noqa: E402
|
||||
|
||||
SITE = os.path.join(WEB, ".cache", "test-site")
|
||||
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
|
||||
FOOT_CLEAR = 20 # px between the track and the footer line
|
||||
|
||||
|
||||
def overlap(a, b, gap=0):
|
||||
return a[0] < b[2] + gap and b[0] < a[2] + gap and a[1] < b[3] + gap and b[1] < a[3] + gap
|
||||
|
||||
|
||||
def track_parts(tid):
|
||||
"""The track as the card tool draws it: the site's map.json where one is built, else the
|
||||
record's own line (the box depends only on the track's extent)."""
|
||||
for path in (os.path.join(SITE, "trails", tid, "map.json"), os.path.join(ROOT, tid, "line.geojson")):
|
||||
if os.path.isfile(path):
|
||||
return make_cards.parts_of(path)
|
||||
return []
|
||||
|
||||
|
||||
@unittest.skipUnless(HAVE, "needs Pillow and fontTools")
|
||||
class CardLayout(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.tmp = tempfile.TemporaryDirectory()
|
||||
cls.fonts = make_cards.load_fonts(cls.tmp.name)
|
||||
cls.measure = make_cards.Measure(cls.fonts)
|
||||
cls.recs = records.load_records(ROOT)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.tmp.cleanup()
|
||||
|
||||
def check(self, lay, label):
|
||||
boxes = make_cards.boxes_of(lay)
|
||||
text = [(k, b) for k, b in boxes if k in ("name", "length", "places", "header", "footer")]
|
||||
W, H = make_cards.W, make_cards.H
|
||||
self.assertTrue(lay.get("fits", True), f"{label}: the text does not fit at the smallest name size")
|
||||
self.assertGreaterEqual(lay["name_size"], make_cards.NAME_MIN, label)
|
||||
for (ka, a), (kb, b) in ((x, y) for i, x in enumerate(text) for y in text[i + 1:]):
|
||||
self.assertFalse(overlap(a, b, GAP), f"{label}: {ka} {a} and {kb} {b} overlap or touch")
|
||||
top, bottom = make_cards.SAFE_TOP, make_cards.SAFE_BOTTOM
|
||||
for kind, box in text:
|
||||
self.assertGreaterEqual(box[0], make_cards.MARGIN - 8, f"{label}: {kind} {box}") # 8: a J or f overhangs its origin
|
||||
self.assertLessEqual(box[2], make_cards.MARGIN + lay["width"] + 8, f"{label}: {kind} {box} is wider than its column")
|
||||
if kind in ("name", "length", "places"):
|
||||
self.assertGreaterEqual(box[1], top, f"{label}: {kind} {box} is above the safe area")
|
||||
self.assertLessEqual(box[3], bottom, f"{label}: {kind} {box} is below the safe area")
|
||||
for kind, box in text:
|
||||
self.assertTrue(0 <= box[0] and box[2] <= W and 0 <= box[1] and box[3] <= H - 14, f"{label}: {kind} {box} leaves the card")
|
||||
mark = dict(boxes)["mark"]
|
||||
for kind, box in text:
|
||||
if kind in ("name", "length", "places"):
|
||||
self.assertFalse(overlap(box, mark, GAP), f"{label}: {kind} meets the mark")
|
||||
for kind, box in boxes:
|
||||
if kind == "track":
|
||||
self.assertGreaterEqual(box[0], make_cards.MARGIN + lay["width"] + TRACK_GAP - 1, f"{label}: track {box} meets the text column")
|
||||
self.assertGreaterEqual(box[1], EDGE, f"{label}: track {box}")
|
||||
self.assertLessEqual(box[2], W - EDGE, f"{label}: track {box}")
|
||||
self.assertLessEqual(box[3], make_cards.FOOT_Y - FOOT_CLEAR, f"{label}: track {box} reaches the footer")
|
||||
for k, b in text:
|
||||
self.assertFalse(overlap(box, b, TRACK_GAP), f"{label}: track {box} and {k} {b}")
|
||||
|
||||
def test_every_trail_card_is_laid_out_cleanly(self):
|
||||
for rec in self.recs:
|
||||
parts = track_parts(rec["id"])
|
||||
self.check(make_cards.layout(self.measure, rec, parts), rec["id"])
|
||||
|
||||
def test_site_card_is_laid_out_cleanly(self):
|
||||
cfg = site.from_file(os.path.join(WEB, "site.toml"))
|
||||
self.check(make_cards.site_layout(self.measure, cfg), "site card")
|
||||
|
||||
def test_every_character_is_in_the_fonts(self):
|
||||
have = {}
|
||||
for key, path in self.fonts.items():
|
||||
have[key] = set(TTFont(path).getBestCmap())
|
||||
cfg = site.from_file(os.path.join(WEB, "site.toml"))
|
||||
texts = [(r["id"], t) for r in self.recs for t in cards.lines(r)]
|
||||
texts += [("site", t) for t in cards.site_lines(cfg)] + [("mark", "Long Hikes longhikes.org")]
|
||||
for who, t in texts:
|
||||
for ch in t:
|
||||
self.assertTrue(ord(ch) in have["serif"] or ch.isspace(), f"{who}: {ch!r} (U+{ord(ch):04X}) is not in the serif font")
|
||||
for r in self.recs:
|
||||
for ch in cards.where(r):
|
||||
self.assertIn(ord(ch), have["sans"], f"{r['id']}: places {ch!r} is not in the sans font")
|
||||
|
||||
def test_a_place_list_is_cut_to_two_lines(self):
|
||||
m = self.measure
|
||||
f = m.font("sans", 30)
|
||||
names = "Newfoundland and Labrador, British Columbia, Northwest Territories, Saskatchewan, Nova Scotia"
|
||||
lines = make_cards.short_places(names, m, f, make_cards.COL_TRACK)
|
||||
self.assertLessEqual(len(lines), 2)
|
||||
self.assertIn("more", " ".join(lines))
|
||||
|
||||
def test_a_long_name_is_never_cut(self):
|
||||
name = "Sentier international des Appalaches (International Appalachian Trail, Quebec and New Brunswick)"
|
||||
items, size, fits = make_cards.flow(self.measure, name, "731 miles · 1,177 km", "Quebec", 660)
|
||||
got = " ".join(t for k, t, *_ in items if k == "name")
|
||||
self.assertEqual(got.split(), name.split())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -63,7 +63,7 @@ class ExtraPagesTest(unittest.TestCase):
|
||||
self.assertEqual(len(routes), 57)
|
||||
page = read_out("routes/index.html")
|
||||
import html as _html
|
||||
text = _html.unescape(page)
|
||||
text = _html.unescape(re.sub(r"<[^>]+>", "", page)) # a credit naming two authors links each name
|
||||
for r in routes:
|
||||
self.assertIn(f'href="/trails/{r["id"]}/"', page, r["id"])
|
||||
self.assertIn(r["route"]["creator"], text, r["id"])
|
||||
|
||||
@@ -0,0 +1,235 @@
|
||||
"""Fingerprinted assets: the names, the files the build writes, every reference to them in
|
||||
the built pages, and the response headers that make them cacheable for a year."""
|
||||
import hashlib
|
||||
import os
|
||||
import re
|
||||
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 fingerprint, layout # noqa: E402
|
||||
import serve # noqa: E402
|
||||
|
||||
OUT = os.path.join(WEB, ".cache", "test-site")
|
||||
NAME = re.compile(r"^/immutable/[a-z0-9.-]+\.[0-9a-f]{10}\.[a-z0-9]+$")
|
||||
|
||||
|
||||
class NamesTest(unittest.TestCase):
|
||||
def test_a_fingerprinted_address_names_the_hash_of_the_content(self):
|
||||
for path in fingerprint.FILES:
|
||||
address = fingerprint.url(path)
|
||||
self.assertRegex(address, NAME, path)
|
||||
digest = hashlib.sha256(fingerprint._content(path)).hexdigest()[:10]
|
||||
stem, ext = os.path.splitext(os.path.basename(path))
|
||||
self.assertEqual(address, f"/immutable/{stem}.{digest}{ext}")
|
||||
|
||||
def test_other_assets_keep_their_address(self):
|
||||
for path in ("/assets/og.png", "/assets/favicon.svg", "/assets/map/outdoor.json",
|
||||
"/assets/vendor/maplibre-gl/LICENSE.txt"):
|
||||
self.assertEqual(fingerprint.url(path), path)
|
||||
|
||||
def test_every_file_exists_and_names_are_unique(self):
|
||||
names = [fingerprint.url(p) for p in fingerprint.FILES]
|
||||
self.assertEqual(len(set(names)), len(names))
|
||||
for path in fingerprint.FILES:
|
||||
self.assertTrue(os.path.isfile(os.path.join(WEB, *path.lstrip("/").split("/"))), path)
|
||||
|
||||
def test_the_stylesheet_names_its_fonts_and_picture_by_their_hashed_names(self):
|
||||
css = fingerprint._content(fingerprint.STYLESHEET).decode("utf-8")
|
||||
for target in re.findall(r'url\("([^"]+)"\)', css):
|
||||
self.assertRegex(target, r"\.[0-9a-f]{10}\.(woff2|svg)$", target)
|
||||
for path in fingerprint.FILES:
|
||||
if path.endswith((".woff2", "contours.svg")):
|
||||
self.assertIn(fingerprint.url(path).rsplit("/", 1)[1], css, path)
|
||||
self.assertNotIn('url("fonts/', css)
|
||||
|
||||
def test_a_changed_file_gets_a_new_name_and_so_does_what_names_it(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
for rel in ("fonts", ):
|
||||
os.makedirs(os.path.join(tmp, rel))
|
||||
files = {"style.css": 'a{background:url("contours.svg")}', "contours.svg": "<svg/>", "app.js": "1;"}
|
||||
for rel, text in files.items():
|
||||
with open(os.path.join(tmp, rel), "w", encoding="utf-8") as f:
|
||||
f.write(text)
|
||||
saved = fingerprint.ASSETS_DIR, fingerprint.FILES
|
||||
try:
|
||||
fingerprint.ASSETS_DIR, fingerprint.FILES = tmp, ("/assets/style.css", "/assets/contours.svg", "/assets/app.js")
|
||||
fingerprint._cache.clear()
|
||||
first = {p: fingerprint.url(p) for p in fingerprint.FILES}
|
||||
with open(os.path.join(tmp, "contours.svg"), "w", encoding="utf-8") as f:
|
||||
f.write("<svg><path/></svg>")
|
||||
os.utime(os.path.join(tmp, "contours.svg"), (1, 2))
|
||||
second = {p: fingerprint.url(p) for p in fingerprint.FILES}
|
||||
finally:
|
||||
fingerprint.ASSETS_DIR, fingerprint.FILES = saved
|
||||
fingerprint._cache.clear()
|
||||
self.assertNotEqual(first["/assets/contours.svg"], second["/assets/contours.svg"])
|
||||
self.assertNotEqual(first["/assets/style.css"], second["/assets/style.css"]) # it names the picture
|
||||
self.assertEqual(first["/assets/app.js"], second["/assets/app.js"])
|
||||
|
||||
|
||||
class PublishTest(unittest.TestCase):
|
||||
def test_publish_writes_the_files_and_takes_the_originals_out_of_assets(self):
|
||||
with tempfile.TemporaryDirectory() as out:
|
||||
shutil.copytree(fingerprint.ASSETS_DIR, os.path.join(out, "assets"))
|
||||
self.assertEqual(fingerprint.publish(out), len(fingerprint.FILES))
|
||||
written = sorted(os.listdir(os.path.join(out, "immutable")))
|
||||
self.assertEqual(written, sorted(fingerprint.url(p).rsplit("/", 1)[1] for p in fingerprint.FILES))
|
||||
for path in fingerprint.FILES:
|
||||
self.assertFalse(os.path.exists(os.path.join(out, *path.lstrip("/").split("/"))), path)
|
||||
# what is not fingerprinted stays
|
||||
self.assertTrue(os.path.isfile(os.path.join(out, "assets", "og.png")))
|
||||
self.assertTrue(os.path.isfile(os.path.join(out, "assets", "map", "outdoor.json")))
|
||||
# the file is its hash: a second publish writes the same names
|
||||
fingerprint.publish(out)
|
||||
self.assertEqual(sorted(os.listdir(os.path.join(out, "immutable"))), written)
|
||||
|
||||
|
||||
class LayoutTest(unittest.TestCase):
|
||||
def doc(self, **kw):
|
||||
from olt import site
|
||||
return layout.layout("T", "<p>x</p>", path="/x/", site=site.Site("N", "T"), **kw)
|
||||
|
||||
def test_the_head_names_hashed_files_and_a_map_page_gives_the_script_the_libraries(self):
|
||||
plain = self.doc()
|
||||
for path in ("/assets/style.css", "/assets/prefs.js", "/assets/app.js"):
|
||||
self.assertIn(fingerprint.url(path), plain)
|
||||
self.assertNotIn(path, plain)
|
||||
self.assertNotIn("maplibre", plain)
|
||||
mapped = self.doc(maps=True, outdoor=True)
|
||||
self.assertNotIn('<link rel="stylesheet" href="/immutable/maplibre', mapped) # nothing is loaded with the page
|
||||
self.assertNotRegex(mapped, r'<script src="/immutable/maplibre[^>]*>')
|
||||
tag = re.search(r'<script src="(/immutable/app\.[0-9a-f]{10}\.js)" defer([^>]*)></script>', mapped)
|
||||
self.assertIsNotNone(tag)
|
||||
self.assertIn(f'data-maplibre-js="{fingerprint.url(layout.MAPLIBRE_JS)}"', tag.group(2))
|
||||
self.assertIn(f'data-maplibre-css="{fingerprint.url(layout.MAPLIBRE_CSS)}"', tag.group(2))
|
||||
self.assertIn(f'data-contour-js="{fingerprint.url(layout.CONTOUR_JS)}"', tag.group(2))
|
||||
overview = self.doc(maps=True)
|
||||
self.assertNotIn("data-contour-js", overview)
|
||||
|
||||
def test_the_preloaded_fonts_are_the_hashed_ones(self):
|
||||
doc = self.doc()
|
||||
for font in layout.FONT_PRELOADS:
|
||||
self.assertIn(f'<link rel="preload" href="{fingerprint.url(font)}" as="font"', doc)
|
||||
|
||||
|
||||
class Refs(HTMLParser):
|
||||
def __init__(self):
|
||||
super().__init__(convert_charrefs=True)
|
||||
self.urls = []
|
||||
|
||||
def handle_starttag(self, tag, attrs):
|
||||
a = dict(attrs)
|
||||
for key in ("src", "href", "data-maplibre-js", "data-maplibre-css", "data-contour-js"):
|
||||
if a.get(key, "").startswith("/"):
|
||||
self.urls.append((key, a[key]))
|
||||
|
||||
|
||||
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)
|
||||
cls.pages = []
|
||||
for base, _, names in os.walk(OUT):
|
||||
for n in names:
|
||||
if n.endswith(".html"):
|
||||
cls.pages.append(os.path.join(base, n))
|
||||
cls.rules = serve.parse_headers(os.path.join(OUT, "_headers"))
|
||||
|
||||
def test_no_page_names_an_original_of_a_fingerprinted_file(self):
|
||||
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())
|
||||
for key, url in refs.urls:
|
||||
self.assertNotIn(url, originals, f"{page}: {url}")
|
||||
if url.startswith("/immutable/"):
|
||||
used += 1
|
||||
self.assertRegex(url, NAME, page)
|
||||
self.assertTrue(os.path.isfile(os.path.join(OUT, *url.lstrip("/").split("/"))), f"{page}: {url}")
|
||||
self.assertGreater(used, len(self.pages)) # at least the stylesheet and a script on every page
|
||||
|
||||
def test_every_page_loads_the_stylesheet_and_scripts_by_hashed_address(self):
|
||||
for page in self.pages:
|
||||
with open(page, encoding="utf-8") as f:
|
||||
doc = f.read()
|
||||
for path in ("/assets/style.css", "/assets/prefs.js", "/assets/app.js"):
|
||||
self.assertIn(fingerprint.url(path), doc, f"{page} lacks {path}")
|
||||
|
||||
def test_the_originals_are_not_in_the_build_and_the_hashed_files_are(self):
|
||||
for path in fingerprint.FILES:
|
||||
self.assertFalse(os.path.exists(os.path.join(OUT, *path.lstrip("/").split("/"))), path)
|
||||
self.assertTrue(os.path.isfile(os.path.join(OUT, *fingerprint.url(path).lstrip("/").split("/"))), path)
|
||||
|
||||
def test_the_stylesheets_urls_resolve(self):
|
||||
css_path = os.path.join(OUT, *fingerprint.url(fingerprint.STYLESHEET).lstrip("/").split("/"))
|
||||
with open(css_path, encoding="utf-8") as f:
|
||||
css = f.read()
|
||||
found = re.findall(r'url\("([^"]+)"\)', css)
|
||||
self.assertGreaterEqual(len(found), 6)
|
||||
for target in found:
|
||||
self.assertTrue(os.path.isfile(os.path.join(os.path.dirname(css_path), target)), target)
|
||||
|
||||
def headers_for(self, path):
|
||||
"""Every header a rule gives the path, as (name, rule pattern) pairs: a name twice is a header set twice."""
|
||||
found = []
|
||||
for pattern, headers in self.rules:
|
||||
if pattern.match(path):
|
||||
found += [(name.lower(), pattern.pattern) for name, _ in headers]
|
||||
return found
|
||||
|
||||
def value(self, path, header):
|
||||
out = None
|
||||
for pattern, headers in self.rules:
|
||||
if pattern.match(path):
|
||||
for name, value in headers:
|
||||
if name.lower() == header.lower():
|
||||
out = value
|
||||
return out
|
||||
|
||||
def test_the_fingerprinted_files_are_cached_for_a_year_and_never_revalidated(self):
|
||||
for path in fingerprint.FILES:
|
||||
address = fingerprint.url(path)
|
||||
self.assertEqual(self.value(address, "Cache-Control"), "public, max-age=31536000, immutable", address)
|
||||
|
||||
def test_what_is_not_fingerprinted_still_revalidates_and_html_is_never_immutable(self):
|
||||
for path in ("/assets/og.png", "/assets/map/outdoor.json", "/", "/index.html", "/trails/appalachian/"):
|
||||
value = self.value(path, "Cache-Control")
|
||||
self.assertNotIn("immutable", value or "", path)
|
||||
self.assertIn("must-revalidate", self.value("/assets/og.png", "Cache-Control"))
|
||||
self.assertIn("max-age=0", self.value("/index.html", "Cache-Control"))
|
||||
|
||||
def test_no_header_is_set_twice_for_one_path(self):
|
||||
paths = [fingerprint.url(p) for p in fingerprint.FILES] + [
|
||||
"/assets/og.png", "/assets/map/outdoor.json", "/", "/index.html", "/404.html",
|
||||
"/data/overview.geojson", "/data/trails.json", "/data/trails.csv", "/data/all-gpx.zip",
|
||||
"/trails/appalachian/", "/trails/appalachian/map.json", "/trails/appalachian/appalachian.gpx",
|
||||
"/trails/appalachian/appalachian.geojson", "/trails/appalachian/trail.toml", "/feed.xml", "/llms.txt"]
|
||||
for path in paths:
|
||||
names = [n for n, _ in self.headers_for(path)]
|
||||
self.assertEqual(len(names), len(set(names)), f"{path}: {self.headers_for(path)}")
|
||||
|
||||
def test_the_content_security_policy_stays_strict(self):
|
||||
csp = self.value("/index.html", "Content-Security-Policy")
|
||||
self.assertIn("default-src 'self'", csp)
|
||||
self.assertIn("script-src 'self';", csp)
|
||||
self.assertIn("style-src 'self';", csp)
|
||||
self.assertNotIn("unsafe-eval", csp)
|
||||
self.assertNotIn("script-src 'self' 'unsafe-inline'", csp)
|
||||
# the one policy covers the hashed files too
|
||||
self.assertEqual(self.value("/immutable/app.0123456789.js", "Content-Security-Policy"), csp)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -266,8 +266,8 @@ class ListTest(unittest.TestCase):
|
||||
self.assertFalse(browse.is_shown(76, 100))
|
||||
|
||||
def test_thin_list_is_not_shown(self):
|
||||
# three loops among twenty trails: below MIN_SIZE, so no link and no page
|
||||
recs = [fake(i, hike={"shape": "loop"} if i < 3 else {"shape": "point-to-point"}) for i in range(20)]
|
||||
# four loops among twenty trails: below MIN_SIZE, so no link and no page
|
||||
recs = [fake(i, hike={"shape": "loop"} if i < 4 else {"shape": "point-to-point"}) for i in range(20)]
|
||||
for i in range(5):
|
||||
recs[i]["tier"] = "national"
|
||||
keys = [lst.key for lst, _ in browse.shown(recs)]
|
||||
@@ -277,7 +277,7 @@ class ListTest(unittest.TestCase):
|
||||
body = home.render(recs, GH)
|
||||
self.assertNotIn('href="/lists/loops/"', body)
|
||||
self.assertIn('href="/lists/national-scenic-trails/"', body)
|
||||
recs[3]["hike"] = {"shape": "loop"}
|
||||
recs[4]["hike"] = {"shape": "loop"}
|
||||
self.assertIn("loops", [lst.key for lst, _ in browse.shown(recs)])
|
||||
|
||||
def test_rules_name_no_trail(self):
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
"""Every <img> in the built site states its size, so the page does not shift as pictures arrive,
|
||||
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
|
||||
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 home, thumbs # noqa: E402
|
||||
|
||||
OUT = os.path.join(WEB, ".cache", "test-site")
|
||||
|
||||
|
||||
class Imgs(HTMLParser):
|
||||
def __init__(self):
|
||||
super().__init__(convert_charrefs=True)
|
||||
self.imgs = []
|
||||
self.in_entries = 0
|
||||
|
||||
def handle_starttag(self, tag, attrs):
|
||||
a = dict(attrs)
|
||||
if tag == "li" and "entry" in (a.get("class") or "").split():
|
||||
self.in_entries += 1
|
||||
if tag == "img":
|
||||
a["_row"] = self.in_entries # the number (1-based) of the last list row opened: 0 before the first
|
||||
self.imgs.append(a)
|
||||
|
||||
|
||||
def page_imgs(path):
|
||||
p = Imgs()
|
||||
with open(path, encoding="utf-8") as f:
|
||||
p.feed(f.read())
|
||||
return p.imgs
|
||||
|
||||
|
||||
class SvgSizeTest(unittest.TestCase):
|
||||
def size(self, svg):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
path = os.path.join(tmp, "x.svg")
|
||||
with open(path, "w", encoding="utf-8") as f:
|
||||
f.write(svg)
|
||||
return thumbs.svg_size(path)
|
||||
|
||||
def test_the_shape_comes_from_the_view_box_and_fits_within_the_thumbnail_size(self):
|
||||
self.assertEqual(self.size('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 170 92"><g/></svg>'), (256, 139))
|
||||
self.assertEqual(self.size('<svg viewBox="17.1 25 82.1 82.1"></svg>'), (256, 256))
|
||||
self.assertEqual(self.size('<svg viewBox="0,0,100,400"></svg>'), (64, 256))
|
||||
|
||||
def test_without_a_view_box_the_width_and_height_are_used(self):
|
||||
self.assertEqual(self.size('<svg width="75.258mm" height="73.228mm"></svg>'), (256, 249))
|
||||
|
||||
def test_an_svg_with_no_size_is_an_error_not_a_guess(self):
|
||||
with self.assertRaises(ValueError):
|
||||
self.size("<svg></svg>")
|
||||
|
||||
|
||||
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)
|
||||
cls.pages = []
|
||||
for base, _, names in os.walk(OUT):
|
||||
for n in names:
|
||||
if n.endswith(".html"):
|
||||
cls.pages.append(os.path.join(base, n))
|
||||
|
||||
def test_every_img_has_a_width_and_height(self):
|
||||
seen = 0
|
||||
for page in self.pages:
|
||||
for img in page_imgs(page):
|
||||
seen += 1
|
||||
for dim in ("width", "height"):
|
||||
self.assertRegex(img.get(dim, ""), r"^[1-9][0-9]*$", f"{page}: {img}")
|
||||
self.assertGreater(seen, 1000)
|
||||
|
||||
def test_logos_are_thumbnails_never_the_full_size_file(self):
|
||||
for page in self.pages:
|
||||
for img in page_imgs(page):
|
||||
self.assertNotRegex(img.get("src", ""), r"/shield\.(svg|png)$", page)
|
||||
|
||||
def test_an_svg_logo_has_a_thumbnail_the_size_of_the_file(self):
|
||||
found = 0
|
||||
for tid in ("bartram", "appalachian", "long-trail"):
|
||||
img = [i for i in page_imgs(os.path.join(OUT, "trails", tid, "index.html"))
|
||||
if i.get("src") == f"/trails/{tid}/{thumbs.THUMB_NAME}"]
|
||||
self.assertEqual(len(img), 1, tid)
|
||||
w, h = thumbs.png_size(os.path.join(OUT, "trails", tid, thumbs.THUMB_NAME))
|
||||
self.assertEqual((img[0]["width"], img[0]["height"]), (str(w), str(h)), tid)
|
||||
found += 1
|
||||
self.assertEqual(found, 3)
|
||||
|
||||
def test_the_first_rows_of_a_list_are_eager_and_the_rest_are_lazy(self):
|
||||
for rel in ("index.html", os.path.join("lists", "under-100-miles", "index.html")):
|
||||
logos = [i for i in page_imgs(os.path.join(OUT, rel))
|
||||
if i["_row"] and i.get("src", "").endswith(thumbs.THUMB_NAME)]
|
||||
self.assertGreater(len(logos), home.EAGER_ROWS + 2, rel)
|
||||
for img in logos:
|
||||
if img["_row"] <= home.EAGER_ROWS:
|
||||
self.assertNotIn("loading", img, f"{rel} row {img['_row']}")
|
||||
else:
|
||||
self.assertEqual(img.get("loading"), "lazy", f"{rel} row {img['_row']}")
|
||||
|
||||
def test_the_saved_page_loads_no_logo_for_its_hidden_rows_and_the_record_logo_is_eager(self):
|
||||
for img in page_imgs(os.path.join(OUT, "saved", "index.html")):
|
||||
if img["_row"] and img.get("src", "").endswith(thumbs.THUMB_NAME):
|
||||
self.assertEqual(img.get("loading"), "lazy")
|
||||
header = [i for i in page_imgs(os.path.join(OUT, "trails", "appalachian", "index.html"))
|
||||
if i.get("src", "").endswith(thumbs.THUMB_NAME)]
|
||||
self.assertTrue(header)
|
||||
self.assertNotIn("loading", header[0])
|
||||
self.assertTrue(re.match(r"^/trails/appalachian/", header[0]["src"]))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,56 @@
|
||||
"""The maps start late: nothing for a map (MapLibre, its style, the contour add-on, the track
|
||||
data) loads with the page. These pin the script's promises (the script has no unit tests; the
|
||||
behaviour was checked by driving the pages in a browser)."""
|
||||
import os
|
||||
import re
|
||||
import unittest
|
||||
|
||||
WEB = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
|
||||
def read(*parts):
|
||||
with open(os.path.join(WEB, *parts), encoding="utf-8") as f:
|
||||
return f.read()
|
||||
|
||||
|
||||
class MapStartTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.js = read("assets", "app.js")
|
||||
|
||||
def test_one_function_starts_a_map_and_it_is_the_only_caller_of_the_fetch_and_the_loader(self):
|
||||
self.assertEqual(self.js.count("fetchData()"), 2) # its definition and the one call
|
||||
self.assertEqual(self.js.count("loadLibraries()"), 2)
|
||||
begin = re.search(r"function begin\(\) \{(.*?)\n \}\n", self.js, re.S)
|
||||
self.assertIsNotNone(begin)
|
||||
self.assertIn("dataReady = fetchData();", begin.group(1))
|
||||
self.assertIn("loadLibraries().then(startMapLibre);", begin.group(1))
|
||||
self.assertIn("if (outdoorUrl) fetchOutdoor(outdoorUrl);", begin.group(1))
|
||||
self.assertEqual(self.js.count("fetchOutdoor(outdoorUrl)"), 2) # begin() and startMapLibre(), once started
|
||||
|
||||
def test_a_map_starts_when_near_the_screen_or_touched_never_at_once(self):
|
||||
self.assertIn("new IntersectionObserver(", self.js)
|
||||
self.assertIn("afterLoad(begin);", self.js) # near the screen, and the page has loaded
|
||||
for event in ("pointerdown", "focusin", "keydown"):
|
||||
self.assertIn(f"'{event}'", self.js)
|
||||
self.assertNotIn("startMaps", self.js)
|
||||
self.assertNotRegex(self.js, r"initMap\(fig\)[^}]*\n\s*(fetch|loadLibraries)")
|
||||
|
||||
def test_the_libraries_come_from_the_addresses_on_the_scripts_own_tag(self):
|
||||
self.assertIn("var SCRIPT = document.currentScript;", self.js)
|
||||
for attr in ("maplibreCss", "maplibreJs", "contourJs"):
|
||||
self.assertIn(f"d.{attr}", self.js)
|
||||
|
||||
def test_maplibres_stylesheet_goes_before_the_sites_so_the_sites_frame_rules_win(self):
|
||||
# MapLibre's .maplibregl-map sets position: relative; the site's .map__canvas needs absolute.
|
||||
self.assertIn("document.head.querySelector('link[rel=\"stylesheet\"]')", self.js)
|
||||
self.assertIn("document.head.insertBefore(el, before || null);", self.js)
|
||||
# the page runs the scripts in order: the add-on needs MapLibre first
|
||||
self.assertIn("script.async = false;", self.js)
|
||||
|
||||
def test_until_it_starts_the_frame_says_what_happens_and_the_page_text_stays_for_no_script(self):
|
||||
self.assertIn("'The map loads when you scroll to it.'", self.js)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -164,25 +164,28 @@ class OutdoorPagesTest(unittest.TestCase):
|
||||
cls.records = records.load_records(ROOT)
|
||||
|
||||
def test_trail_maps_are_outdoor_and_load_the_add_on(self):
|
||||
contour = f'<script src="{layout.CONTOUR_JS}" defer></script>'
|
||||
maplibre = f'<script src="{layout.MAPLIBRE_JS}" defer></script>'
|
||||
# The page names the add-on (and MapLibre) on app.js's own tag; app.js loads them when the
|
||||
# map starts, MapLibre first (test_map_start). No page loads either with its own tag.
|
||||
from olt import fingerprint
|
||||
contour = f'data-contour-js="{fingerprint.url(layout.CONTOUR_JS)}"'
|
||||
with_map = 0
|
||||
for rec in self.records:
|
||||
page = read(OUT, "trails", rec["id"], "index.html")
|
||||
figures = re.findall(r'<figure class="mapfig[^"]*"[^>]*>', page)
|
||||
mapped = [f for f in figures if 'data-map="' in f]
|
||||
self.assertNotIn("maplibre", re.sub(r'<script src="/immutable/app[^>]*>', "", page), rec["id"])
|
||||
if mapped:
|
||||
with_map += 1
|
||||
for fig in mapped:
|
||||
self.assertIn(f'data-outdoor="{layout.OUTDOOR_STYLE}"', fig, rec["id"])
|
||||
self.assertEqual(page.count(contour), 1, rec["id"])
|
||||
self.assertLess(page.index(maplibre), page.index(contour), rec["id"])
|
||||
self.assertEqual(page.count(f'data-maplibre-js="{fingerprint.url(layout.MAPLIBRE_JS)}"'), 1, rec["id"])
|
||||
else:
|
||||
self.assertNotIn(contour, page, rec["id"])
|
||||
self.assertNotIn("data-contour-js", page, rec["id"])
|
||||
self.assertNotIn("data-outdoor", page, rec["id"])
|
||||
self.assertGreater(with_map, 100)
|
||||
self.assertTrue(os.path.isfile(os.path.join(OUT, *layout.OUTDOOR_STYLE.strip("/").split("/"))))
|
||||
self.assertTrue(os.path.isfile(os.path.join(OUT, *layout.CONTOUR_JS.strip("/").split("/"))))
|
||||
self.assertTrue(os.path.isfile(os.path.join(OUT, *fingerprint.url(layout.CONTOUR_JS).strip("/").split("/"))))
|
||||
|
||||
def test_overview_maps_stay_plain(self):
|
||||
paths = ["index.html", os.path.join("routes", "index.html"), os.path.join("lists", "index.html")]
|
||||
|
||||
+14
-5
@@ -330,11 +330,18 @@ class BuiltSiteTest(unittest.TestCase):
|
||||
for th in re.findall(r"<th\b[^>]*>", head):
|
||||
self.assertIn('scope="col"', th, path)
|
||||
|
||||
def test_app_script_loads_before_maplibre(self):
|
||||
def test_maplibre_is_not_loaded_with_the_page(self):
|
||||
# app.js loads MapLibre when the map scrolls into view or is touched, from the
|
||||
# addresses on its own tag (layout.py); the page itself names no MapLibre file.
|
||||
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)
|
||||
tag = re.search(r'<script src="/immutable/app\.[0-9a-f]{10}\.js" defer ([^>]*)></script>', doc)
|
||||
self.assertIsNotNone(tag)
|
||||
self.assertRegex(tag.group(1), r'data-maplibre-js="/immutable/maplibre-gl\.[0-9a-f]{10}\.js"')
|
||||
self.assertRegex(tag.group(1), r'data-maplibre-css="/immutable/maplibre-gl\.[0-9a-f]{10}\.css"')
|
||||
self.assertNotRegex(doc, r'<link[^>]*maplibre')
|
||||
self.assertNotRegex(doc, r'<script src="[^"]*maplibre')
|
||||
self.assertNotIn("data-contour-js", tag.group(1))
|
||||
|
||||
def test_not_found_page_has_a_search_form(self):
|
||||
with open(os.path.join(OUT, "404.html"), encoding="utf-8") as f:
|
||||
@@ -550,8 +557,10 @@ class RenderUnitTest(unittest.TestCase):
|
||||
rec = sample_record(name="A & B")
|
||||
n = pages.render_site([rec], out, repo, site=site.Site("N", "T"))
|
||||
# trail page + home + 404 + places hub + 1 place + lists hub + routes,
|
||||
# sources, logos, about, data, schema, changelog, left out, saved (no list holds MIN_SIZE trails)
|
||||
self.assertEqual(n, 15)
|
||||
# sources, logos, about, data, schema, changelog, left out, saved (no list holds MIN_SIZE trails),
|
||||
# and the two reference pages, the glossary and the method (the tables, authors, recent and
|
||||
# linked-trails pages need at least MIN_SIZE trails and are not built for one)
|
||||
self.assertEqual(n, 17)
|
||||
with open(os.path.join(out, "trails", "x", "index.html"), encoding="utf-8") as f:
|
||||
self.assertIn("A & B", f.read())
|
||||
with open(os.path.join(out, "index.html"), encoding="utf-8") as f:
|
||||
|
||||
@@ -46,14 +46,14 @@ def levels(html_text):
|
||||
|
||||
class TrailTitleTest(unittest.TestCase):
|
||||
def test_common_name_abbreviation_miles_and_what_the_page_offers(self):
|
||||
self.assertEqual(trail.page_title(at(), S), "Appalachian Trail (AT): 2,198 miles, map and GPX")
|
||||
self.assertEqual(trail.page_title(at(), S), "Appalachian Trail (AT): 2,198 miles (3,537 km), map and GPX")
|
||||
|
||||
def test_the_record_name_is_used_where_there_is_no_common_name(self):
|
||||
rec = gpx(fake(1, km=160))
|
||||
rec["name"] = "Hoosier Heritage Trail"
|
||||
del rec["short_name"]
|
||||
rec["derived"]["length_mi"] = 99
|
||||
self.assertEqual(trail.page_title(rec, S), "Hoosier Heritage Trail: 99 miles, map and GPX")
|
||||
self.assertEqual(trail.page_title(rec, S), "Hoosier Heritage Trail: 99 miles (160 km), map and GPX")
|
||||
|
||||
def test_gpx_and_map_only_where_the_page_has_them(self):
|
||||
rec = at()
|
||||
@@ -71,10 +71,10 @@ class TrailTitleTest(unittest.TestCase):
|
||||
rec["kind"] = "route"
|
||||
rec["route"] = {"creator": "Steve Roper", "line_policy": "sold"}
|
||||
title = trail.page_title(rec, S)
|
||||
self.assertEqual(title, "Sierra High Route (SHR): 195-mile route")
|
||||
self.assertEqual(title, "Sierra High Route (SHR): 195-mile route by Steve Roper")
|
||||
self.assertNotIn("GPX", title)
|
||||
rec["name"], rec["short_name"] = "Tiny", "T"
|
||||
self.assertEqual(trail.page_title(rec, S), "Tiny (T): 195-mile route by Steve Roper")
|
||||
rec["name"], rec["short_name"] = "A Route With A Rather Long Name", "RWLN"
|
||||
self.assertEqual(trail.page_title(rec, S), "A Route With A Rather Long Name (RWLN): 195-mile route")
|
||||
|
||||
def test_pieces_go_in_a_stated_order_and_the_length_stays(self):
|
||||
rec = at()
|
||||
@@ -84,9 +84,9 @@ class TrailTitleTest(unittest.TestCase):
|
||||
title = trail.page_title(rec, S)
|
||||
self.assertLessEqual(len(title), ROOM)
|
||||
self.assertIn("2,198 miles", title)
|
||||
rec["common_name"] = "A Very Long Name For A Trail That Goes On And On"
|
||||
rec["common_name"] = "A Very Long Name For A Trail That Goes On"
|
||||
title = trail.page_title(rec, S)
|
||||
self.assertEqual(title, "A Very Long Name For A Trail That Goes On And On: 2,198 miles")
|
||||
self.assertEqual(title, "A Very Long Name For A Trail That Goes On: 2,198 miles, GPX")
|
||||
|
||||
def test_kilometres_follow_only_where_there_is_room(self):
|
||||
rec = gpx(fake(1, km=80))
|
||||
@@ -97,7 +97,7 @@ class TrailTitleTest(unittest.TestCase):
|
||||
def test_the_page_carries_the_title_and_the_common_name_in_its_heading(self):
|
||||
rec = at()
|
||||
title, description, body, _ = trail.render(rec, S)
|
||||
self.assertEqual(title, "Appalachian Trail (AT): 2,198 miles, map and GPX")
|
||||
self.assertEqual(title, "Appalachian Trail (AT): 2,198 miles (3,537 km), map and GPX")
|
||||
self.assertIn('<h1>Appalachian Trail <span class="titleblock__abbr">AT</span></h1>', body)
|
||||
self.assertIn("Full name: Appalachian National Scenic Trail", body)
|
||||
self.assertIn("Common name", body)
|
||||
@@ -161,7 +161,7 @@ class PlaceAndListTitleTest(unittest.TestCase):
|
||||
r["id"], r["name"] = f"n{i}", f"Trail {i}"
|
||||
recs[0]["derived"]["kind"] = recs[0]["kind"] = "route"
|
||||
title = regions.region_page("ca-nl", recs, S)[0]
|
||||
self.assertLessEqual(len(title) + len(" · Long Hikes"), common.TITLE_LIMIT)
|
||||
self.assertLessEqual(len(title), common.TITLE_LIMIT)
|
||||
self.assertTrue(title.startswith("Long Trails in Newfoundland and Labrador"))
|
||||
|
||||
def test_a_place_with_one_trail(self):
|
||||
@@ -187,7 +187,11 @@ class PlaceAndListTitleTest(unittest.TestCase):
|
||||
|
||||
def test_the_home_page_has_its_own_title_and_description(self):
|
||||
page = layout.layout("", "<h1>x</h1>", path="/", site=S, description=home.description(self.recs))
|
||||
self.assertIn("<title>Long-Distance Hiking Trails of the US and Canada · Long Hikes</title>", page)
|
||||
# 48 + " · Long Hikes" is 61 characters: the site name is dropped from <title>, and the
|
||||
# share titles never carry it.
|
||||
self.assertIn("<title>Long-Distance Hiking Trails of the US and Canada</title>", page)
|
||||
self.assertIn('<meta property="og:title" content="Long-Distance Hiking Trails of the US and Canada">', page)
|
||||
self.assertIn('<meta name="twitter:title" content="Long-Distance Hiking Trails of the US and Canada">', page)
|
||||
self.assertNotIn("A tagline", page.split("</head>")[0].split('name="description"')[1].split(">")[0])
|
||||
self.assertLessEqual(len(home.description(self.recs)), common.DESCRIPTION_LIMIT)
|
||||
self.assertIn("6 long-distance hiking trails and routes", home.description(self.recs))
|
||||
@@ -195,6 +199,63 @@ class PlaceAndListTitleTest(unittest.TestCase):
|
||||
self.assertIn("<title>N: Tag</title>", bare)
|
||||
|
||||
|
||||
class TitleAndShareTextTest(unittest.TestCase):
|
||||
def head(self, title, description="Short."):
|
||||
return layout.layout(title, "<h1>x</h1>", path="/x/", site=S, description=description).split("</head>")[0]
|
||||
|
||||
def test_the_site_name_is_kept_in_title_only_where_the_whole_is_60_or_fewer(self):
|
||||
fits = "T" * (60 - len(" · Long Hikes"))
|
||||
head = self.head(fits)
|
||||
self.assertIn(f"<title>{fits} · Long Hikes</title>", head)
|
||||
over = "T" * (60 - len(" · Long Hikes") + 1)
|
||||
self.assertIn(f"<title>{over}</title>", self.head(over))
|
||||
|
||||
def test_share_titles_never_carry_the_site_name(self):
|
||||
for title in ("Short", "T" * 47, "T" * 70):
|
||||
head = self.head(title)
|
||||
self.assertIn(f'<meta property="og:title" content="{title}">', head)
|
||||
self.assertIn(f'<meta name="twitter:title" content="{title}">', head)
|
||||
|
||||
def test_a_title_that_only_its_name_makes_long_is_not_cut(self):
|
||||
rec = at()
|
||||
rec["common_name"] = rec["name"] = "N" * 58
|
||||
rec["short_name"] = ""
|
||||
self.assertEqual(trail.page_title(rec, S), "N" * 58) # the name fits, the length does not
|
||||
rec["common_name"] = rec["name"] = "N" * 70
|
||||
self.assertEqual(trail.page_title(rec, S), "N" * 70 + f": {rec['derived']['length_mi']:,} miles")
|
||||
|
||||
def test_share_description_is_at_most_125_and_cut_at_a_sentence_or_word(self):
|
||||
self.assertEqual(common.share_description("A short one."), "A short one.")
|
||||
text = ("A trail of 2,198 miles (3,537 km) across 14 states, usually 5 to 7 months. "
|
||||
"It follows the crest of the Appalachian Mountains from Georgia to Maine and is the longest.")
|
||||
got = common.share_description(text)
|
||||
self.assertEqual(got, "A trail of 2,198 miles (3,537 km) across 14 states, usually 5 to 7 months.")
|
||||
words = ("A trail of 2,198 miles (3,537 km) across 14 states, usually 5 to 7 months and "
|
||||
"following the crest of the Appalachian Mountains from Georgia to Maine, and more")
|
||||
got = common.share_description(words)
|
||||
self.assertLessEqual(len(got), 125)
|
||||
self.assertTrue(got.endswith("\u2026"))
|
||||
self.assertTrue(words.startswith(got[:-1]))
|
||||
self.assertIsNone(re.search(r"(,|\b(and|or|but|with|to|of|the|in))\u2026$", got), got)
|
||||
for limit in range(40, 125):
|
||||
cut = common.share_description(words, limit)
|
||||
self.assertLessEqual(len(cut), limit)
|
||||
self.assertIsNone(re.search(r"([,;:]|\b(and|or|but|with|to|of|the|a|in|by|from))\u2026?$", cut), cut)
|
||||
|
||||
def test_the_search_description_is_unchanged_and_the_share_one_is_cut_from_it(self):
|
||||
desc = ("A trail of 2,198 miles (3,537 km) across 14 states, usually 5 to 7 months. "
|
||||
"It follows the crest of the Appalachian Mountains from Georgia to Maine, the longest in the country.")
|
||||
head = self.head("T", desc)
|
||||
self.assertIn(f'<meta name="description" content="{desc}">', head)
|
||||
self.assertIn('<meta property="og:description" content="A trail of 2,198 miles (3,537 km) across 14 states, usually 5 to 7 months.">', head)
|
||||
self.assertIn('<meta name="twitter:description" content="A trail of 2,198 miles (3,537 km) across 14 states, usually 5 to 7 months.">', head)
|
||||
|
||||
def test_the_footer_links_the_glossary_the_method_and_the_authors(self):
|
||||
foot = layout.footer(S)
|
||||
for href in ("/glossary/", "/method/", "/authors/"):
|
||||
self.assertEqual(foot.count(f'href="{href}"'), 1, href)
|
||||
|
||||
|
||||
class HeadingOrderTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.recs = [fake(i, km=100 + 50 * i, regions=["CO"]) for i in range(1, 6)]
|
||||
|
||||
@@ -132,10 +132,14 @@ class SortKeysTest(unittest.TestCase):
|
||||
|
||||
|
||||
class ListDefaultsTest(unittest.TestCase):
|
||||
def test_only_four_lists_open_in_another_order(self):
|
||||
def test_only_the_lists_defined_by_an_order_open_in_another(self):
|
||||
# the length bands open longest first, the shortest bands and the time lists in their own order
|
||||
special = {lst.key: lst.sort for lst in browse.LISTS if lst.sort != "name"}
|
||||
self.assertEqual(special, {"longest": "length-desc", "under-100-miles": "length-asc",
|
||||
"a-week-or-less": "time-asc", "one-to-two-weeks": "time-asc"})
|
||||
self.assertEqual(special, {
|
||||
"longest": "length-desc", "500-to-1000-miles": "length-desc", "200-to-500-miles": "length-desc",
|
||||
"100-to-200-miles": "length-desc", "under-100-miles": "length-asc", "under-200-miles": "length-asc",
|
||||
"weekend": "time-asc", "a-week-or-less": "time-asc", "one-to-two-weeks": "time-asc",
|
||||
"two-to-four-weeks": "time-asc", "a-month-or-more": "time-asc"})
|
||||
for lst in browse.LISTS:
|
||||
self.assertIn(lst.sort, facets.SORT_LABEL, lst.key)
|
||||
self.assertFalse(hasattr(lst, "order"), lst.key)
|
||||
|
||||
@@ -196,7 +196,7 @@ class JsonLdTest(unittest.TestCase):
|
||||
self.assertEqual(place["url"], f"{BASE}/trails/{rec['id']}/")
|
||||
page = next(n for n in nodes if n["@type"] == "ItemPage")
|
||||
self.assertEqual(page["mainEntity"]["@id"], place["@id"])
|
||||
self.assertEqual(page["dateModified"], seo.modified(rec))
|
||||
self.assertEqual(page["dateModified"], seo.checked(rec))
|
||||
self.assertRegex(page["dateModified"], r"^\d{4}-\d{2}-\d{2}$")
|
||||
count += 1
|
||||
self.assertEqual(count, len(self.records))
|
||||
@@ -285,7 +285,7 @@ class JsonLdTest(unittest.TestCase):
|
||||
self.assertTrue(os.path.isfile(os.path.join(OUT, "assets", "apple-touch-icon.png")))
|
||||
# only what site.toml holds: the repository, and a contact when one is set
|
||||
self.assertEqual(org.get("sameAs", []), [SITE.repo_url] if SITE.repo_url else [])
|
||||
self.assertEqual("email" in org or "contactPoint" in org, bool(SITE.contact_url))
|
||||
self.assertEqual("email" in org or "contactPoint" in org, bool(SITE.contact))
|
||||
web = next(n for n in home if n["@type"] == "WebSite")
|
||||
self.assertEqual(web["publisher"], {"@id": org["@id"]})
|
||||
data = nodes_of(self.pages["data/index.html"])
|
||||
@@ -303,7 +303,9 @@ class JsonLdTest(unittest.TestCase):
|
||||
self.assertTrue(os.path.isfile(os.path.join(OUT, *path.split("/"))), path)
|
||||
self.assertTrue(all("name" in v for v in ds["variableMeasured"]))
|
||||
self.assertIn("United States", ds["description"])
|
||||
self.assertEqual(ds["creator"]["name"], SITE.name)
|
||||
# one maintainer, named by name and profile page: the Person is the creator, the site the publisher
|
||||
self.assertEqual(ds["creator"]["name"], SITE.maintainer_name or SITE.name)
|
||||
self.assertEqual(ds["publisher"]["name"], SITE.name)
|
||||
|
||||
def test_no_wording_the_house_style_forbids(self):
|
||||
for path in ("data/index.html", "index.html", "trails/long-trail/index.html"):
|
||||
@@ -347,6 +349,15 @@ class CardsTest(unittest.TestCase):
|
||||
stored = cards.stored_fingerprint(os.path.join(WEB, "cards", f"{rec['id']}.png"))
|
||||
self.assertEqual(stored, cards.fingerprint(rec), f"{rec['id']}: card is stale")
|
||||
|
||||
def test_site_card_is_not_stale(self):
|
||||
"""assets/og.png shows the site name and tagline from web/site.toml. A changed setting
|
||||
fails here until web/tools/make_cards.py has redrawn it."""
|
||||
cfg = site.from_file(os.path.join(WEB, "site.toml"))
|
||||
self.assertEqual(cards.stored_fingerprint(os.path.join(WEB, "assets", "og.png")),
|
||||
cards.site_fingerprint(cfg), "assets/og.png is stale")
|
||||
self.assertEqual(thumbs.png_size(os.path.join(WEB, "assets", "og.png")), (1200, 630))
|
||||
self.assertEqual(meta(read("index.html"), "og:image"), f"{BASE}/assets/og.png")
|
||||
|
||||
def test_no_card_for_a_record_that_is_gone(self):
|
||||
ids = {r["id"] for r in self.records}
|
||||
cards = {n[:-4] for n in os.listdir(os.path.join(WEB, "cards")) if n.endswith(".png")}
|
||||
|
||||
@@ -53,14 +53,24 @@ def repository_png_logos():
|
||||
return found
|
||||
|
||||
|
||||
def repository_logos():
|
||||
"""{id: path} for each logo with a thumbnail: <id>/shield.png, or <id>/shield.svg where there is no PNG."""
|
||||
found = dict(repository_png_logos())
|
||||
for name in os.listdir(ROOT):
|
||||
path = os.path.join(ROOT, name, "shield.svg")
|
||||
if not name.startswith((".", "_")) and name not in found 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()
|
||||
def test_every_repository_logo_has_a_thumbnail_no_larger_than_256(self):
|
||||
logos = repository_logos()
|
||||
self.assertTrue(logos)
|
||||
for tid in logos:
|
||||
thumb = os.path.join(WEB, "thumbs", f"{tid}.png")
|
||||
@@ -71,7 +81,7 @@ class ThumbFilesTest(unittest.TestCase):
|
||||
self.assertGreater(min(w, h), 0, tid)
|
||||
|
||||
def test_no_thumbnail_without_a_source(self):
|
||||
logos = repository_png_logos()
|
||||
logos = repository_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}")
|
||||
@@ -96,8 +106,39 @@ class ThumbFilesTest(unittest.TestCase):
|
||||
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"}}}
|
||||
def test_svg_logo_gets_a_thumbnail_like_a_png_one(self):
|
||||
tid = "x"
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
repo, out, made = (os.path.join(tmp, n) for n in ("repo", "out", "thumbs"))
|
||||
for d in (os.path.join(repo, tid), os.path.join(out, "trails", tid), made):
|
||||
os.makedirs(d)
|
||||
with open(os.path.join(repo, tid, "shield.svg"), "w", encoding="utf-8") as f:
|
||||
f.write('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 170 92"></svg>')
|
||||
shutil.copyfile(repository_png_logos()["cohos"], os.path.join(made, f"{tid}.png"))
|
||||
rec = {"id": tid, "derived": {"files": {"shield": f"{tid}/shield.svg"}, "logo_img": {"src": "stale"}}}
|
||||
thumbs.prepare(rec, out, repo, thumb_dir=made)
|
||||
logo = rec["derived"]["logo_img"]
|
||||
self.assertEqual(logo["src"], f"/trails/{tid}/{thumbs.THUMB_NAME}")
|
||||
self.assertEqual((logo["width"], logo["height"]), thumbs.png_size(os.path.join(made, f"{tid}.png")))
|
||||
self.assertTrue(os.path.isfile(os.path.join(out, "trails", tid, thumbs.THUMB_NAME)))
|
||||
|
||||
def test_svg_logo_with_no_thumbnail_falls_back_to_the_svg_with_its_own_shape(self):
|
||||
tid = "x"
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
repo, out, empty = (os.path.join(tmp, n) for n in ("repo", "out", "thumbs"))
|
||||
for d in (os.path.join(repo, tid), os.path.join(out, "trails", tid), empty):
|
||||
os.makedirs(d)
|
||||
with open(os.path.join(repo, tid, "shield.svg"), "w", encoding="utf-8") as f:
|
||||
f.write('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 170 92"></svg>')
|
||||
rec = {"id": tid, "derived": {"files": {"shield": f"{tid}/shield.svg"}}}
|
||||
err = io.StringIO()
|
||||
with contextlib.redirect_stderr(err):
|
||||
thumbs.prepare(rec, out, repo, thumb_dir=empty)
|
||||
self.assertEqual(err.getvalue().count("warning"), 1)
|
||||
self.assertEqual(rec["derived"]["logo_img"], {"src": f"/trails/{tid}/shield.svg", "width": 256, "height": 139})
|
||||
|
||||
def test_a_logo_of_another_type_gets_no_thumbnail(self):
|
||||
rec = {"id": "x", "derived": {"files": {"shield": "x/shield.gif"}, "logo_img": {"src": "stale"}}}
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
thumbs.prepare(rec, tmp, tmp, thumb_dir=tmp)
|
||||
self.assertNotIn("logo_img", rec["derived"])
|
||||
|
||||
@@ -0,0 +1,257 @@
|
||||
"""Tests for who the site says maintains it, when each trail was last checked, and the generated
|
||||
"In brief" paragraph at the top of every trail page.
|
||||
|
||||
Records come from the repository, so the paragraph is checked against what a record really holds;
|
||||
a sparse record is built here. The site is not built: pages are rendered one record at a time.
|
||||
"""
|
||||
import copy
|
||||
import html
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
WEB = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
ROOT = os.path.dirname(WEB)
|
||||
sys.path.insert(0, WEB)
|
||||
|
||||
from olt import common, docs, hike, records, seo, site, trail # noqa: E402
|
||||
|
||||
SITE = site.load()
|
||||
|
||||
|
||||
def load(tid):
|
||||
rec = records.load_record(ROOT, tid)
|
||||
if tid in SITE.name_lang:
|
||||
rec["derived"]["name_lang"] = SITE.name_lang[tid]
|
||||
return rec
|
||||
|
||||
|
||||
def text_of(fragment):
|
||||
return html.unescape(re.sub(r"<[^>]+>", "", str(fragment)))
|
||||
|
||||
|
||||
def sparse_record():
|
||||
"""A record with no [hike] table: a name, a length, a place and a source."""
|
||||
return {
|
||||
"id": "sparse", "name": "Sparse Trail", "country": "US", "regions": ["AZ"], "length_km": 100,
|
||||
"length_note": "", "tier": "regional", "designation": "A & B Association", "wave": 1,
|
||||
"source": {"status": "none", "publisher": "P", "url": "https://example.org/", "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": "None."},
|
||||
"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": []},
|
||||
}
|
||||
|
||||
|
||||
class MaintainerSettings(unittest.TestCase):
|
||||
def test_site_toml_names_the_maintainer_and_nothing_personal(self):
|
||||
self.assertEqual(SITE.maintainer_name, "Stephen Waits")
|
||||
self.assertEqual(SITE.maintainer_url, "https://github.com/swaits")
|
||||
with open(site.SITE_TOML, encoding="utf-8") as f:
|
||||
text = f.read()
|
||||
self.assertNotIn("@", re.sub(r"#.*", "", text), "no email address in the settings")
|
||||
|
||||
def test_contact_is_the_issue_chooser(self):
|
||||
self.assertEqual(SITE.issue_chooser_url, SITE.repo_url + "/issues/new/choose")
|
||||
self.assertEqual(SITE.contact, SITE.issue_chooser_url)
|
||||
owner = site.Site("N", "T", repo_url="https://github.com/o/r", contact_url="https://example.org/contact")
|
||||
self.assertEqual(owner.contact, "https://example.org/contact")
|
||||
elsewhere = site.Site("N", "T", repo_url="https://git.example.org/o/r")
|
||||
self.assertEqual(elsewhere.issue_chooser_url, "")
|
||||
self.assertEqual(elsewhere.contact, "")
|
||||
|
||||
def test_about_section_comes_from_the_settings(self):
|
||||
body = str(docs.about_page([load("appalachian")], SITE, ROOT)[2])
|
||||
self.assertIn('<h2 id="who-maintains">Who maintains this</h2>', body)
|
||||
self.assertIn(f'<a href="{SITE.maintainer_url}">{SITE.maintainer_name}</a>', body)
|
||||
self.assertIn(f'<a href="{SITE.issue_chooser_url}">open an issue on GitHub</a>', body)
|
||||
section = body[body.index('id="who-maintains"'):]
|
||||
section = section[:section.index("</section>")]
|
||||
for claim in ("public domain", "names the page it was read on", "no ads, no accounts, no tracking and no analytics"):
|
||||
self.assertIn(claim, section)
|
||||
self.assertNotRegex(section, r"[\w.]+@[\w.]+", "no email address")
|
||||
|
||||
def test_no_maintainer_no_section_and_no_person(self):
|
||||
bare = site.Site("N", "T", base_url="https://example.org", repo_url="https://github.com/o/r")
|
||||
self.assertEqual(docs.maintainer_section(bare), "")
|
||||
self.assertEqual(seo.person_node(bare), {})
|
||||
self.assertNotIn("founder", seo.organization_node(bare))
|
||||
|
||||
def test_structured_data_names_the_maintainer_by_profile(self):
|
||||
person = seo.person_node(SITE)
|
||||
self.assertEqual(person["@type"], "Person")
|
||||
self.assertEqual(person["name"], SITE.maintainer_name)
|
||||
self.assertEqual(person["sameAs"], [SITE.maintainer_url])
|
||||
self.assertNotIn("email", json.dumps(person))
|
||||
org = next(n for n in seo.home_jsonld(SITE) if n["@type"] == "Organization")
|
||||
self.assertEqual(org["founder"], person)
|
||||
self.assertEqual(org["contactPoint"]["url"], SITE.issue_chooser_url)
|
||||
data = seo.dataset_jsonld([load("appalachian")], SITE, version="2026-11-16")
|
||||
self.assertEqual(data["creator"], person)
|
||||
self.assertEqual(data["maintainer"], person)
|
||||
self.assertEqual(data["publisher"]["@type"], "Organization")
|
||||
self.assertNotRegex(json.dumps([org, data]), r"[\w.+-]+@[\w-]+\.[\w.]+", "no email address")
|
||||
|
||||
|
||||
class LastChecked(unittest.TestCase):
|
||||
def test_shown_date_is_the_records_newest_check_and_equals_date_modified(self):
|
||||
for tid in ("appalachian", "timberline", "circle-of-solitude"):
|
||||
rec = load(tid)
|
||||
body = str(trail.render(rec, SITE, [rec])[2])
|
||||
shown = re.search(r'Last checked <time datetime="(\d{4}-\d{2}-\d{2})">(\d{4}-\d{2}-\d{2})</time>', body)
|
||||
self.assertTrue(shown, tid)
|
||||
self.assertEqual(shown.group(1), shown.group(2))
|
||||
checks = [rec.get("verification", {}).get("date"), hike.table(rec).get("checked"),
|
||||
rec["source"].get("source_checked")]
|
||||
self.assertEqual(shown.group(1), max(str(c) for c in checks if c))
|
||||
page = seo.trail_jsonld(rec, SITE, title="t", description="d")[0]
|
||||
self.assertEqual(page["dateModified"], shown.group(1))
|
||||
|
||||
def test_a_history_entry_is_not_a_check(self):
|
||||
rec = load("appalachian")
|
||||
rec["history"] = [{"date": "2099-01-01", "change": "x", "fields": [], "asked_by": "x"}]
|
||||
self.assertNotEqual(seo.checked(rec), "2099-01-01")
|
||||
self.assertEqual(seo.modified(rec), "2099-01-01")
|
||||
|
||||
def test_no_date_no_line(self):
|
||||
rec = sparse_record()
|
||||
del rec["source"]["source_checked"]
|
||||
self.assertEqual(seo.checked(rec), "")
|
||||
self.assertEqual(str(trail.checked_line(rec)), "")
|
||||
|
||||
|
||||
class InBrief(unittest.TestCase):
|
||||
def sentences(self, rec):
|
||||
return [text_of(s) for s in trail.brief_sentences(rec)]
|
||||
|
||||
def test_full_record(self):
|
||||
rec = load("appalachian")
|
||||
s = self.sentences(rec)
|
||||
self.assertEqual(s[0], "The Appalachian Trail is a 2,198-mile (3,537 km) National Scenic Trail, designated in 1968, "
|
||||
"through forest and alpine country across 14 states of the United States.")
|
||||
self.assertEqual(s[1], "It runs from Springer Mountain, Georgia, to Katahdin, Maine, and walking all of it "
|
||||
"usually takes 5 to 7 months.")
|
||||
self.assertEqual(s[2], "Its highest point is Kuwohi (Clingmans Dome), at 6,624 ft (2,019 m), and the track climbs "
|
||||
"466,594 ft (142,218 m) in total, computed from the track.")
|
||||
self.assertEqual(s[3], "Northbound hikes start late February to early April, and this page has a GPX "
|
||||
"of the track to download.")
|
||||
self.assertEqual(len(s), 4)
|
||||
|
||||
def test_season_is_said_as_a_sentence_that_fits_the_field(self):
|
||||
def season(text):
|
||||
rec = sparse_record()
|
||||
rec["hike"] = {"season": text}
|
||||
return trail.season_sentence(rec)
|
||||
self.assertEqual(season("May to July"), ("range", "The usual season is May to July"))
|
||||
self.assertEqual(season("Spring and fall"), ("range", "The usual season is spring and fall"))
|
||||
self.assertEqual(season("Late July through September"), ("range", "The usual season is late July through September"))
|
||||
self.assertEqual(season("All year"), ("sentence", "It can be walked all year"))
|
||||
self.assertEqual(season("Northbound hikes start late February to early April"),
|
||||
("sentence", "Northbound hikes start late February to early April"))
|
||||
# a range with a note after it keeps the range; a long note with nothing to cut at is left to "At a glance"
|
||||
self.assertEqual(season("Spring and fall; summers tend to be humid and buggy"),
|
||||
("range", "The usual season is spring and fall"))
|
||||
self.assertIsNone(season("Best travelled " + "in the later part of the summer " * 5))
|
||||
|
||||
def test_a_permit_is_said_only_when_it_is_short(self):
|
||||
short = sparse_record()
|
||||
short["hike"] = {"permit": "No permit is needed to hike it."}
|
||||
self.assertEqual(trail.permit_sentence(short), "No permit is needed to hike it.")
|
||||
long = sparse_record()
|
||||
long["hike"] = {"permit": "Some sections need a permit: East Bay lands need a trail permit, and another section needs a docent."}
|
||||
self.assertEqual(trail.permit_sentence(long), "")
|
||||
|
||||
def test_sparse_record_says_only_what_it_holds(self):
|
||||
s = self.sentences(sparse_record())
|
||||
self.assertEqual(s, ["The Sparse Trail is a 62-mile (100 km) trail in Arizona, United States.",
|
||||
"This site has no GPX for it."])
|
||||
|
||||
def test_route_names_a_plain_author_and_leaves_out_a_nickname(self):
|
||||
plain = load("bigfoot-trail")
|
||||
self.assertIn("a 360-mile (579 km) route by Michael Kauffmann, dating from 2009, through forest country",
|
||||
self.sentences(plain)[0])
|
||||
nick = load("great-basin-trail")
|
||||
self.assertIn('Ryan "Dirtmonger" Sylva', nick["route"]["creator"])
|
||||
self.assertNotIn("Dirtmonger", " ".join(self.sentences(nick)))
|
||||
self.assertRegex(self.sentences(nick)[0], r"-mile \([\d,]+ km\) loop route through ")
|
||||
|
||||
def test_loop_network_and_partial_track(self):
|
||||
loop = self.sentences(load("timberline"))
|
||||
self.assertIn("loop trail", loop[0])
|
||||
self.assertTrue(any(x.startswith("It starts and ends at Timberline Lodge") for x in loop))
|
||||
net = self.sentences(load("finger-lakes"))
|
||||
self.assertIn("trail network", net[0])
|
||||
self.assertTrue(any(x.startswith("Most walks start at ") for x in net))
|
||||
part = self.sentences(load("allegheny-trail"))
|
||||
self.assertTrue(any("computed from the part of the track on file, about 5% of the published length" in x for x in part))
|
||||
self.assertTrue(any(x == "This page has a GPX of part of the track to download." for x in part))
|
||||
|
||||
def test_trail_without_a_track_and_french_name(self):
|
||||
free = self.sentences(load("circle-of-solitude"))
|
||||
self.assertTrue(free[-1].startswith("This site has no GPX for it"))
|
||||
fr = load("sentier-national")
|
||||
self.assertTrue(self.sentences(fr)[0].startswith("Sentier National (Quebec) is a "))
|
||||
self.assertIn('<span lang="fr">', str(trail.brief_sentences(fr)[0]))
|
||||
|
||||
def test_a_place_name_that_starts_with_near_reads_mid_sentence(self):
|
||||
s = self.sentences(load("lone-star"))
|
||||
self.assertIn("It runs from near Richards, Texas, to near Cleveland, Texas.", " ".join(s))
|
||||
for rec in records.load_records(ROOT):
|
||||
self.assertNotRegex(" ".join(self.sentences(rec)), r"\b(from|to|at) Near ", rec["id"])
|
||||
|
||||
def test_article_follows_the_spoken_number(self):
|
||||
self.assertIn(" is an 81-mile ", self.sentences(load("avon"))[0])
|
||||
self.assertIn(" is an 800-mile ", self.sentences(load("desert-winter-thru-hike"))[0])
|
||||
|
||||
def test_every_record_gets_a_paragraph_the_record_can_support(self):
|
||||
for rec in records.load_records(ROOT):
|
||||
if rec["id"] in SITE.name_lang:
|
||||
rec["derived"]["name_lang"] = SITE.name_lang[rec["id"]]
|
||||
s = self.sentences(rec)
|
||||
paragraph = " ".join(s)
|
||||
self.assertGreaterEqual(len(s), 2, rec["id"])
|
||||
self.assertLessEqual(len(s), 4, rec["id"])
|
||||
self.assertIn("GPX", paragraph, rec["id"])
|
||||
self.assertNotRegex(paragraph, r"\b(Season|Permits are noted)\b", rec["id"])
|
||||
for bad in ("None", "{", "}", " ", " ,", " .", "unknown", "not known", "n/a"):
|
||||
self.assertNotIn(bad, paragraph, rec["id"])
|
||||
self.assertIn(f"{rec['derived']['length_mi']:,}-mile", paragraph, rec["id"])
|
||||
self.assertIn(f"({words_km(rec)} km)", paragraph, rec["id"])
|
||||
summary = hike.summary(rec)
|
||||
for sentence in re.split(r"(?<=[.!?])\s+", summary):
|
||||
self.assertNotIn(sentence.strip(), s, f"{rec['id']} repeats its summary word for word")
|
||||
h = hike.table(rec)
|
||||
if h.get("days"):
|
||||
self.assertIn("usually takes", paragraph, rec["id"])
|
||||
else:
|
||||
self.assertNotIn("usually takes", paragraph, rec["id"])
|
||||
if not (h.get("season") or h.get("months")):
|
||||
self.assertNotRegex(paragraph, r"usual season|walked all year|Northbound|season", rec["id"])
|
||||
if "No permit" in paragraph or "permit" in paragraph.lower():
|
||||
self.assertIn(common.sentence(h.get("permit", "")), paragraph, rec["id"])
|
||||
self.assertEqual("highest point" in paragraph,
|
||||
bool(h.get("high_point") or h.get("high_point_m") or rec["derived"].get("elevation")), rec["id"])
|
||||
|
||||
def test_the_paragraph_is_in_the_page_head_before_the_buttons(self):
|
||||
rec = load("appalachian")
|
||||
body = str(trail.render(rec, SITE, [rec])[2])
|
||||
self.assertLess(body.index('class="trail-lede"'), body.index('class="trail-brief"'))
|
||||
self.assertLess(body.index('class="trail-brief"'), body.index('class="note trail-checked"'))
|
||||
self.assertLess(body.index('class="note trail-checked"'), body.index('class="cluster trail-actions"'))
|
||||
self.assertIn("<strong>In brief.</strong>", body)
|
||||
|
||||
|
||||
def words_km(rec):
|
||||
from olt import words
|
||||
return words.fmt_km(rec["length_km"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -103,7 +103,7 @@ class LengthListsTest(unittest.TestCase):
|
||||
def test_the_hide_rule_is_kept(self):
|
||||
self.assertFalse(browse.is_shown(3, 100))
|
||||
self.assertFalse(browse.is_shown(80, 100))
|
||||
self.assertTrue(browse.is_shown(4, 100))
|
||||
self.assertTrue(browse.is_shown(browse.MIN_SIZE, 100))
|
||||
|
||||
|
||||
class RoundStepsTest(unittest.TestCase):
|
||||
|
||||
@@ -0,0 +1,447 @@
|
||||
"""Tests for the views built from the records: the extra lists, the place-by-list pages, tables, rankings,
|
||||
authors, recent changes, linked trails, the glossary and the method page.
|
||||
|
||||
Each view's selection rule is tested on small fixtures; the data files are checked against the real records.
|
||||
These do not need the built site.
|
||||
|
||||
python3 -m unittest discover -s web/tests
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
WEB = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
ROOT = os.path.dirname(WEB)
|
||||
sys.path.insert(0, WEB)
|
||||
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)
|
||||
from test_hike import fake # noqa: E402
|
||||
|
||||
SITE = site.Site("Long Hikes", "T", repo_url="https://github.com/o/r")
|
||||
|
||||
|
||||
def mi(n):
|
||||
"""The kilometres of a length in miles, unrounded, so a band's edge falls where the rule puts it."""
|
||||
return n * words.KM_PER_MI
|
||||
|
||||
|
||||
def keys(recs, key):
|
||||
return [r["id"] for r in browse.members(browse.by_key(key), recs)]
|
||||
|
||||
|
||||
class LengthBandTest(unittest.TestCase):
|
||||
def test_bands_split_at_the_mile_figures(self):
|
||||
recs = [fake(1, km=mi(99)), fake(2, km=mi(100)), fake(3, km=mi(199)), fake(4, km=mi(200)),
|
||||
fake(5, km=mi(499)), fake(6, km=mi(500)), fake(7, km=mi(999)), fake(8, km=mi(1000))]
|
||||
self.assertEqual(keys(recs, "under-100-miles"), ["t1"])
|
||||
self.assertEqual(sorted(keys(recs, "100-to-200-miles")), ["t2", "t3"])
|
||||
self.assertEqual(sorted(keys(recs, "200-to-500-miles")), ["t4", "t5"])
|
||||
self.assertEqual(sorted(keys(recs, "500-to-1000-miles")), ["t6", "t7"])
|
||||
self.assertEqual(keys(recs, "longest"), ["t8"])
|
||||
|
||||
def test_each_trail_is_in_exactly_one_band(self):
|
||||
bands = ("under-100-miles", "100-to-200-miles", "200-to-500-miles", "500-to-1000-miles", "longest")
|
||||
recs = [fake(i, km=km) for i, km in enumerate(range(50, 3000, 37))]
|
||||
for r in recs:
|
||||
self.assertEqual(sum(1 for b in bands if browse.by_key(b).test(r)), 1, r["length_km"])
|
||||
|
||||
def test_under_200_is_the_two_short_bands(self):
|
||||
recs = [fake(1, km=mi(50)), fake(2, km=mi(150)), fake(3, km=mi(250))]
|
||||
self.assertEqual(sorted(keys(recs, "under-200-miles")), ["t1", "t2"])
|
||||
self.assertTrue(browse.by_key("under-200-miles").search_title(9).startswith("Thru-Hikes Under 200 Miles"))
|
||||
|
||||
|
||||
class TimeListTest(unittest.TestCase):
|
||||
def test_bands_by_days(self):
|
||||
stated = lambda i, days: fake(i, hike={"days": days}) # noqa: E731
|
||||
recs = [stated(1, [2, 4]), stated(2, [4, 4]), stated(3, [5, 7]), stated(4, [20, 28]), stated(5, [30, 60])]
|
||||
self.assertEqual(sorted(keys(recs, "weekend")), ["t1", "t2"])
|
||||
self.assertEqual(keys(recs, "two-to-four-weeks"), ["t4"])
|
||||
self.assertEqual(keys(recs, "a-month-or-more"), ["t5"])
|
||||
self.assertEqual(sorted(keys(recs, "a-week-or-less")), ["t1", "t2", "t3"])
|
||||
|
||||
def test_note_says_how_many_are_stated_and_how_the_rest_were_estimated(self):
|
||||
recs = [fake(1, km=100, hike={"days": [3, 4]}), fake(2, km=100), fake(3, km=100)]
|
||||
note = browse.time_note(recs, recs)
|
||||
self.assertIn("A source states the time for 1 of these", note)
|
||||
self.assertIn("For the other 2 it is estimated from the length", note)
|
||||
self.assertIn("12 to 19 miles a day", note)
|
||||
self.assertIn("7 to 12", note)
|
||||
self.assertIn("all 1", browse.time_note(recs[:1], recs))
|
||||
self.assertIn("No source states the time", browse.time_note(recs[1:], recs))
|
||||
|
||||
|
||||
class KindListTest(unittest.TestCase):
|
||||
def test_high_routes_by_name_or_designation(self):
|
||||
a, b, c, d = fake(1), fake(2), fake(3), fake(4)
|
||||
a["name"] = "Alpine High Route"
|
||||
b["name"] = "Uinta Highline Trail" # a trail named Highline is not a high route
|
||||
c["common_name"] = "Big High Route"
|
||||
d["designation"] = "Person-defined high route"
|
||||
self.assertEqual(keys([a, b, c, d], "high-routes"), ["t1", "t3", "t4"])
|
||||
|
||||
def test_mostly_cross_country_and_unfinished(self):
|
||||
recs = [fake(1, hike={"travel": "mostly-cross-country"}), fake(2, hike={"travel": "some-cross-country"}),
|
||||
fake(3, hike={"unfinished": "Half is built."}), fake(4)]
|
||||
self.assertEqual(keys(recs, "mostly-cross-country"), ["t1"])
|
||||
self.assertEqual(keys(recs, "off-trail"), ["t1", "t2"])
|
||||
self.assertEqual(keys(recs, "unfinished"), ["t3"])
|
||||
|
||||
def test_holders_come_from_the_designation_alone(self):
|
||||
nrt, pc, fs, sp, club, route = (fake(i) for i in range(1, 7))
|
||||
nrt["designation"] = "National Recreation Trail (certified 2008), managed by the Bureau of Land Management"
|
||||
pc["designation"] = "Parks Canada, Jasper National Park"
|
||||
fs["designation"] = "National Recreation Trail #31 (Forest Service, Tonto National Forest)"
|
||||
sp["designation"] = "BC Parks (Naikoon Provincial Park)"
|
||||
club["designation"] = "Keystone Trails Association"
|
||||
route["designation"] = "Person-defined route (Jo); no agency or association"
|
||||
route["kind"] = "route"
|
||||
route["derived"]["kind"] = "route"
|
||||
recs = [nrt, pc, fs, sp, club, route]
|
||||
self.assertEqual(keys(recs, "national-recreation-trails"), ["t1", "t3"])
|
||||
self.assertEqual(keys(recs, "parks-canada"), ["t2"])
|
||||
self.assertEqual(keys(recs, "forest-service"), ["t3"])
|
||||
self.assertEqual(keys(recs, "state-and-provincial-parks"), ["t4"])
|
||||
# a route that says it has no association is not kept by one
|
||||
self.assertEqual(keys(recs, "clubs-and-associations"), ["t5"])
|
||||
|
||||
|
||||
class MonthListTest(unittest.TestCase):
|
||||
def test_a_month_holds_the_trails_whose_months_include_it(self):
|
||||
recs = [fake(1, hike={"months": [6, 7]}), fake(2, hike={"months": [8]}), fake(3)]
|
||||
self.assertEqual(keys(recs, "hike-in-july"), ["t1"])
|
||||
self.assertEqual(keys(recs, "hike-in-august"), ["t2"])
|
||||
|
||||
def test_a_month_needs_eight_trails_and_says_how_many_have_a_season(self):
|
||||
july = browse.by_key("hike-in-july")
|
||||
self.assertEqual(july.min_size, 8)
|
||||
self.assertFalse(browse.is_shown(7, 100, july.min_size))
|
||||
self.assertTrue(browse.is_shown(8, 100, july.min_size))
|
||||
recs = [fake(i, hike={"months": [7]}) for i in range(10)] + [fake(20 + i) for i in range(10)]
|
||||
shown = {lst.key for lst, _ in browse.shown(recs)}
|
||||
self.assertIn("hike-in-july", shown)
|
||||
self.assertNotIn("hike-in-august", shown)
|
||||
note = july.note(browse.members(july, recs), recs)
|
||||
self.assertIn("Only 10 of the 20 trails have a season on file", note)
|
||||
|
||||
def test_every_list_has_a_group_and_every_group_a_heading(self):
|
||||
headings = {k for k, _, _ in browse.GROUPS}
|
||||
for lst in browse.LISTS:
|
||||
self.assertIn(lst.group, headings, lst.key)
|
||||
|
||||
def test_titles_are_unique_and_short_enough(self):
|
||||
titles = [lst.search_title(99) for lst in browse.LISTS]
|
||||
self.assertEqual(len(titles), len(set(titles)))
|
||||
for t in titles:
|
||||
self.assertLessEqual(len(t), common.TITLE_LIMIT, t)
|
||||
|
||||
|
||||
class PlaceFacetTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
# Eight trails in Arizona: six under 100 miles, three of them loops; two in Utah.
|
||||
self.recs = [fake(i, km=mi(50), regions=["AZ"], hike={"shape": "loop" if i < 3 else "point-to-point"})
|
||||
for i in range(6)]
|
||||
self.recs += [fake(6, km=mi(150), regions=["AZ"]), fake(7, km=mi(150), regions=["AZ"])]
|
||||
self.recs += [fake(8, km=mi(50), regions=["UT"]), fake(9, km=mi(50), regions=["UT"])]
|
||||
# enough trails elsewhere that the lists are shown (no more than 75% of all trails)
|
||||
self.recs += [fake(20 + i, km=mi(400), regions=["NY"]) for i in range(12)]
|
||||
|
||||
def pages(self):
|
||||
return placefacets.plan(self.recs)
|
||||
|
||||
def test_a_page_needs_five_trails_in_the_place(self):
|
||||
pages = self.pages()
|
||||
self.assertTrue(pages)
|
||||
for p in pages:
|
||||
self.assertGreaterEqual(len(p["recs"]), browse.MIN_SIZE)
|
||||
self.assertNotIn("ut", {p["slug"].split("-")[1] for p in pages}) # two trails: no page
|
||||
|
||||
def test_a_page_that_repeats_the_whole_place_is_left_out(self):
|
||||
for p in self.pages():
|
||||
self.assertLessEqual(len(p["recs"]), browse.MAX_SHARE * len(p["info"]["records"]))
|
||||
|
||||
def test_three_loops_are_too_few(self):
|
||||
self.assertNotIn("loops", {p["lst"].key for p in self.pages()})
|
||||
|
||||
def test_a_set_that_repeats_another_page_of_the_place_is_kept_once(self):
|
||||
# the six short trails are the same set under two lists: only one page for them
|
||||
sets = [frozenset(r["id"] for r in p["recs"]) for p in self.pages() if p["slug"] == "us-az"]
|
||||
self.assertEqual(len(sets), len(set(sets)))
|
||||
|
||||
def test_title_and_path(self):
|
||||
p = self.pages()[0]
|
||||
self.assertEqual(p["path"], f"/regions/{p['slug']}/{p['lst'].key}/")
|
||||
title, desc, body, _ = placefacets.page(p, self.recs, SITE, self.pages())
|
||||
self.assertIn("Arizona", title)
|
||||
self.assertIn(f"{len(p['recs'])}", title)
|
||||
self.assertEqual(str(body).count("<h1>"), 1)
|
||||
|
||||
|
||||
class RankingTest(unittest.TestCase):
|
||||
def test_highest_points_rank_only_records_that_state_one(self):
|
||||
recs = [fake(i, hike={"high_point_m": 1000 + i * 10, "high_point": f"P{i}"}) for i in range(1, 7)] + [fake(9), fake(10)]
|
||||
spec = next(s for s in standing.RANKINGS if s[0] == "highest-points")
|
||||
title, desc, body, have = standing.ranking_page(spec, recs, SITE)
|
||||
self.assertEqual(len(have), 6)
|
||||
self.assertIn("6 of the 8 trails have a high point stated", str(body))
|
||||
text = str(body)
|
||||
self.assertLess(text.index("P6"), text.index("P5")) # highest first
|
||||
self.assertIn("Ranked by High Point", title)
|
||||
|
||||
def test_a_ranking_with_fewer_than_five_is_not_built(self):
|
||||
recs = [fake(i, hike={"high_point_m": 2000}) for i in range(4)]
|
||||
spec = next(s for s in standing.RANKINGS if s[0] == "highest-points")
|
||||
self.assertIsNone(standing.ranking_page(spec, recs, SITE))
|
||||
|
||||
def test_climb_leaves_out_a_track_that_covers_part_of_the_trail(self):
|
||||
whole = {"ascent_m": 1000, "coverage": 1.0, "highest": {"m": 5}, "source": {"limits": "Computed, not measured."}}
|
||||
partial = dict(whole, coverage=0.5)
|
||||
recs = [fake(i, km=100) for i in range(6)]
|
||||
for r, e in zip(recs, [whole] * 5 + [partial]):
|
||||
r["derived"]["elevation"] = e
|
||||
have = [r for r in recs if standing._climb(r) is not None]
|
||||
self.assertEqual(len(have), 5)
|
||||
self.assertEqual(standing._climb_rate(have[0]), 1000 / 100)
|
||||
|
||||
|
||||
class CollectionTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.recs = [fake(i, km=1000 * i) for i in range(1, 4)]
|
||||
self.coll = {"id": "set", "name": "The Set", "members": ["t1", "t2", "t3"],
|
||||
"definition": "A set of three.", "source_url": "https://example.org/", "source_publisher": "Someone"}
|
||||
|
||||
def test_members_are_set_side_by_side_in_the_order_given(self):
|
||||
title, desc, body, recs = standing.collection_page(self.coll, self.recs, SITE)
|
||||
self.assertEqual([r["id"] for r in recs], ["t1", "t2", "t3"])
|
||||
self.assertIn("Compared", title)
|
||||
self.assertEqual(standing.collection_path(self.coll), "/set/")
|
||||
for word in ("best", "rank", "recommend"):
|
||||
self.assertNotIn(word, str(body).lower().replace("ranked", ""))
|
||||
|
||||
def test_a_missing_member_means_no_page(self):
|
||||
self.coll["members"].append("nope")
|
||||
self.assertIsNone(standing.collection_page(self.coll, self.recs, SITE))
|
||||
|
||||
|
||||
class AuthorTest(unittest.TestCase):
|
||||
def routes(self, credits):
|
||||
out = []
|
||||
for i, c in enumerate(credits):
|
||||
r = fake(i)
|
||||
r["kind"] = "route"
|
||||
r["derived"]["kind"] = "route"
|
||||
r["route"] = {"creator": c}
|
||||
out.append(r)
|
||||
return out
|
||||
|
||||
def test_credits_in_authors_file_gather_one_person(self):
|
||||
recs = self.routes(["Andrew Skurka", "Andrew Skurka and Ryan Jordan", "Cam Honan"])
|
||||
gs = {g["name"]: g for g in authors.groups(recs, ROOT)}
|
||||
self.assertEqual(len(gs["Andrew Skurka"]["routes"]), 2)
|
||||
self.assertEqual(len(gs["Cam Honan"]["routes"]), 1)
|
||||
|
||||
def test_a_shared_credit_is_on_each_persons_page_and_names_the_other(self):
|
||||
recs = self.routes(["Andrew Skurka and Ryan Jordan"])
|
||||
gs = {g["name"]: g for g in authors.groups(recs, ROOT)}
|
||||
self.assertEqual([r["id"] for r in gs["Ryan Jordan"]["routes"]], [r["id"] for r in recs])
|
||||
self.assertEqual(gs["Ryan Jordan"]["others"][recs[0]["id"]], ["Andrew Skurka"])
|
||||
g = gs["Ryan Jordan"]
|
||||
_, _, body, _, _, person = authors.author_page(g, recs, SITE, list(gs.values()))
|
||||
self.assertIn("also credited to <a href=\"/authors/andrew-skurka/\">Andrew Skurka</a>", str(body))
|
||||
self.assertEqual(person["@type"], "Person")
|
||||
|
||||
def test_featured_authors_are_cards_with_lengths_that_follow_the_units_switch(self):
|
||||
recs = self.routes(["Cam Honan"] * 3 + ["A Club"])
|
||||
_, _, body, _ = authors.index_page(recs, SITE, ROOT)
|
||||
html = str(body)
|
||||
self.assertIn('<li class="shelf shelf--author">', html)
|
||||
self.assertIn('class="shelf__count"', html)
|
||||
self.assertIn('class="shelf__len"><span class="len len--inline"><span class="len__mi">', html)
|
||||
self.assertIn("All 3 routes by Cam Honan", html)
|
||||
self.assertNotIn("A Club</a></h3>", html)
|
||||
|
||||
def test_every_author_has_a_page_however_few_routes(self):
|
||||
recs = self.routes(["Andrew Skurka"] * 3 + ["Andrew Skurka and Ryan Jordan"] * 2 + ["Cam Honan"] * 4 + ["A Club"])
|
||||
pages = {g["name"]: len(g["routes"]) for g in authors.author_pages(recs, ROOT)}
|
||||
self.assertEqual(pages, {"Andrew Skurka": 5, "Ryan Jordan": 2, "Cam Honan": 4, "A Club": 1})
|
||||
|
||||
def test_a_single_route_page_has_substance_and_an_unlisted_credit_is_not_a_person(self):
|
||||
real = [r for r in records.load_records(ROOT) if r.get("kind") == "route"]
|
||||
gs = authors.author_pages(real, ROOT)
|
||||
one = next(g for g in gs if len(g["routes"]) == 1 and g["kind"] == "person")
|
||||
title, desc, body, _, routes, person = authors.author_page(one, real, SITE, gs)
|
||||
self.assertIn('class="trail-brief"', str(body))
|
||||
self.assertIn("<table", str(body))
|
||||
self.assertLessEqual(len(title), 60)
|
||||
self.assertEqual(person["name"], one["name"])
|
||||
club = next(g for g in gs if g["name"] == "Wilderness Mindset")
|
||||
self.assertEqual(club["kind"], "")
|
||||
self.assertIsNone(authors.author_page(club, real, SITE, gs)[5])
|
||||
|
||||
def test_the_top_section_is_every_author_at_the_threshold_and_follows_it(self):
|
||||
real = [r for r in records.load_records(ROOT) if r.get("kind") == "route"]
|
||||
gs = authors.author_pages(real, ROOT)
|
||||
top = authors.prominent(gs)
|
||||
self.assertTrue(top)
|
||||
self.assertTrue(all(len(g["routes"]) >= authors.PROMINENT_MIN for g in top))
|
||||
self.assertEqual(len(top), sum(1 for g in gs if len(g["routes"]) >= authors.PROMINENT_MIN))
|
||||
counts = [len(g["routes"]) for g in top]
|
||||
self.assertEqual(counts, sorted(counts, reverse=True))
|
||||
body = str(authors.index_page(real, SITE, ROOT)[2])
|
||||
self.assertLess(body.index('id="most-routes"'), body.index('id="other-authors"'))
|
||||
for g in top:
|
||||
self.assertLess(body.index(f'<h3 class="shelf__title"><a href="/authors/{g["slug"]}/">'), body.index('id="other-authors"'))
|
||||
self.assertEqual(body.count('class="shelf shelf--author"'), len(top))
|
||||
old = authors.PROMINENT_MIN
|
||||
try:
|
||||
authors.PROMINENT_MIN = 5
|
||||
self.assertEqual({g["name"] for g in authors.prominent(gs)}, {"Brett Tucker", "Andrew Skurka"})
|
||||
finally:
|
||||
authors.PROMINENT_MIN = old
|
||||
|
||||
def test_a_credit_in_a_route_page_links_each_named_author(self):
|
||||
recs = self.routes(["Andrew Skurka and Ryan Jordan"])
|
||||
links = authors.link_map(recs, ROOT)
|
||||
html = str(authors.credit_html("Andrew Skurka and Ryan Jordan", links["Andrew Skurka and Ryan Jordan"]))
|
||||
self.assertIn('<a href="/authors/andrew-skurka/">Andrew Skurka</a> and <a href="/authors/ryan-jordan/">Ryan Jordan</a>', html)
|
||||
|
||||
def test_authors_file_matches_the_records(self):
|
||||
real = records.load_records(ROOT)
|
||||
creators = {r["route"]["creator"] for r in real if r.get("kind") == "route"}
|
||||
for a in datafiles.authors(ROOT):
|
||||
for c in a["credits"]:
|
||||
self.assertIn(c, creators)
|
||||
|
||||
|
||||
class RecentTest(unittest.TestCase):
|
||||
def rec(self, i, added, changes=()):
|
||||
r = fake(i)
|
||||
r["history"] = [{"date": added, "change": "Added.", "fields": ["record"], "outcome": "applied"}]
|
||||
for d, fields, outcome in changes:
|
||||
r["history"].append({"date": d, "change": f"Changed {fields[0]}.", "fields": fields, "outcome": outcome})
|
||||
return r
|
||||
|
||||
def test_whole_days_of_additions_until_enough(self):
|
||||
recs = [self.rec(i, "2026-11-16") for i in range(12)] + [self.rec(20 + i, "2026-11-15") for i in range(12)] \
|
||||
+ [self.rec(40 + i, "2026-11-09") for i in range(12)]
|
||||
added = views.recent_added(recs)
|
||||
self.assertEqual([d for d, _ in added], ["2026-11-16", "2026-11-15"])
|
||||
self.assertEqual(sum(len(rs) for _, rs in added), 24)
|
||||
|
||||
def test_changes_leave_out_additions_and_declined_requests(self):
|
||||
r = self.rec(1, "2026-11-10", [("2026-11-12", ["length_km"], "applied"), ("2026-11-13", ["length_km"], "declined")])
|
||||
rows, total = views.recent_changes([r])
|
||||
self.assertEqual(total, 1)
|
||||
self.assertEqual(rows[0][0], "2026-11-12")
|
||||
|
||||
def test_newest_first(self):
|
||||
a = self.rec(1, "2026-11-10", [("2026-11-12", ["name"], "applied")])
|
||||
b = self.rec(2, "2026-11-10", [("2026-11-14", ["name"], "applied")])
|
||||
rows, _ = views.recent_changes([a, b])
|
||||
self.assertEqual([r[0] for r in rows], ["2026-11-14", "2026-11-12"])
|
||||
|
||||
def test_no_page_with_fewer_than_five_added(self):
|
||||
self.assertIsNone(views.recent_page([self.rec(i, "2026-11-16") for i in range(4)], SITE))
|
||||
|
||||
|
||||
class LinkedTest(unittest.TestCase):
|
||||
def test_a_group_is_a_trail_that_three_others_name(self):
|
||||
hub = fake(0)
|
||||
hub["name"] = "Grand Example Trail"
|
||||
recs = [hub]
|
||||
for i in range(1, 6):
|
||||
r = fake(i)
|
||||
r["name"] = f"Side Path {i}"
|
||||
r["hike"] = {"summary": "It joins the Grand Example Trail near the border." if i <= 3 else "It is a walk."}
|
||||
recs.append(r)
|
||||
groups = views.connections(recs)
|
||||
self.assertEqual([h["id"] for h, _ in groups], ["t0"])
|
||||
self.assertEqual([r["id"] for r in groups[0][1]], ["t1", "t2", "t3"])
|
||||
|
||||
def test_two_namers_are_not_a_group(self):
|
||||
hub = fake(0)
|
||||
hub["name"] = "Grand Example Trail"
|
||||
recs = [hub] + [dict(fake(i), name=f"Side Path {i}", hike={"summary": "Meets the Grand Example Trail."})
|
||||
for i in (1, 2)]
|
||||
self.assertEqual(views.connections(recs), [])
|
||||
|
||||
|
||||
class SummaryTest(unittest.TestCase):
|
||||
def test_longest_and_shortest_come_from_the_lengths(self):
|
||||
recs = [fake(1, km=mi(60)), fake(2, km=mi(900)), fake(3, km=mi(300))]
|
||||
for r in recs:
|
||||
r["name"] = f"Name{r['id']}"
|
||||
text = str(summary.facts(recs, recs))
|
||||
self.assertIn("The longest is", text)
|
||||
self.assertLess(text.index("Namet2"), text.index("Namet1"))
|
||||
|
||||
def test_a_small_place_gets_a_paragraph_for_each_trail(self):
|
||||
recs = [fake(1, hike={"summary": "First sentence. Second sentence here.", "high_point_m": 2000, "high_point": "Top"})]
|
||||
text = str(summary.details(recs))
|
||||
self.assertIn("Second sentence here.", text)
|
||||
self.assertIn("Its high point is Top", text)
|
||||
self.assertEqual(str(summary.details([fake(i) for i in range(summary.DETAIL_MAX + 1)])), "")
|
||||
|
||||
def test_place_page_says_how_many_trails_and_the_share(self):
|
||||
recs = [fake(i, regions=["AZ"]) for i in range(4)] + [fake(5, regions=["UT"])]
|
||||
title, desc, body, _ = regions.region_page("us-az", recs, SITE)
|
||||
self.assertIn("4 trails of the 5 trails on this site, 80.0 percent", str(body))
|
||||
|
||||
|
||||
class RealDataTest(unittest.TestCase):
|
||||
"""The data files and the lists, against the repository's own records."""
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.records = records.load_records(ROOT)
|
||||
cls.shown = browse.shown(cls.records)
|
||||
|
||||
def test_no_list_page_has_fewer_than_five_trails(self):
|
||||
for lst, recs in self.shown:
|
||||
self.assertGreaterEqual(len(recs), browse.MIN_SIZE, lst.key)
|
||||
|
||||
def test_the_new_lists_are_shown(self):
|
||||
have = {lst.key for lst, _ in self.shown}
|
||||
for key in ("100-to-200-miles", "200-to-500-miles", "500-to-1000-miles", "under-200-miles", "weekend",
|
||||
"two-to-four-weeks", "a-month-or-more", "high-routes", "mostly-cross-country", "hike-in-july"):
|
||||
self.assertIn(key, have)
|
||||
|
||||
def test_glossary_links_resolve_to_pages_that_are_built(self):
|
||||
known = {"/", "/lists/", "/routes/", "/authors/", "/method/", "/numbers/", "/glossary/", "/data/schema/"}
|
||||
known |= {browse.path(lst) for lst, _ in self.shown}
|
||||
known |= {standing.collection_path(c) for c in datafiles.collections(ROOT)}
|
||||
known |= {f"/numbers/{s[0]}/" for s in standing.RANKINGS}
|
||||
for t in reference.terms(ROOT):
|
||||
for p in t.get("see", []):
|
||||
self.assertIn(p, known, f"{t['id']} points at {p}")
|
||||
|
||||
def test_glossary_covers_the_words_the_site_uses(self):
|
||||
ids = {t["id"] for t in reference.terms(ROOT)}
|
||||
for needed in ("thru-hike", "section-hike", "route", "high-route", "track", "gpx", "national-scenic-trail",
|
||||
"cross-country", "resupply"):
|
||||
self.assertIn(needed, ids)
|
||||
|
||||
def test_the_triple_crown_is_built_from_its_collection(self):
|
||||
coll = datafiles.collections(ROOT)[0]
|
||||
built = standing.collection_page(coll, self.records, SITE)
|
||||
self.assertIsNotNone(built)
|
||||
self.assertEqual(len(built[3]), 3)
|
||||
|
||||
def test_the_method_page_counts_what_the_records_hold(self):
|
||||
title, desc, body = reference.method_page(self.records, SITE, ROOT)
|
||||
n_ver = len(reference.verified(self.records))
|
||||
self.assertIn(f"{n_ver} of the {len(self.records)} trails have a track", str(body))
|
||||
|
||||
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("place-summary", str(body))
|
||||
if len(by_slug[slug]["records"]) > 1:
|
||||
self.assertIn("The longest is", str(body))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user