Say what each page is in the words people search with, and mark up the facts
A whole-site search audit found clean foundations and three gaps: titles without the words people search for, no structured data on trail pages, and trails that did not link to each other. - Trail titles carry the name hikers use, the abbreviation, the length and what the page offers; "GPX" only where the page has one. A new optional `common_name` field holds the name hikers use (13 records). - Descriptions are built from each record, at most 155 characters. - Place and list pages are titled for what they are; heading levels no longer jump. - Trail pages link to similar and related trails and to the lists they belong to. Every trail has at least three links from other trails. - JSON-LD on every page: a Place for each trail, breadcrumbs, item lists on list and place pages, WebSite and Organization on the home page, a fuller Dataset on the data page. - A social card per trail, a changelog feed, `lastmod` in the sitemap from record dates, `noindex` on the 404 and on raw per-trail files, a favicon and an `llms.txt` listing the data files and licences. - The "Considered and left out" page has its spacing fixed. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
1 parent
a46338afd5
commit
5b80fccd1e
245 files changed
+2534
-137
No files matched your search
@@ -122,7 +122,8 @@ class TrailPageTest(unittest.TestCase):
|
||||
self.assertIn('href="https://trail.example/facts"', about)
|
||||
self.assertIn("For start, end, time and season", text(about))
|
||||
self.assertIn("Checked 2026-11-13.", text(about))
|
||||
self.assertEqual(trail.description(rec)[:52], "A long walk along the crest of the Example Range. Wh")
|
||||
self.assertTrue(trail.description(rec).startswith(
|
||||
"A trail of 62 miles (100 km) in Arizona, usually 5 to 7 months. A long walk along the crest"))
|
||||
|
||||
def test_partial_hike_table(self):
|
||||
rec = sample_record("X Trail")
|
||||
|
||||
@@ -55,7 +55,7 @@ class PageTest(unittest.TestCase):
|
||||
self.text = str(self.body)
|
||||
|
||||
def test_title(self):
|
||||
self.assertEqual(self.title, "Considered and left out")
|
||||
self.assertEqual(self.title, "Trails Considered and Left Out, and Why")
|
||||
|
||||
def test_opening_is_generated_from_the_entries(self):
|
||||
self.assertIn("lists 2 trails and routes", self.text)
|
||||
|
||||
@@ -0,0 +1,317 @@
|
||||
"""Tests for the words a search result shows (titles and descriptions), the heading order of
|
||||
the place and list pages, and the links between trails (olt/trail.py, olt/regions.py,
|
||||
olt/browse.py, olt/related.py, olt/leftout.py).
|
||||
|
||||
They render fixtures; they do not need the built site.
|
||||
"""
|
||||
import copy
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
WEB = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
sys.path.insert(0, WEB)
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
from olt import browse, common, home, layout, leftout, regions, related, site, trail # noqa: E402
|
||||
from test_hike import FULL_HIKE, fake # noqa: E402
|
||||
|
||||
S = site.Site("Long Hikes", "A tagline", home_title="Long-Distance Hiking Trails of the US and Canada")
|
||||
ROOM = common.title_room(S)
|
||||
|
||||
|
||||
def gpx(rec):
|
||||
"""Give a fixture the downloads a built record has."""
|
||||
rec["derived"]["has_line"] = True
|
||||
rec["derived"]["downloads"] = [
|
||||
{"file": "t.geojson", "format": "GeoJSON", "role": "main", "bytes": 1000, "note": "Full"},
|
||||
{"file": "t.gpx", "format": "GPX", "role": "main", "bytes": 500, "note": "Simplified"}]
|
||||
return rec
|
||||
|
||||
|
||||
def at():
|
||||
rec = gpx(fake(1, km=3537, regions=["GA", "NC", "TN", "VA", "WV", "MD", "PA", "NJ", "NY", "CT", "MA", "VT", "NH", "ME"],
|
||||
hike=dict(FULL_HIKE, days=[150, 210])))
|
||||
rec["name"] = "Appalachian National Scenic Trail"
|
||||
rec["common_name"] = "Appalachian Trail"
|
||||
rec["short_name"] = "AT"
|
||||
rec["derived"]["length_mi"] = 2198
|
||||
return rec
|
||||
|
||||
|
||||
def levels(html_text):
|
||||
return [int(m) for m in re.findall(r"<h([1-6])[ >]", 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")
|
||||
|
||||
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")
|
||||
|
||||
def test_gpx_and_map_only_where_the_page_has_them(self):
|
||||
rec = at()
|
||||
rec["derived"]["has_line"] = False
|
||||
rec["derived"]["downloads"] = []
|
||||
title = trail.page_title(rec, S)
|
||||
self.assertNotIn("GPX", title)
|
||||
self.assertNotIn("map", title)
|
||||
self.assertIn("2,198 miles", title)
|
||||
|
||||
def test_a_route_says_it_is_a_route(self):
|
||||
rec = fake(1, km=314)
|
||||
rec["name"], rec["short_name"] = "Sierra High Route", "SHR"
|
||||
rec["derived"]["kind"], rec["derived"]["length_mi"] = "route", 195
|
||||
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.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")
|
||||
|
||||
def test_pieces_go_in_a_stated_order_and_the_length_stays(self):
|
||||
rec = at()
|
||||
rec["common_name"] = "Appalachian Long Distance Footpath"
|
||||
rec["short_name"] = "ALDF"
|
||||
rec["derived"]["length_mi"] = 2198
|
||||
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"
|
||||
title = trail.page_title(rec, S)
|
||||
self.assertEqual(title, "A Very Long Name For A Trail That Goes On And On: 2,198 miles")
|
||||
|
||||
def test_kilometres_follow_only_where_there_is_room(self):
|
||||
rec = gpx(fake(1, km=80))
|
||||
rec["name"], rec["short_name"] = "Short Path", "SP"
|
||||
rec["derived"]["length_mi"] = 50
|
||||
self.assertEqual(trail.page_title(rec, S), "Short Path (SP): 50 miles (80 km), map and GPX")
|
||||
|
||||
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.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)
|
||||
|
||||
def test_a_record_without_a_common_name_shows_no_full_name(self):
|
||||
body = trail.render(gpx(fake(1)), S)[2]
|
||||
self.assertNotIn("Full name", body)
|
||||
|
||||
|
||||
class TrailDescriptionTest(unittest.TestCase):
|
||||
def test_it_leads_with_the_facts_of_the_record(self):
|
||||
text = trail.description(at())
|
||||
self.assertTrue(text.startswith("A trail of 2,198 miles (3,537 km) across 14 states, usually 5 to 7 months."), text)
|
||||
self.assertIn("A long walk along the crest of the Example Range", text)
|
||||
|
||||
def test_at_most_155_characters_cut_at_a_word(self):
|
||||
rec = at()
|
||||
rec["hike"]["summary"] = "The walk goes " + "on and on and on " * 20 + "to the end."
|
||||
text = trail.description(rec)
|
||||
self.assertLessEqual(len(text), common.DESCRIPTION_LIMIT)
|
||||
self.assertTrue(text.endswith("…"))
|
||||
self.assertFalse(text[:-1].endswith(" "))
|
||||
self.assertTrue(text[:-1].rsplit(" ", 1)[1] in ("on", "and", "goes", "walk", "The"))
|
||||
|
||||
def test_no_stock_sentence(self):
|
||||
for rec in (at(), fake(1), fake(2, hike={})):
|
||||
text = trail.description(rec)
|
||||
self.assertNotIn("GPX", text)
|
||||
|
||||
def test_a_record_with_no_summary_uses_its_designation(self):
|
||||
rec = fake(1, km=160)
|
||||
rec["derived"]["length_mi"] = 99
|
||||
rec["regions"] = ["IN"]
|
||||
self.assertEqual(trail.description(rec), "A trail of 99 miles (160 km) in Arizona. A & B Association.".replace("Arizona", "Indiana"))
|
||||
|
||||
def test_a_route_is_a_route_and_stated_time_only(self):
|
||||
rec = fake(1, km=300, hike={"summary": "Steve Roper's route.", "checked": "2026-11-13"})
|
||||
rec["derived"]["kind"], rec["kind"] = "route", "route"
|
||||
self.assertTrue(trail.description(rec).startswith("A route of "), trail.description(rec))
|
||||
self.assertNotIn("usually", trail.description(rec))
|
||||
|
||||
|
||||
class PlaceAndListTitleTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.recs = [fake(i, km=100 + 90 * i, regions=["CO"], hike=dict(FULL_HIKE)) for i in range(1, 7)]
|
||||
for i, r in enumerate(self.recs):
|
||||
r["id"], r["name"] = f"t{i}", f"Trail {i}"
|
||||
r["derived"]["length_mi"] = round(r["length_km"] / 1.609344)
|
||||
self.recs[0]["derived"]["kind"] = self.recs[0]["kind"] = "route"
|
||||
|
||||
def test_place_title_counts_trails_and_routes(self):
|
||||
title, desc, body, _ = regions.region_page("us-co", self.recs, S)
|
||||
self.assertEqual(title, "Long Trails in Colorado: 5 Trails and 1 Route")
|
||||
self.assertLessEqual(len(desc), common.DESCRIPTION_LIMIT)
|
||||
self.assertIn("from Trail 0, 118 miles, to Trail 5, 398 miles.", desc)
|
||||
self.assertNotIn(title, desc)
|
||||
|
||||
def test_a_long_place_name_drops_the_counts_to_fit(self):
|
||||
recs = [fake(i, regions=["NL"], country="CA") for i in range(1, 4)]
|
||||
for i, r in enumerate(recs):
|
||||
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.assertTrue(title.startswith("Long Trails in Newfoundland and Labrador"))
|
||||
|
||||
def test_a_place_with_one_trail(self):
|
||||
title, desc = regions.region_page("us-co", self.recs[1:2], S)[:2]
|
||||
self.assertEqual(title, "Long Trails in Colorado: 1 Trail")
|
||||
self.assertIn("is the one long trail listed in Colorado", desc)
|
||||
|
||||
def test_every_list_has_a_search_title_that_fits(self):
|
||||
for lst in browse.LISTS:
|
||||
title = lst.search_title(999)
|
||||
self.assertLessEqual(len(title), ROOM, title)
|
||||
self.assertIn("999", title)
|
||||
self.assertEqual(browse.by_key("loops").search_title(32), "Loop Hiking Trails: 32 Long Trail Loops")
|
||||
|
||||
def test_list_description_adds_to_the_title(self):
|
||||
lst = browse.by_key("under-100-miles")
|
||||
members = browse.members(lst, [fake(i, km=100) for i in range(1, 5)])
|
||||
title, desc = regions.list_page(lst, members, 20, S)[:2]
|
||||
self.assertTrue(title.startswith("Hiking Trails Under 100 Miles: 4"))
|
||||
self.assertLessEqual(len(desc), common.DESCRIPTION_LIMIT)
|
||||
self.assertTrue(desc.startswith(lst.blurb))
|
||||
self.assertIn("4 trails", desc)
|
||||
|
||||
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)
|
||||
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))
|
||||
bare = layout.layout("", "x", path="/", site=site.Site("N", "Tag"))
|
||||
self.assertIn("<title>N: Tag</title>", bare)
|
||||
|
||||
|
||||
class HeadingOrderTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.recs = [fake(i, km=100 + 50 * i, regions=["CO"]) for i in range(1, 6)]
|
||||
for i, r in enumerate(self.recs):
|
||||
r["id"] = f"t{i}"
|
||||
|
||||
def check(self, body):
|
||||
found = levels(str(body))
|
||||
for before, after in zip(found, found[1:]):
|
||||
self.assertLessEqual(after, before + 1, found)
|
||||
return found
|
||||
|
||||
def test_place_page(self):
|
||||
found = self.check(regions.region_page("us-co", self.recs, S)[2])
|
||||
self.assertEqual(found[0], 1)
|
||||
self.assertEqual(found[1], 2)
|
||||
|
||||
def test_list_page(self):
|
||||
lst = browse.by_key("under-100-miles")
|
||||
self.check(regions.list_page(lst, self.recs, 10, S)[2])
|
||||
|
||||
def test_routes_page_keeps_groups_above_their_trails(self):
|
||||
for r in self.recs:
|
||||
r["kind"] = r["derived"]["kind"] = "route"
|
||||
r["route"] = {"creator": "A. Author", "line_policy": "sold"}
|
||||
found = self.check(regions.routes_page(self.recs, S)[2])
|
||||
self.assertIn(3, found)
|
||||
|
||||
def test_the_home_page_list_is_unchanged(self):
|
||||
self.assertIn('<h3 class="entry__name">', str(home.results(self.recs)))
|
||||
self.assertIn('<h2 class="entry__name">', str(home.results(self.recs, top=2)))
|
||||
|
||||
|
||||
class LeftOutLayoutTest(unittest.TestCase):
|
||||
def test_the_intro_and_the_groups_are_spaced_like_the_other_list_pages(self):
|
||||
entries = [{"id": "a", "name": "A", "country": "US", "regions": ["AZ"], "reason": "below-floor",
|
||||
"note": "Short.", "decided": "2026-11-14", "source_url": "https://e.org/"}]
|
||||
body = str(leftout.left_out_page(entries, S, "")[2])
|
||||
# .place spaces its children apart (the intro from the first heading), and
|
||||
# .section--finder gives the intro the same short space above as the home page's list.
|
||||
opening = '<div class="container section section--finder place">'
|
||||
self.assertIn(opening, body)
|
||||
main = body[body.index(opening):]
|
||||
self.assertLess(main.index('<p class="prose">'), main.index("<section"))
|
||||
|
||||
|
||||
class LinksTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.recs = []
|
||||
for i in range(1, 13):
|
||||
r = fake(i, km=100 + 25 * i, hike={"summary": f"Walk number {i}.", "checked": "2026-11-13",
|
||||
"terrain": ["desert"] if i % 2 else ["forest"], "shape": "loop" if i < 7 else "point-to-point"})
|
||||
r["id"], r["name"] = f"t{i}", f"Trail {i}"
|
||||
r["derived"]["length_mi"] = round(r["length_km"] / 1.609344)
|
||||
self.recs.append(r)
|
||||
|
||||
def test_every_trail_is_listed_by_three_others(self):
|
||||
counts = {r["id"]: 0 for r in self.recs}
|
||||
for r in self.recs:
|
||||
like = related.similar_to(r, self.recs)
|
||||
self.assertTrue(4 <= len(like) <= related.SIMILAR_MAX)
|
||||
self.assertNotIn(r["id"], [x["id"] for x in like])
|
||||
for x in like:
|
||||
counts[x["id"]] += 1
|
||||
self.assertGreaterEqual(min(counts.values()), related.MIN_INBOUND)
|
||||
|
||||
def test_similar_trails_are_close_in_length(self):
|
||||
rec = self.recs[5]
|
||||
like = related.similar_to(rec, self.recs)
|
||||
self.assertTrue(any(abs(x["length_km"] - rec["length_km"]) <= 50 for x in like))
|
||||
|
||||
def test_shared_terrain(self):
|
||||
self.assertEqual(related.shared_terrain(self.recs[0], self.recs[2]), ["desert"])
|
||||
self.assertEqual(related.shared_terrain(self.recs[0], self.recs[1]), [])
|
||||
|
||||
def test_trails_that_share_a_name_or_name_each_other_are_related(self):
|
||||
a, b, c = fake(1), fake(2), fake(3)
|
||||
a["name"], b["name"], c["name"] = "Teton Crest Trail", "Teton Crest Route", "Lone Peak Trail"
|
||||
c["hike"] = {"summary": "It meets the Teton Crest Route at its north end.", "checked": "2026-11-13"}
|
||||
recs = [a, b, c]
|
||||
for r, i in zip(recs, "abc"):
|
||||
r["id"] = i
|
||||
self.assertEqual([(r["id"], why) for r, why in related.related_to(c, recs)], [("b", "named")])
|
||||
self.assertEqual([(r["id"], why) for r, why in related.related_to(b, recs)], [("c", "names")])
|
||||
self.assertEqual(related.related_to(a, recs), [])
|
||||
b["name"] = "Teton Crest Trail (Route)"
|
||||
related._CACHE.clear()
|
||||
self.assertIn(("b", "name"), [(r["id"], why) for r, why in related.related_to(a, recs)])
|
||||
|
||||
def test_a_one_word_name_is_not_matched(self):
|
||||
a, b = fake(1), fake(2)
|
||||
a["name"], b["name"] = "Wonderland", "Wonderland Loop"
|
||||
a["id"], b["id"] = "a", "b"
|
||||
b["hike"] = {"summary": "Not the Wonderland.", "checked": "2026-11-13"}
|
||||
self.assertEqual(related.related_to(b, [a, b]), [])
|
||||
|
||||
def test_the_page_links_terrain_shape_time_and_length_to_their_lists(self):
|
||||
recs = [copy.deepcopy(r) for r in self.recs]
|
||||
rec = recs[0]
|
||||
page = str(trail.glance(rec, recs))
|
||||
shown = {lst.key for lst, _ in browse.shown(recs)}
|
||||
for key in ("terrain-desert", "loops"):
|
||||
if key in shown:
|
||||
self.assertIn(f'href="{browse.path(browse.by_key(key))}"', page, key)
|
||||
bare = str(trail.glance(rec))
|
||||
self.assertNotIn("/lists/", bare)
|
||||
|
||||
def test_a_list_that_is_not_shown_is_not_linked(self):
|
||||
recs = self.recs[:2]
|
||||
self.assertIsNone(related.list_link(recs, "loops"))
|
||||
self.assertIsNone(related.list_link(None, "loops"))
|
||||
|
||||
def test_the_foot_of_the_page_offers_similar_and_related_trails(self):
|
||||
body = str(trail.onward(self.recs[0], self.recs))
|
||||
self.assertIn('id="onward-similar"', body)
|
||||
self.assertIn("Similar in length and terrain", body)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,514 @@
|
||||
"""Tests for the machine-readable side of the site: JSON-LD, social cards, the sitemap's dates,
|
||||
robots headers, the 404, the Atom feed, llms.txt and the favicon.
|
||||
|
||||
The JSON-LD is checked against the properties schema.org and Google Search Central document
|
||||
for each type (REQUIRED below, read 2026-11); Google's Rich Results Test itself cannot be run
|
||||
here. The site is built into web/.cache/test-site, as the other page tests do.
|
||||
"""
|
||||
import html
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import unittest
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
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 browse, cards, common, docs, feed, records, regions, seo, site, thumbs # noqa: E402
|
||||
|
||||
OUT = os.path.join(WEB, ".cache", "test-site")
|
||||
SITE = site.load()
|
||||
BASE = SITE.base_url
|
||||
|
||||
# The properties each type must carry: Google's required ones where it has a feature
|
||||
# (BreadcrumbList, ListItem, Dataset), and the ones that make the node say what it is otherwise.
|
||||
REQUIRED = {
|
||||
"ItemPage": ("@id", "url", "name", "mainEntity", "dateModified"),
|
||||
"CollectionPage": ("@id", "url", "name", "mainEntity", "dateModified"),
|
||||
"Place": ("name",),
|
||||
"TouristAttraction": ("@id", "name", "url", "additionalProperty"), # a trail or route
|
||||
"ItemList": ("itemListElement", "numberOfItems"),
|
||||
"BreadcrumbList": ("itemListElement",),
|
||||
"ListItem": ("position", "name"),
|
||||
"WebSite": ("name", "url"),
|
||||
"Organization": ("name", "url", "logo"),
|
||||
"Dataset": ("name", "description", "license", "creator", "distribution", "keywords",
|
||||
"spatialCoverage", "temporalCoverage", "dateModified", "version", "isAccessibleForFree",
|
||||
"variableMeasured", "measurementTechnique"),
|
||||
"DataDownload": ("contentUrl", "encodingFormat"),
|
||||
"PropertyValue": ("name",),
|
||||
}
|
||||
# Things a page about a trail must not claim: the dataset holds none of them.
|
||||
FORBIDDEN = {"aggregateRating", "review", "reviews", "openingHours", "openingHoursSpecification",
|
||||
"priceRange", "offers", "price", "telephone", "ratingValue", "potentialAction"}
|
||||
|
||||
|
||||
def missing(node):
|
||||
"""The required properties a node lacks, by its type; ListItem needs item or url as well."""
|
||||
types = node.get("@type")
|
||||
types = types if isinstance(types, list) else [types]
|
||||
out = []
|
||||
for t in types:
|
||||
out += [k for k in REQUIRED.get(t, ()) if node.get(k) in (None, "", [], {})]
|
||||
if t == "ListItem" and not (node.get("item") or node.get("url")):
|
||||
out.append("item")
|
||||
if t == "Dataset" and "description" in node and not 50 <= len(node["description"]) <= 5000:
|
||||
out.append("description (50 to 5000 characters)")
|
||||
return out
|
||||
|
||||
|
||||
def read(rel):
|
||||
with open(os.path.join(OUT, *rel.split("/")), encoding="utf-8") as f:
|
||||
return f.read()
|
||||
|
||||
|
||||
def ld_blocks(doc):
|
||||
"""The raw text of every JSON-LD script in an HTML document."""
|
||||
return re.findall(r'<script type="application/ld\+json">(.*?)</script>', doc, re.S)
|
||||
|
||||
|
||||
def nodes_of(doc):
|
||||
"""Every JSON-LD node on a page, flattened out of any @graph."""
|
||||
out = []
|
||||
for raw in ld_blocks(doc):
|
||||
obj = json.loads(raw)
|
||||
out += obj["@graph"] if "@graph" in obj else [obj]
|
||||
return out
|
||||
|
||||
|
||||
def walk(obj):
|
||||
"""Every dict inside a JSON-LD value."""
|
||||
if isinstance(obj, dict):
|
||||
yield obj
|
||||
for v in obj.values():
|
||||
yield from walk(v)
|
||||
elif isinstance(obj, list):
|
||||
for v in obj:
|
||||
yield from walk(v)
|
||||
|
||||
|
||||
def meta(doc, key, attr="property"):
|
||||
m = re.search(rf'<meta {attr}="{re.escape(key)}" content="([^"]*)"', doc)
|
||||
return html.unescape(m.group(1)) if m else None
|
||||
|
||||
|
||||
def page_paths():
|
||||
out = []
|
||||
for base, _, names in os.walk(OUT):
|
||||
for n in names:
|
||||
if n.endswith(".html"):
|
||||
out.append(os.path.relpath(os.path.join(base, n), OUT).replace(os.sep, "/"))
|
||||
return sorted(out)
|
||||
|
||||
|
||||
def visible_crumbs(doc):
|
||||
"""(text, href) from the breadcrumb a page shows, read with a regular expression
|
||||
so that it does not share code with the markup under test."""
|
||||
m = re.search(r'<nav class="breadcrumb"[^>]*>(.*?)</nav>', doc, re.S)
|
||||
if not m:
|
||||
return []
|
||||
items = []
|
||||
for li in re.findall(r"<li[^>]*>(.*?)</li>", m.group(1), re.S):
|
||||
href = re.search(r'href="([^"]*)"', li)
|
||||
items.append((" ".join(html.unescape(re.sub(r"<[^>]+>", "", li)).split()), href.group(1) if href else ""))
|
||||
return items
|
||||
|
||||
|
||||
def setUpModule():
|
||||
os.makedirs(os.path.dirname(OUT), exist_ok=True)
|
||||
subprocess.run([sys.executable, os.path.join(WEB, "build.py"), "--out", OUT],
|
||||
check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
|
||||
|
||||
class RequiredPropertiesTest(unittest.TestCase):
|
||||
"""The checker itself: it must fail on a node that lacks what its type needs."""
|
||||
|
||||
def test_missing_properties_are_found(self):
|
||||
self.assertEqual(missing({"@type": ["Place", "TouristAttraction"], "name": "X", "url": "u", "@id": "i"}),
|
||||
["additionalProperty"])
|
||||
self.assertEqual(missing({"@type": "Place"}), ["name"])
|
||||
self.assertIn("name", missing({"@type": "BreadcrumbList", "itemListElement": []}) + ["name"])
|
||||
self.assertEqual(missing({"@type": "BreadcrumbList"}), ["itemListElement"])
|
||||
self.assertEqual(missing({"@type": "ListItem", "position": 1, "name": "A"}), ["item"])
|
||||
self.assertEqual(missing({"@type": "ListItem", "position": 1, "name": "A", "item": "https://x/"}), [])
|
||||
self.assertIn("contentUrl", missing({"@type": "DataDownload", "encodingFormat": "text/csv"}))
|
||||
self.assertTrue(missing({"@type": "Dataset", "name": "n", "description": "too short"}))
|
||||
|
||||
def test_a_trail_without_a_name_would_fail(self):
|
||||
rec = records.load_record(ROOT, "long-trail")
|
||||
rec["derived"]["downloads"] = []
|
||||
node = seo.place_node(rec, SITE)
|
||||
self.assertEqual(missing(node), [])
|
||||
node.pop("additionalProperty")
|
||||
self.assertEqual(missing(node), ["additionalProperty"])
|
||||
|
||||
|
||||
class JsonLdTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.records = records.load_records(ROOT)
|
||||
cls.pages = {p: read(p) for p in page_paths()}
|
||||
|
||||
def test_every_block_parses_and_is_escaped(self):
|
||||
seen = 0
|
||||
for path, doc in self.pages.items():
|
||||
for raw in ld_blocks(doc):
|
||||
seen += 1
|
||||
obj = json.loads(raw)
|
||||
self.assertEqual(obj["@context"], "https://schema.org", path)
|
||||
self.assertNotRegex(raw, r"[<>&]", f"{path}: unescaped character inside JSON-LD")
|
||||
self.assertGreater(seen, 280)
|
||||
|
||||
def test_blocks_are_data_blocks_the_policy_allows(self):
|
||||
"""application/ld+json is not script: the browser does not run it, so script-src 'self'
|
||||
covers every page and nothing here needs a looser policy."""
|
||||
rules = serve.parse_headers(os.path.join(OUT, "_headers"))
|
||||
csp = next(v for pat, hs in rules if pat.match("/") for k, v in hs if k.lower() == "content-security-policy")
|
||||
script_src = re.search(r"script-src ([^;]*)", csp).group(1).split()
|
||||
self.assertEqual(script_src, ["'self'"])
|
||||
self.assertNotIn("unsafe-inline", csp.replace("style-src-attr 'unsafe-inline'", ""))
|
||||
for path, doc in self.pages.items():
|
||||
self.assertNotRegex(doc, r'<script type="application/ld\+json"[^>]*\ssrc=', path)
|
||||
|
||||
def test_every_node_has_what_its_type_requires_and_nothing_forbidden(self):
|
||||
for path, doc in self.pages.items():
|
||||
for top in nodes_of(doc):
|
||||
for node in walk(top):
|
||||
if "@type" in node:
|
||||
self.assertEqual(missing(node), [], f"{path}: {node.get('@type')}")
|
||||
self.assertFalse(FORBIDDEN & set(node), f"{path}: {FORBIDDEN & set(node)}")
|
||||
|
||||
def test_204_trail_pages_carry_a_place(self):
|
||||
count = 0
|
||||
for rec in self.records:
|
||||
path = f"trails/{rec['id']}/index.html"
|
||||
nodes = nodes_of(self.pages[path])
|
||||
places = [n for n in nodes if "Place" in (n["@type"] if isinstance(n["@type"], list) else [n["@type"]])]
|
||||
self.assertEqual(len(places), 1, rec["id"])
|
||||
place = places[0]
|
||||
self.assertIn("TouristAttraction", place["@type"])
|
||||
self.assertEqual(place["name"], rec["name"])
|
||||
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.assertRegex(page["dateModified"], r"^\d{4}-\d{2}-\d{2}$")
|
||||
count += 1
|
||||
self.assertEqual(count, len(self.records))
|
||||
|
||||
def test_a_trail_states_only_what_its_record_holds(self):
|
||||
built_derived = {r["id"]: r["derived"] for r in json.loads(read("data/trails.json"))}
|
||||
for rec in self.records:
|
||||
place = next(n for n in nodes_of(self.pages[f"trails/{rec['id']}/index.html"])
|
||||
if n["@type"] != "ItemPage" and n["@type"] != "BreadcrumbList")
|
||||
props = {(p["name"], p.get("unitCode")): p for p in place["additionalProperty"]}
|
||||
self.assertEqual(props[("Published length", "SMI")]["value"], rec["derived"]["length_mi"], rec["id"])
|
||||
self.assertEqual(props[("Published length", "KMT")]["value"], rec["length_km"], rec["id"])
|
||||
h = rec.get("hike", {})
|
||||
self.assertEqual(("Start", None) in props, bool(h.get("start")), rec["id"])
|
||||
self.assertEqual(("Usual season", None) in props, bool(h.get("season")), rec["id"])
|
||||
self.assertEqual(any(k[0] == "Highest point" for k in props),
|
||||
bool(h.get("high_point_m") or h.get("high_point")), rec["id"])
|
||||
if h.get("official_url"):
|
||||
self.assertIn(h["official_url"], place["sameAs"], rec["id"])
|
||||
else:
|
||||
self.assertNotIn("sameAs", {k: v for k, v in place.items() if k == "sameAs" and
|
||||
any(u == h.get("official_url") for u in v)})
|
||||
if common.is_route(rec):
|
||||
self.assertEqual(props[("Route author", None)]["value"], rec["route"]["creator"], rec["id"])
|
||||
tracks = [d for d in place.get("subjectOf", []) if d["@type"] == "DataDownload"]
|
||||
self.assertEqual(bool(tracks), common.has_line(rec), rec["id"])
|
||||
for d in tracks:
|
||||
self.assertTrue(os.path.isfile(os.path.join(OUT, *d["contentUrl"][len(BASE) + 1:].split("/"))),
|
||||
d["contentUrl"])
|
||||
self.assertTrue(d.get("license") or d.get("usageInfo"), rec["id"])
|
||||
if "geo" in place:
|
||||
self.assertIn(place["geo"]["@type"], ("GeoShape", "GeoCoordinates"))
|
||||
built = built_derived[rec["id"]] # the build adds the track's box to the record
|
||||
self.assertEqual("geo" in place, bool(built.get("bbox") or h.get("start_lonlat") or h.get("end_lonlat")),
|
||||
rec["id"])
|
||||
|
||||
def test_breadcrumbs_equal_the_visible_ones(self):
|
||||
counted = 0
|
||||
for path, doc in self.pages.items():
|
||||
crumbs = visible_crumbs(doc)
|
||||
lists = [n for n in nodes_of(doc) if n["@type"] == "BreadcrumbList"]
|
||||
if not crumbs or 'name="robots" content="noindex"' in doc:
|
||||
self.assertEqual(lists, [], path)
|
||||
continue
|
||||
self.assertEqual(len(lists), 1, path)
|
||||
items = lists[0]["itemListElement"]
|
||||
self.assertEqual([i["name"] for i in items], [t for t, _ in crumbs], path)
|
||||
self.assertEqual([i["position"] for i in items], list(range(1, len(crumbs) + 1)), path)
|
||||
canonical = meta(doc, "og:url")
|
||||
self.assertEqual(items[-1]["item"], canonical, path)
|
||||
for item, (_, href) in zip(items[:-1], crumbs):
|
||||
self.assertEqual(item["item"], BASE + href, path)
|
||||
counted += 1
|
||||
self.assertGreater(counted, 280) # trail, place, list and document pages
|
||||
|
||||
def test_trail_place_and_list_pages_have_breadcrumbs(self):
|
||||
for rec in self.records:
|
||||
self.assertTrue(any(n["@type"] == "BreadcrumbList" for n in nodes_of(self.pages[f"trails/{rec['id']}/index.html"])))
|
||||
for path in self.pages:
|
||||
if path.startswith(("regions/", "lists/")) and path.count("/") == 2:
|
||||
self.assertTrue(any(n["@type"] == "BreadcrumbList" for n in nodes_of(self.pages[path])), path)
|
||||
|
||||
def test_lists_and_places_carry_a_collection_of_what_they_list(self):
|
||||
by_slug, _ = regions.collect_regions(self.records)
|
||||
expected = {f"regions/{slug}/index.html": info["records"] for slug, info in by_slug.items()}
|
||||
for lst, recs in browse.shown(self.records):
|
||||
expected[f"{browse.path(lst).strip('/')}/index.html"] = recs
|
||||
self.assertGreater(len(expected), 70)
|
||||
for path, recs in expected.items():
|
||||
page = next(n for n in nodes_of(self.pages[path]) if n["@type"] == "CollectionPage")
|
||||
listing = page["mainEntity"]
|
||||
self.assertEqual(listing["@type"], "ItemList", path)
|
||||
self.assertEqual(listing["numberOfItems"], len(recs), path)
|
||||
self.assertEqual({i["url"] for i in listing["itemListElement"]},
|
||||
{BASE + common.trail_path(r) for r in recs}, path)
|
||||
self.assertEqual([i["position"] for i in listing["itemListElement"]], list(range(1, len(recs) + 1)), path)
|
||||
self.assertEqual(page["dateModified"], seo.newest(recs), path)
|
||||
|
||||
def test_home_has_website_and_organization_and_the_data_page_has_the_dataset(self):
|
||||
home = nodes_of(self.pages["index.html"])
|
||||
kinds = sorted(n["@type"] for n in home)
|
||||
self.assertEqual(kinds, ["Organization", "WebSite"])
|
||||
org = next(n for n in home if n["@type"] == "Organization")
|
||||
self.assertEqual(org["name"], SITE.name)
|
||||
self.assertEqual(org["url"], BASE + "/")
|
||||
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))
|
||||
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"])
|
||||
sets = [n for n in data if n["@type"] == "Dataset"]
|
||||
self.assertEqual(len(sets), 1)
|
||||
ds = sets[0]
|
||||
self.assertEqual(missing(ds), [])
|
||||
self.assertEqual(ds["license"], "https://creativecommons.org/publicdomain/zero/1.0/")
|
||||
self.assertEqual(ds["dateModified"], seo.newest(self.records))
|
||||
self.assertTrue(re.fullmatch(r"\d{4}-\d{2}-\d{2}/\d{4}-\d{2}-\d{2}", ds["temporalCoverage"]))
|
||||
self.assertEqual({d["contentUrl"].rsplit("/", 1)[1] for d in ds["distribution"]},
|
||||
{n for n, _, _ in docs.BULK_FILES} | set())
|
||||
for d in ds["distribution"]:
|
||||
path = d["contentUrl"][len(BASE) + 1:]
|
||||
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)
|
||||
|
||||
def test_no_wording_the_house_style_forbids(self):
|
||||
for path in ("data/index.html", "index.html", "trails/long-trail/index.html"):
|
||||
text = " ".join(json.dumps(n) for n in nodes_of(self.pages[path]))
|
||||
self.assertNotRegex(text, r"\bline file\b|\btrack line\b", path)
|
||||
|
||||
|
||||
class CardsTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.records = records.load_records(ROOT)
|
||||
|
||||
def test_every_page_has_complete_open_graph_and_a_card_that_exists(self):
|
||||
for path in page_paths():
|
||||
doc = read(path)
|
||||
for key in ("og:title", "og:description", "og:type", "og:site_name", "og:image", "og:image:alt"):
|
||||
self.assertTrue(meta(doc, key), f"{path}: {key}")
|
||||
for key in ("twitter:title", "twitter:description", "twitter:image"):
|
||||
self.assertTrue(meta(doc, key, "name"), f"{path}: {key}")
|
||||
self.assertEqual(meta(doc, "og:image"), meta(doc, "twitter:image", "name"), path)
|
||||
image = meta(doc, "og:image")
|
||||
self.assertTrue(image.startswith(BASE + "/"), f"{path}: {image}")
|
||||
target = os.path.join(OUT, *image[len(BASE) + 1:].split("/"))
|
||||
self.assertTrue(os.path.isfile(target), f"{path}: {image}")
|
||||
self.assertEqual(thumbs.png_size(target), (1200, 630), image)
|
||||
|
||||
def test_each_trail_has_its_own_card_under_200_kb(self):
|
||||
for rec in self.records:
|
||||
doc = read(f"trails/{rec['id']}/index.html")
|
||||
self.assertEqual(meta(doc, "og:image"), f"{BASE}/trails/{rec['id']}/card.png", rec["id"])
|
||||
card = os.path.join(OUT, "trails", rec["id"], "card.png")
|
||||
self.assertEqual(thumbs.png_size(card), (1200, 630), rec["id"])
|
||||
self.assertLess(os.path.getsize(card), 200_000, rec["id"])
|
||||
self.assertIn(rec["name"], meta(doc, "og:image:alt"))
|
||||
self.assertEqual(meta(read("regions/index.html"), "og:image"), f"{BASE}/assets/og.png")
|
||||
|
||||
def test_no_card_is_stale(self):
|
||||
"""A card stores a hash of what it shows (name, length, places). A record that changed
|
||||
since its card was drawn fails here: run web/tools/make_cards.py and commit the cards."""
|
||||
for rec in self.records:
|
||||
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_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")}
|
||||
self.assertEqual(cards, ids)
|
||||
|
||||
|
||||
class SitemapDatesTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.records = records.load_records(ROOT)
|
||||
ns = {"s": "http://www.sitemaps.org/schemas/sitemap/0.9"}
|
||||
root = ET.fromstring(read("sitemap.xml"))
|
||||
cls.dates = {u.find("s:loc", ns).text: (u.find("s:lastmod", ns).text if u.find("s:lastmod", ns) is not None else "")
|
||||
for u in root.findall("s:url", ns)}
|
||||
|
||||
def test_sitemap_urls_are_the_indexable_pages(self):
|
||||
built = set()
|
||||
for path in page_paths():
|
||||
doc = read(path)
|
||||
if 'name="robots" content="noindex"' in doc:
|
||||
continue
|
||||
built.add(BASE + "/" + re.sub(r"index\.html$", "", path))
|
||||
self.assertEqual(set(self.dates), built)
|
||||
|
||||
def test_trail_pages_carry_their_records_date(self):
|
||||
for rec in self.records:
|
||||
self.assertEqual(self.dates[f"{BASE}/trails/{rec['id']}/"], seo.modified(rec), rec["id"])
|
||||
|
||||
def test_every_lastmod_is_a_date_the_data_holds(self):
|
||||
held = {d for r in self.records for d in seo.record_dates(r)}
|
||||
held |= {e[0] for e in feed.entries(docs.read_doc(ROOT, "CHANGELOG.md"))}
|
||||
held |= {str(e["decided"]) for e in __import__("olt.leftout", fromlist=["x"]).load_entries(ROOT)}
|
||||
for url, date in self.dates.items():
|
||||
if date:
|
||||
self.assertRegex(date, r"^\d{4}-\d{2}-\d{2}$", url)
|
||||
self.assertIn(date, held, url)
|
||||
self.assertGreaterEqual(sum(1 for d in self.dates.values() if d), 290)
|
||||
|
||||
def test_a_list_or_place_is_as_new_as_its_newest_trail(self):
|
||||
by_slug, _ = regions.collect_regions(self.records)
|
||||
for slug, info in by_slug.items():
|
||||
self.assertEqual(self.dates[f"{BASE}/regions/{slug}/"], seo.newest(info["records"]), slug)
|
||||
for lst, recs in browse.shown(self.records):
|
||||
if lst.key != "routes":
|
||||
self.assertEqual(self.dates[f"{BASE}{browse.path(lst)}"], seo.newest(recs), lst.key)
|
||||
|
||||
def test_modified_is_the_newest_of_check_and_history(self):
|
||||
rec = {"verification": {"date": "2026-01-02"}, "hike": {"checked": "2026-03-04"},
|
||||
"source": {"source_checked": "2026-02-01"},
|
||||
"history": [{"date": "2026-01-01"}, {"date": "2026-05-06"}]}
|
||||
self.assertEqual(seo.modified(rec), "2026-05-06")
|
||||
rec["history"] = [{"date": "2026-01-01"}]
|
||||
self.assertEqual(seo.modified(rec), "2026-03-04")
|
||||
self.assertEqual(seo.modified({}), "")
|
||||
|
||||
def test_a_page_with_no_date_gets_no_lastmod(self):
|
||||
s = site.Site("N", "T", base_url="https://example.org")
|
||||
xml = seo.sitemap_xml(["/a/", "/b/"], s, {"/a/": "2026-01-01"})
|
||||
self.assertIn("<loc>https://example.org/a/</loc><lastmod>2026-01-01</lastmod>", xml)
|
||||
self.assertIn("<url><loc>https://example.org/b/</loc></url>", xml)
|
||||
|
||||
def test_the_sitemap_does_not_read_the_clock(self):
|
||||
with open(os.path.join(WEB, "olt", "seo.py"), encoding="utf-8") as f:
|
||||
source = f.read()
|
||||
self.assertNotRegex(source, r"import (time|datetime)|from (time|datetime)|\.today\(|\.now\(")
|
||||
|
||||
|
||||
class CrawlerFilesTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.rules = serve.parse_headers(os.path.join(OUT, "_headers"))
|
||||
|
||||
def headers(self, path):
|
||||
out = {}
|
||||
for pattern, hs in self.rules:
|
||||
if pattern.match(path):
|
||||
for name, value in hs:
|
||||
self.assertNotIn(name.lower(), out, f"{path}: {name} set by two rules")
|
||||
out[name.lower()] = value
|
||||
return out
|
||||
|
||||
def test_404_is_noindex_and_not_in_the_sitemap(self):
|
||||
doc = read("404.html")
|
||||
self.assertIn('<meta name="robots" content="noindex">', doc)
|
||||
self.assertNotIn('rel="canonical"', doc)
|
||||
self.assertNotIn("/404.html", read("sitemap.xml"))
|
||||
self.assertEqual(ld_blocks(doc), [])
|
||||
|
||||
def test_raw_files_under_trails_are_noindex_and_data_downloads_are_not(self):
|
||||
raw = {"trail.toml": 0, "release.txt": 0, "map.json": 0, "sketch.json": 0, ".geojson": 0, ".gpx": 0}
|
||||
for base, _, names in os.walk(os.path.join(OUT, "trails")):
|
||||
for n in names:
|
||||
path = "/" + os.path.relpath(os.path.join(base, n), OUT).replace(os.sep, "/")
|
||||
h = self.headers(path)
|
||||
if n in raw or n.endswith((".geojson", ".gpx")):
|
||||
key = n if n in raw else "." + n.rsplit(".", 1)[1]
|
||||
raw[key] += 1
|
||||
self.assertEqual(h.get("x-robots-tag"), "noindex", path)
|
||||
else:
|
||||
self.assertNotIn("x-robots-tag", h, path) # pages, logos, cards
|
||||
self.assertTrue(all(raw.values()), raw)
|
||||
for name in ("trails.csv", "trails.json", "index.geojson", "overview.geojson", "all-gpx.zip", "all-geojson.zip"):
|
||||
self.assertNotIn("x-robots-tag", self.headers(f"/data/{name}"), name)
|
||||
for path in ("/", "/trails/long-trail/", "/feed.xml", "/llms.txt", "/sitemap.xml", "/robots.txt"):
|
||||
self.assertNotIn("x-robots-tag", self.headers(path), path)
|
||||
|
||||
def test_no_header_is_set_twice_for_any_built_file(self):
|
||||
for base, _, names in os.walk(OUT):
|
||||
for n in names:
|
||||
self.headers("/" + os.path.relpath(os.path.join(base, n), OUT).replace(os.sep, "/"))
|
||||
|
||||
|
||||
class FeedAndExtrasTest(unittest.TestCase):
|
||||
def test_atom_feed_is_well_formed_and_from_the_changelog(self):
|
||||
ns = {"a": "http://www.w3.org/2005/Atom"}
|
||||
root = ET.fromstring(read("feed.xml"))
|
||||
self.assertEqual(root.tag, "{http://www.w3.org/2005/Atom}feed")
|
||||
for tag in ("title", "id", "updated", "author"):
|
||||
self.assertIsNotNone(root.find(f"a:{tag}", ns), tag)
|
||||
self.assertEqual(root.find("a:link[@rel='self']", ns).get("href"), f"{BASE}/feed.xml")
|
||||
entries = root.findall("a:entry", ns)
|
||||
changelog = feed.entries(docs.read_doc(ROOT, "CHANGELOG.md"))
|
||||
self.assertEqual(len(entries), min(len(changelog), feed.FEED_MAX))
|
||||
ids = [e.find("a:id", ns).text for e in entries]
|
||||
self.assertEqual(len(set(ids)), len(ids))
|
||||
for e, (date, title, slug, _) in zip(entries, changelog):
|
||||
self.assertEqual(e.find("a:title", ns).text, title)
|
||||
self.assertEqual(e.find("a:updated", ns).text, f"{date}T00:00:00Z")
|
||||
self.assertEqual(e.find("a:link", ns).get("href"), f"{BASE}/data/changelog/#{slug}")
|
||||
self.assertIn(f'id="{slug}"', read("data/changelog/index.html"))
|
||||
self.assertTrue(e.find("a:content", ns).text.strip())
|
||||
self.assertEqual(root.find("a:updated", ns).text, f"{changelog[0][0]}T00:00:00Z")
|
||||
for e in entries: # links in an entry are absolute: a reader has no base
|
||||
self.assertNotRegex(e.find("a:content", ns).text, r'href="/')
|
||||
|
||||
def test_head_links_to_the_feed_and_the_data_page_to_its_files(self):
|
||||
for path in ("index.html", "trails/long-trail/index.html", "data/index.html"):
|
||||
self.assertIn('<link rel="alternate" type="application/atom+xml"', read(path))
|
||||
self.assertIn('href="/feed.xml"', read(path))
|
||||
data = read("data/index.html")
|
||||
self.assertIn('<link rel="alternate" type="application/json" href="/data/trails.json"', data)
|
||||
self.assertIn('<link rel="alternate" type="text/csv" href="/data/trails.csv"', data)
|
||||
self.assertNotIn('type="text/csv"', read("index.html"))
|
||||
|
||||
def test_favicon_ico_is_a_real_icon_at_the_root(self):
|
||||
with open(os.path.join(OUT, "favicon.ico"), "rb") as f:
|
||||
head = f.read(6)
|
||||
self.assertEqual(head[:4], b"\x00\x00\x01\x00") # ICO
|
||||
self.assertGreaterEqual(int.from_bytes(head[4:6], "little"), 1)
|
||||
|
||||
def test_llms_txt_points_at_files_that_exist(self):
|
||||
text = read("llms.txt")
|
||||
self.assertTrue(text.startswith(f"# {SITE.name}\n\n> "))
|
||||
links = re.findall(r"\]\((https://[^)]+)\)", text)
|
||||
self.assertGreater(len(links), 8)
|
||||
for url in links:
|
||||
if url.startswith(BASE + "/"):
|
||||
path = os.path.join(OUT, *url[len(BASE) + 1:].split("/"))
|
||||
self.assertTrue(os.path.exists(path) or os.path.isfile(os.path.join(path, "index.html")), url)
|
||||
self.assertIn("CC0", text)
|
||||
self.assertNotIn("<id>.line", text)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user