Rebuild the site for people browsing trails
The site read like a database. It is now a place to find and read about long trails, and everything on it is still derived from the records. - One kind of thing: a trail. A route is a kind of trail, explained where the word first appears. The navigation is Trails, Places, About. - The home page is the catalogue, with filters for where, length, time, season, terrain, kind, walking, shape and GPX. A filter is offered only when at least a third of the trails have a value for it. - Lists (for example National Scenic Trails and Routes) and a Places page that groups states and provinces into regions. - A trail page leads with what a hiker needs: summary, at a glance, map, downloads, elevation profile and where to go next. The dataset's own fields sit in a collapsed "About this data" section. - The trail list is a compact card on phones and beside the filters, and a column table where it has the full page width. - web/serve.py takes --bind, for viewing from another device. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
1 parent
efb6164737
commit
b817d2097b
21 files changed
+3468
-719
No files matched your search
@@ -0,0 +1,284 @@
|
||||
"""Tests for the computed elevation facts (olt/elevation.py): the At a glance
|
||||
rows, the profile and its part breaks, the caveats, unit switching, the climb
|
||||
sort, the model credit, and the Routes list dropping its repetition.
|
||||
|
||||
These render fixtures; they do not need the built site.
|
||||
"""
|
||||
import copy
|
||||
import html
|
||||
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)
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
from olt import docs, elevation, home, records, regions, site, trail # noqa: E402
|
||||
from test_pages import sample_record # noqa: E402
|
||||
|
||||
GH = site.Site("N", "T", repo_url="https://github.com/o/r")
|
||||
|
||||
SOURCE = {
|
||||
"model": "Example Model", "url": "https://model.example/",
|
||||
"attribution": "Example Model credit, as it gives it.",
|
||||
"zoom": 12, "ground_m_per_pixel_at_40n": 29.2, "sample_spacing_m": 30.0,
|
||||
"smoothing": "Moving average over 90 m of track; ascent and descent counted with a 5 m reversal threshold",
|
||||
"limits": "Computed from a public elevation model, not measured on the ground.",
|
||||
"method_version": 1, "computed": "2026-11-13",
|
||||
}
|
||||
|
||||
|
||||
def elev(**kw):
|
||||
"""A small elevation.json in memory: one part, full coverage, south to north."""
|
||||
data = {
|
||||
"highest": {"m": 2000, "lat": 40.0, "lon": -105.0},
|
||||
"lowest": {"m": 500, "lat": 39.0, "lon": -105.5},
|
||||
"ascent_m": 3000, "descent_m": 2900,
|
||||
"track_km": 100.0, "published_km": 100, "coverage": 1.0,
|
||||
"parts": 1, "orientation": "south-to-north",
|
||||
"profile": [[0, 500], [50, 2000], [100, 800]],
|
||||
"source": copy.deepcopy(SOURCE),
|
||||
}
|
||||
data.update(kw)
|
||||
return data
|
||||
|
||||
|
||||
def rec_with(data=None, hike_table=None):
|
||||
rec = sample_record("X Trail")
|
||||
rec["derived"]["elevation"] = data
|
||||
rec["derived"]["has_line"] = data is not None
|
||||
if data is not None:
|
||||
rec["source"]["line_file"] = "line.geojson"
|
||||
rec["derived"]["files"] = {"line": "x/line.geojson"}
|
||||
if hike_table:
|
||||
rec["hike"] = hike_table
|
||||
return rec
|
||||
|
||||
|
||||
def render(rec):
|
||||
return trail.render(rec, GH)[2]
|
||||
|
||||
|
||||
def text(fragment):
|
||||
return re.sub(r"\s+", " ", html.unescape(re.sub(r"<[^>]+>", " ", fragment)))
|
||||
|
||||
|
||||
def glance_of(body):
|
||||
return body[body.index('<section class="glance'):body.index("</section>", body.index('<section class="glance'))]
|
||||
|
||||
|
||||
def top_part(body):
|
||||
return body[:body.index('<details class="about-data"')]
|
||||
|
||||
|
||||
class GlanceTest(unittest.TestCase):
|
||||
def test_computed_rows_without_a_sourced_high_point(self):
|
||||
t = text(glance_of(render(rec_with(elev()))))
|
||||
self.assertIn("High point 2,000 m 6,562 ft Computed from the track.", t)
|
||||
self.assertIn("Low point 500 m 1,640 ft Computed from the track.", t)
|
||||
# descent within a few percent of the climb is not shown
|
||||
self.assertIn("Climb 3,000 m 9,843 ft Computed from the track, walking south to north.", t)
|
||||
self.assertNotIn("Descent", t)
|
||||
|
||||
def test_descent_shown_when_it_differs(self):
|
||||
t = text(glance_of(render(rec_with(elev(descent_m=1000)))))
|
||||
self.assertIn("Descent: 1,000 m 3,281 ft", t)
|
||||
self.assertIn("walking south to north", t)
|
||||
self.assertFalse(elevation.show_descent(elev(ascent_m=1000, descent_m=951)))
|
||||
self.assertTrue(elevation.show_descent(elev(ascent_m=1000, descent_m=949)))
|
||||
|
||||
def test_sourced_high_point_is_kept(self):
|
||||
rec = rec_with(elev(), {"high_point": "Example Peak", "high_point_m": 2025, "checked": "2026-11-13"})
|
||||
t = text(glance_of(render(rec)))
|
||||
self.assertIn("High point Example Peak 2,025 m 6,644 ft", t)
|
||||
self.assertNotIn("2,000 m", t) # the computed highest does not replace it
|
||||
# the computed low point and climb still appear, marked as computed
|
||||
self.assertIn("Low point 500 m", t)
|
||||
self.assertIn("Climb 3,000 m", t)
|
||||
|
||||
def test_sourced_name_without_an_elevation_stays_as_it_was(self):
|
||||
rec = rec_with(elev(), {"high_point": "Example Peak", "checked": "2026-11-13"})
|
||||
t = text(glance_of(render(rec)))
|
||||
self.assertIn("High point Example Peak", t)
|
||||
self.assertNotIn("2,000 m", t)
|
||||
|
||||
def test_sea_level_low_point(self):
|
||||
data = elev(lowest={"m": 0, "lat": 43.0, "lon": -124.0})
|
||||
t = text(glance_of(render(rec_with(data))))
|
||||
self.assertIn("Low point 0 m 0 ft Sea level. Computed from the track.", t)
|
||||
self.assertIn("low point of sea level", elevation.summary_sentence(data))
|
||||
|
||||
def test_loop_climb_has_no_direction(self):
|
||||
rec = rec_with(elev(), {"shape": "loop", "checked": "2026-11-13"})
|
||||
t = text(glance_of(render(rec)))
|
||||
self.assertIn("Climb 3,000 m 9,843 ft Computed from the track.", t)
|
||||
self.assertNotIn("walking south to north", text(top_part(render(rec))))
|
||||
|
||||
|
||||
class CaveatTest(unittest.TestCase):
|
||||
def test_partial_coverage(self):
|
||||
for cov, shown in ((0.84, True), (0.85, False), (1.0, False)):
|
||||
data = elev(coverage=cov, track_km=cov * 100)
|
||||
t = text(top_part(render(rec_with(data))))
|
||||
if shown:
|
||||
self.assertIn("for the track only", t)
|
||||
self.assertIn(f"about {round(cov * 100)}% of the published length", t)
|
||||
else:
|
||||
self.assertNotIn("for the track only", t, cov)
|
||||
self.assertEqual(elevation.coverage_percent(elev(coverage=0.002)), "less than 1%")
|
||||
|
||||
def test_over_coverage(self):
|
||||
for cov, shown in ((1.16, True), (1.15, False)):
|
||||
data = elev(coverage=cov, track_km=cov * 100)
|
||||
t = text(top_part(render(rec_with(data))))
|
||||
if shown:
|
||||
self.assertIn("the climb is overstated", t)
|
||||
self.assertIn("side trails or alternates", t)
|
||||
else:
|
||||
self.assertNotIn("overstated", t, cov)
|
||||
|
||||
def test_many_parts_draw_no_profile(self):
|
||||
for parts, drawn in ((elevation.PROFILE_MAX_PARTS, True), (elevation.PROFILE_MAX_PARTS + 1, False)):
|
||||
body = render(rec_with(elev(parts=parts)))
|
||||
self.assertEqual("elev-profile__line" in body, drawn, parts)
|
||||
if not drawn:
|
||||
self.assertIn("No profile is drawn", text(body))
|
||||
self.assertIn(f"{parts} in the elevation sampling", text(body))
|
||||
# the figures are still there
|
||||
self.assertIn("Climb 3,000 m", text(glance_of(body)))
|
||||
|
||||
|
||||
class ProfileTest(unittest.TestCase):
|
||||
# two parts: the point at 50 km ends the first, the next at 50 km starts the second
|
||||
PROFILE = [[0, 500], [25, 900], [50, 700], [50, 1200], [75, 2000], [100, 800]]
|
||||
|
||||
def test_breaks_at_part_boundaries(self):
|
||||
segs = elevation.segments(self.PROFILE, [50])
|
||||
self.assertEqual([[p[0] for p in s] for s in segs], [[0, 25, 50], [50, 75, 100]])
|
||||
data = elev(parts=2, part_starts_km=[50], profile=self.PROFILE)
|
||||
svg = str(elevation.profile_svg(data))
|
||||
path = re.search(r'<path class="elev-profile__line" d="([^"]*)"', svg).group(1)
|
||||
self.assertEqual(path.count("M"), 2) # one subpath per part, never joined
|
||||
self.assertIn("The line breaks where the track does", text(render(rec_with(data))))
|
||||
|
||||
def test_repeated_part_starts_each_break(self):
|
||||
profile = [[0, 1], [10, 2], [10, 3], [10, 4], [20, 5]]
|
||||
self.assertEqual(len(elevation.segments(profile, [10, 10])), 3)
|
||||
|
||||
def test_axes_in_both_units(self):
|
||||
svg = str(elevation.profile_svg(elev()))
|
||||
km = svg[svg.index('<g class="len__km">'):svg.index('<g class="len__mi">')]
|
||||
mi = svg[svg.index('<g class="len__mi">'):]
|
||||
self.assertIn("Distance along the track (km)", km)
|
||||
self.assertIn("Elevation (m)", km)
|
||||
self.assertIn("2,000", km) # a metre tick reaches the high point
|
||||
self.assertIn("Distance along the track (mi)", mi)
|
||||
self.assertIn("Elevation (ft)", mi)
|
||||
self.assertNotIn("style=", svg)
|
||||
# CSS shows one system, by the same data-units preference as lengths
|
||||
with open(os.path.join(WEB, "assets", "style.css"), encoding="utf-8") as f:
|
||||
css = f.read()
|
||||
self.assertIn(".elev-profile .len__mi { display: none; }", css)
|
||||
self.assertIn(':root[data-units="mi"] .elev-profile .len__mi { display: inline; }', css)
|
||||
self.assertIn(':root[data-units="mi"] .elev-profile .len__km { display: none; }', css)
|
||||
|
||||
def test_text_alternative_states_the_facts(self):
|
||||
svg = str(elevation.profile_svg(elev()))
|
||||
label = html.unescape(re.search(r'aria-label="([^"]*)"', svg).group(1))
|
||||
for want in ("3,000 m (9,843 ft)", "100.0 km (62 mi)", "500 m (1,640 ft)",
|
||||
"2,000 m (6,562 ft)", "walking south to north"):
|
||||
self.assertIn(want, label, want)
|
||||
# the same sentence is the visible caption
|
||||
self.assertIn(label, text(render(rec_with(elev()))))
|
||||
|
||||
def test_no_elevation_file_shows_nothing(self):
|
||||
body = render(rec_with(None))
|
||||
for absent in ("Elevation profile", "Low point", "Climb", 'id="elevation-data-title"',
|
||||
'id="elevation-title"', "detail--with-profile"):
|
||||
self.assertNotIn(absent, body, absent)
|
||||
self.assertIn("At a glance", body) # and the page is otherwise whole
|
||||
|
||||
|
||||
class AboutTest(unittest.TestCase):
|
||||
def test_method_credit_and_every_value(self):
|
||||
data = elev(parts=2, part_starts_km=[50], profile=ProfileTest.PROFILE)
|
||||
body = render(rec_with(data))
|
||||
about = body[body.index('<details class="about-data"'):]
|
||||
t = text(about)
|
||||
self.assertIn('id="elevation-data-title"', about)
|
||||
for want in ("computed from the trail’s track and Example Model",
|
||||
"A point was taken every 30 m along each part of the track",
|
||||
"Example Model credit, as it gives it.",
|
||||
"Highest point on the track 2,000 m", "At 40.00000, -105.00000",
|
||||
"Lowest point on the track 500 m", "Total climb 3,000 m",
|
||||
"Total descent 2,900 m", "Length sampled 100.0 km",
|
||||
"Coverage 1.000", "Parts 2", "Part starts 50.0 km",
|
||||
"Computed 2026-11-13",
|
||||
"Computed from a public elevation model, not measured on the ground."):
|
||||
self.assertIn(want, t, want)
|
||||
self.assertIn('href="https://model.example/"', about)
|
||||
|
||||
def test_model_credit_on_the_sources_page(self):
|
||||
_, _, body = docs.sources_page([rec_with(elev()), rec_with(None)], GH, ROOT)
|
||||
self.assertIn("Elevation model", body)
|
||||
self.assertIn("Example Model credit, as it gives it.", body)
|
||||
self.assertIn('href="https://model.example/"', body)
|
||||
|
||||
|
||||
class CatalogueTest(unittest.TestCase):
|
||||
def test_climb_in_the_row_and_the_sort(self):
|
||||
row = home.entry(rec_with(elev()))
|
||||
self.assertIn('data-climb="3000"', row)
|
||||
self.assertIn("<dt>Climb</dt>", row)
|
||||
self.assertIn("3,000 m", text(row))
|
||||
self.assertIn("computed", text(row))
|
||||
row_none = home.entry(rec_with(None))
|
||||
self.assertIn('data-climb=""', row_none)
|
||||
self.assertNotIn("<dt>Climb</dt>", row_none)
|
||||
self.assertIn('<option value="climb">Most climb first</option>', home.SORT_SELECT)
|
||||
with open(os.path.join(WEB, "assets", "app.js"), encoding="utf-8") as f:
|
||||
js = f.read()
|
||||
self.assertIn("key === 'climb'", js)
|
||||
# a trail with no computed climb sorts last, not first
|
||||
self.assertIn("a.dataset.climb === '' ? -1", js)
|
||||
self.assertIn("return bc - ac", js)
|
||||
|
||||
|
||||
class RoutesListTest(unittest.TestCase):
|
||||
def _route(self):
|
||||
rec = rec_with(None)
|
||||
rec["derived"]["kind"] = "route"
|
||||
rec["kind"] = "route"
|
||||
rec["route"] = {"creator": "A Person", "year": 1970, "line_policy": "sold"}
|
||||
rec["guide"] = []
|
||||
return rec
|
||||
|
||||
def test_no_repetition_under_by_author_headings(self):
|
||||
rec = self._route()
|
||||
plain = home.entry(rec)
|
||||
self.assertIn("Route by A Person, 1970", text(plain))
|
||||
self.assertIn('<a class="tag tag--route" href="/routes/">Route</a>', plain)
|
||||
_, _, body, _ = regions.routes_page([rec], GH)
|
||||
self.assertIn("By A Person", text(body))
|
||||
self.assertNotIn("entry__by", body)
|
||||
self.assertNotIn("tag--route", body)
|
||||
|
||||
|
||||
class LoaderTest(unittest.TestCase):
|
||||
def test_real_records(self):
|
||||
pct = records.load_record(ROOT, "pacific-crest")
|
||||
data = pct["derived"]["elevation"]
|
||||
self.assertIsNotNone(data)
|
||||
self.assertGreater(data["ascent_m"], 0)
|
||||
self.assertIn("Terrain Tiles", data["source"]["attribution"])
|
||||
none_rec = records.load_record(ROOT, "sierra-high-route")
|
||||
self.assertIsNone(none_rec["derived"]["elevation"])
|
||||
# elevation facts are derived, so they never appear as record fields
|
||||
self.assertNotIn("ascent_m", text(trail.raw_record(pct)))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
+48
-39
@@ -13,7 +13,7 @@ ROOT = os.path.dirname(WEB)
|
||||
sys.path.insert(0, WEB)
|
||||
|
||||
import serve # noqa: E402
|
||||
from olt import docs, home, records, regions as regions_mod, seo, site, words # noqa: E402
|
||||
from olt import common, docs, facets, home, records, regions as regions_mod, seo, site, words # noqa: E402
|
||||
|
||||
OUT = os.path.join(WEB, ".cache", "test-site")
|
||||
|
||||
@@ -83,7 +83,7 @@ class ExtraPagesTest(unittest.TestCase):
|
||||
|
||||
def test_no_dead_internal_links_in_added_pages(self):
|
||||
import re
|
||||
for rel in ("regions/index.html", "routes/index.html", "sources/index.html",
|
||||
for rel in ("regions/index.html", "routes/index.html", "lists/index.html", "sources/index.html",
|
||||
"logos/index.html", "about/index.html", "data/index.html",
|
||||
"data/schema/index.html", "data/changelog/index.html"):
|
||||
html = read_out(rel)
|
||||
@@ -107,39 +107,31 @@ class ExtraPagesTest(unittest.TestCase):
|
||||
self.assertIn('href="/regions/us-vt/"', page)
|
||||
|
||||
|
||||
def test_country_and_region_counts_match_the_regions_pages(self):
|
||||
def test_where_counts_match_the_place_pages(self):
|
||||
home_doc = read_out("index.html")
|
||||
index = read_out("regions/index.html")
|
||||
by_slug, canada_wide = regions_mod.collect_regions(self.records)
|
||||
for country, label in (("US", "United States"), ("CA", "Canada")):
|
||||
shown = int(re.search(rf'value="{country}"><span>{label} \((\d+)\)</span>', home_doc).group(1))
|
||||
on_index = int(re.search(rf'data-country-count="{country}">(\d+)<', index).group(1))
|
||||
listed = set()
|
||||
for slug, info in by_slug.items():
|
||||
if info["country"] == country:
|
||||
listed |= set(entry_ids(read_out(f"regions/{slug}/index.html")))
|
||||
if country == "CA":
|
||||
listed |= {r["id"] for r in canada_wide}
|
||||
self.assertEqual(shown, on_index, country)
|
||||
self.assertEqual(shown, len(listed), country)
|
||||
# every row of those records says it touches the country
|
||||
for tid in listed:
|
||||
attrs = re.search(rf'<li class="entry" data-id="{tid}"([^>]*)>', home_doc).group(1)
|
||||
self.assertIn(country, re.search(r'data-countries="([^"]*)"', attrs).group(1).split(), tid)
|
||||
self.assertIn('data-countries="US CA"', re.search(
|
||||
r'<li class="entry" data-id="eastern-continental-trail"[^>]*>', home_doc).group(0))
|
||||
self.assertIn('data-countries="US CA"', re.search(
|
||||
r'<li class="entry" data-id="great-plains-trail"[^>]*>', home_doc).group(0))
|
||||
# each region option's count is the number of records on that region's page
|
||||
for value, n in re.findall(r'<option value="((?:US|CA)-[A-Z]{2})">[^<(]+\((\d+)\)</option>', home_doc):
|
||||
by_slug, across = regions_mod.collect_regions(self.records)
|
||||
# each state or province option's count is the number of trails on its place page
|
||||
found = re.findall(r'<option value="((?:US|CA)-[A-Z]{2})">[^<(]+\((\d+)\)</option>', home_doc)
|
||||
self.assertEqual({v for v, _ in found}, {i["key"] for i in by_slug.values()})
|
||||
for value, n in found:
|
||||
page = read_out(f"regions/{value.lower()}/index.html")
|
||||
self.assertEqual(int(n), len(entry_ids(page)), value)
|
||||
canada = re.search(r'<option value="CA-\*">All provinces and territories \((\d+)\)</option>', home_doc)
|
||||
self.assertEqual(int(canada.group(1)), len(canada_wide))
|
||||
self.assertIn('href="/?region=CA-*"', index)
|
||||
# and the rows that say they are there
|
||||
self.assertEqual(int(n), len(re.findall(rf'data-where="[^"]*\b{value}\b', home_doc)), value)
|
||||
for country, label in (("US", "United States"), ("CA", "Canada")):
|
||||
n = int(re.search(rf'<option value="{country}">{label} \((\d+)\)</option>', home_doc).group(1))
|
||||
self.assertEqual(n, sum(1 for r in self.records if country in common.countries(r)), country)
|
||||
for g, name, _ in facets.PLACE_GROUPS:
|
||||
m = re.search(rf'<option value="g:{g}">All of {re.escape(name)} \((\d+)\)</option>', home_doc)
|
||||
n = sum(1 for r in self.records if g in facets.place_groups(r))
|
||||
self.assertEqual(int(m.group(1)) if m else 0, n, g)
|
||||
self.assertTrue(across)
|
||||
self.assertIn('id="across-canada"', read_out("regions/index.html"))
|
||||
self.assertIn('id="canada-wide"', read_out("regions/index.html")) # the old anchor still lands
|
||||
|
||||
def test_list_pages_share_the_home_list(self):
|
||||
for rel in ("index.html", "regions/us-co/index.html", "routes/index.html"):
|
||||
for rel in ("index.html", "regions/us-co/index.html", "routes/index.html",
|
||||
"lists/national-scenic-trails/index.html"):
|
||||
doc = read_out(rel)
|
||||
results = doc[doc.index('<div class="results">'):]
|
||||
for part in ('<div class="list-head" aria-hidden="true">', '<ol class="entries"',
|
||||
@@ -148,9 +140,9 @@ class ExtraPagesTest(unittest.TestCase):
|
||||
scale = re.search(r'<div class="list-head".*?</div>', results, re.S).group(0)
|
||||
self.assertEqual(scale.count('class="len__km"'), 3, rel)
|
||||
self.assertEqual(scale.count('class="len__mi"'), 3, rel)
|
||||
for name in ("Length", "Time", "GPX"):
|
||||
self.assertIn(f"<span>{name}", scale, rel)
|
||||
self.assertNotIn('class="route-item"', read_out("routes/index.html"))
|
||||
co = read_out("regions/us-co/index.html")
|
||||
self.assertIn('<a href="/?region=US-CO&line=1">With a track</a>', co)
|
||||
|
||||
def test_routes_page_rows_carry_their_guides(self):
|
||||
doc = read_out("routes/index.html")
|
||||
@@ -160,18 +152,35 @@ class ExtraPagesTest(unittest.TestCase):
|
||||
row = re.search(rf'<li class="entry" data-id="{r["id"]}".*?\n</li>', doc, re.S).group(0)
|
||||
for g in r["guide"]:
|
||||
self.assertIn(f'href="{html.escape(g["url"], quote=True)}"', row, r["id"])
|
||||
# says what a route is, in the one definition, and no longer explains track policies
|
||||
self.assertIn(html.escape(facets.ROUTE_DEFINITION, quote=True), doc)
|
||||
self.assertNotIn("track policies", doc.lower())
|
||||
self.assertNotIn("policy-scale", doc)
|
||||
|
||||
def test_home_finder_layout(self):
|
||||
doc = read_out("index.html")
|
||||
form = doc[doc.index('<form class="filters"'):doc.index("</form>")]
|
||||
self.assertIn('<details class="filters__more">', form)
|
||||
self.assertNotIn("filters__more\" open", form)
|
||||
# the line checkbox comes straight after the search field, outside the details
|
||||
self.assertLess(form.index('name="line"'), form.index("<details"))
|
||||
self.assertLess(form.index('id="q"'), form.index('name="line"'))
|
||||
self.assertIn('<a class="button button--primary hero__cta" href="#q">Find a trail</a>', doc)
|
||||
self.assertIn("No records match these filters.", doc)
|
||||
steps = [int(v) for v in re.findall(r'<option value="(\d+)">', form[form.index('id="max"'):])]
|
||||
self.assertIn("No trails match these filters.", doc)
|
||||
more = form[form.index('<details class="filters__more">'):]
|
||||
first = form[:form.index('<details class="filters__more">')]
|
||||
# the first-rank filters in view, Walking, Shape and GPX behind "More"
|
||||
for name in ("q", "where", "min", "max", "time", "kind"):
|
||||
self.assertIn(f'name="{name}"', first, name)
|
||||
for name in ("gpx",):
|
||||
self.assertIn(f'name="{name}"', more, name)
|
||||
for name, key in (("month", "season"), ("terrain", "terrain")):
|
||||
self.assertEqual(f'name="{name}"' in first, facets.offered(self.records, key), name)
|
||||
for name, key in (("walking", "walking"), ("shape", "shape")):
|
||||
self.assertEqual(f'name="{name}"' in more, facets.offered(self.records, key), name)
|
||||
# no dataset filters
|
||||
for name in ("tier", "policy", "designated", "line", "country", "region"):
|
||||
self.assertNotIn(f'name="{name}"', form, name)
|
||||
# the map is in the tool, beside the list it filters
|
||||
main = doc[doc.index('<div class="finder__main">'):]
|
||||
self.assertLess(main.index('data-map="overview"'), main.index('<ol class="entries" id="entries">'))
|
||||
steps = [int(v) for v in re.findall(r'<option value="(\d+)">', form[form.index('id="max"'):form.index("</select>", form.index('id="max"'))])]
|
||||
self.assertGreaterEqual(steps[-1], max(r["length_km"] for r in self.records))
|
||||
self.assertEqual(home.length_steps(self.records)[:11], list(home.LENGTH_STEPS))
|
||||
|
||||
@@ -193,7 +202,7 @@ class ExtraPagesTest(unittest.TestCase):
|
||||
# a record's "none (no line included)" is shown in words, not as the raw value
|
||||
self.assertIn("<td>None (no track included)</td>", page)
|
||||
self.assertNotIn("none (no line included)", page)
|
||||
self.assertEqual(page.count('<th scope="col">Trails and routes</th>'), 2)
|
||||
self.assertEqual(page.count('<th scope="col">Trails</th>'), 2)
|
||||
self.assertNotRegex(page, r'<td><a href="/trails/[^"]+/">[^<]*</a>, <a')
|
||||
|
||||
def test_data_page_licences_from_the_records(self):
|
||||
|
||||
@@ -0,0 +1,318 @@
|
||||
"""Tests for the site's taxonomy and vocabulary (olt/facets.py and the pages that use it):
|
||||
each attribute's name and values, the time estimate, the place grouping, filtering
|
||||
with missing values and the coverage threshold, one word for one thing on every
|
||||
browsing page, and the URLs the live site has always had.
|
||||
|
||||
The fixture tests need no built site; BuiltVocabularyTest builds it (as test_pages does).
|
||||
"""
|
||||
import html
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
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 facets, home, records, trail, words # noqa: E402
|
||||
from test_hike import GH, fake, text, top_part # noqa: E402
|
||||
|
||||
OUT = os.path.join(WEB, ".cache", "test-site")
|
||||
|
||||
|
||||
def route(i=1, policy="sold", **kw):
|
||||
rec = fake(i, **kw)
|
||||
rec["kind"] = "route"
|
||||
rec["derived"]["kind"] = "route"
|
||||
rec["route"] = {"creator": "Andrew Skurka", "year": 2018, "line_policy": policy}
|
||||
rec["guide"] = [{"title": "Guide", "author": "Andrew Skurka", "access": "purchase",
|
||||
"url": "https://guide.example/", "format": "book"}]
|
||||
return rec
|
||||
|
||||
|
||||
class AttributeTest(unittest.TestCase):
|
||||
def test_names(self):
|
||||
self.assertEqual((facets.WHERE, facets.LENGTH, facets.TIME, facets.SEASON, facets.TERRAIN,
|
||||
facets.KIND, facets.WALKING, facets.SHAPE, facets.GPX),
|
||||
("Where", "Length", "Time", "Season", "Terrain", "Kind", "Walking", "Shape", "GPX"))
|
||||
|
||||
def test_values(self):
|
||||
self.assertEqual(list(facets.TERRAIN_VALUES), ["alpine", "forest", "desert", "coast", "prairie",
|
||||
"canyon", "tundra", "lakes", "farmland"])
|
||||
self.assertEqual(facets.WALKING_VALUES, {"trail": "On trail", "trail-and-road": "Trail and road",
|
||||
"some-cross-country": "Some cross-country",
|
||||
"mostly-cross-country": "Mostly cross-country"})
|
||||
self.assertEqual(facets.SHAPES, {"point-to-point": "End to end", "loop": "Loop", "network": "Network"})
|
||||
self.assertEqual(facets.KINDS, {"trail": "Official trail", "route": "Route"})
|
||||
self.assertEqual([label for _, label, _ in facets.TIME_BANDS],
|
||||
["A week or less", "One to two weeks", "Two to four weeks", "One to three months",
|
||||
"More than three months"])
|
||||
self.assertEqual(facets.ROUTE_DEFINITION,
|
||||
"A route is a trail that a hiker worked out and published. No agency or association "
|
||||
"looks after it as one trail, and there may be no signs for it.")
|
||||
|
||||
def test_kind_and_route_line(self):
|
||||
self.assertEqual(facets.kind(fake(1)), "trail")
|
||||
self.assertEqual(facets.route_by(fake(1)), "")
|
||||
r = route()
|
||||
self.assertEqual(facets.kind(r), "route")
|
||||
self.assertEqual(facets.route_by(r), "Route by Andrew Skurka, 2018")
|
||||
del r["route"]["year"]
|
||||
self.assertEqual(facets.route_by(r), "Route by Andrew Skurka")
|
||||
|
||||
def test_walking_is_not_kind(self):
|
||||
# a route on maintained trail says so; an official trail can have road walks
|
||||
r = route(hike={"travel": "trail"})
|
||||
self.assertEqual(facets.walking(r), "trail")
|
||||
t = fake(2, hike={"travel": "trail-and-road"})
|
||||
self.assertEqual(facets.kind(t), "trail")
|
||||
self.assertEqual(facets.walking(t), "trail-and-road")
|
||||
page = text(top_part(trail.render(r, GH)[2]))
|
||||
self.assertIn("Walking On trail", page)
|
||||
self.assertIn("Route by Andrew Skurka, 2018", page)
|
||||
self.assertIn("What is a route?", page)
|
||||
self.assertIn(facets.ROUTE_DEFINITION, page)
|
||||
|
||||
def test_gpx_status(self):
|
||||
cases = [(fake(1), "elsewhere"), (route(policy="open"), "free"), (route(policy="sold"), "sold"),
|
||||
(route(policy="withheld"), "unpublished"), (route(policy="unclear"), "elsewhere")]
|
||||
for rec, want in cases:
|
||||
self.assertEqual(facets.gpx(rec), want, rec.get("route"))
|
||||
from test_hike import with_line
|
||||
partial = with_line(fake(1))
|
||||
self.assertEqual(facets.gpx(partial), "partial")
|
||||
whole = with_line(fake(1))
|
||||
whole["verification"]["difference_percent"] = -2.0
|
||||
self.assertEqual(facets.gpx(whole), "here")
|
||||
self.assertEqual(set(facets.GPX_STATUS.values()),
|
||||
{"GPX to download here", "Partial GPX to download here", "Free from its author",
|
||||
"Sold by its author", "Not published", "Not here, see the official site"})
|
||||
|
||||
def test_designation_badge_only_for_nst(self):
|
||||
self.assertIn("National Scenic Trail", home.entry(fake(1, tier="national")))
|
||||
for tier in ("regional", "short", "deferred", "candidate"):
|
||||
self.assertNotIn("tag--", home.entry(fake(1, tier=tier)), tier)
|
||||
|
||||
|
||||
class TimeTest(unittest.TestCase):
|
||||
def test_stated(self):
|
||||
rec = fake(1, hike={"days": [150, 210]})
|
||||
self.assertEqual(facets.time_days(rec), (150, 210, False))
|
||||
self.assertEqual(facets.time_text(rec), "5 to 7 months")
|
||||
self.assertEqual(facets.estimate_note(rec), "")
|
||||
self.assertEqual(facets.time_band(rec), "long")
|
||||
|
||||
def test_estimate_from_length(self):
|
||||
rec = fake(1, km=300) # 300 km at 20 to 30 km a day: 10 to 15 days
|
||||
self.assertEqual(facets.time_days(rec), (10, 15, True))
|
||||
self.assertEqual(facets.time_text(rec), "About 1 to 2 weeks")
|
||||
self.assertEqual(facets.estimate_note(rec), "Estimated from the length, at 20 to 30 km (12 to 19 mi) a day.")
|
||||
self.assertEqual(facets.time_band(rec), "two-weeks")
|
||||
# cross-country is slower: 12 to 20 km a day
|
||||
rec = fake(2, km=300, hike={"travel": "mostly-cross-country"})
|
||||
self.assertEqual(facets.time_days(rec), (15, 25, True))
|
||||
self.assertIn("12 to 20 km", facets.estimate_note(rec))
|
||||
self.assertEqual(facets.time_band(rec), "month")
|
||||
|
||||
def test_every_trail_has_a_time_and_its_label(self):
|
||||
for rec in records.load_records(ROOT):
|
||||
lo, hi, est = facets.time_days(rec)
|
||||
self.assertTrue(0 < lo <= hi, rec["id"])
|
||||
self.assertIn(facets.time_band(rec), facets.TIME_LABEL, rec["id"])
|
||||
self.assertEqual(bool(facets.estimate_note(rec)), est, rec["id"])
|
||||
row = text(home.entry(fake(1, km=300)))
|
||||
self.assertIn("About 1 to 2 weeks estimate", row)
|
||||
self.assertNotIn("estimate", text(home.entry(fake(1, hike={"days": [4, 6]}))))
|
||||
|
||||
def test_bands(self):
|
||||
self.assertEqual(facets.time_band(fake(1, hike={"days": [5, 8]})), "week") # middle 6.5 days
|
||||
self.assertEqual(facets.time_band(fake(1, hike={"days": [7, 21]})), "two-weeks")
|
||||
self.assertEqual(facets.time_band(fake(1, hike={"days": [20, 35]})), "month")
|
||||
|
||||
|
||||
class PlaceTest(unittest.TestCase):
|
||||
def test_every_code_in_exactly_one_group(self):
|
||||
keys = [k for _, _, ks in facets.PLACE_GROUPS for k in ks]
|
||||
self.assertEqual(len(keys), len(set(keys)))
|
||||
every = {f"US-{c}" for c in words.US_STATES} | {f"CA-{c}" for c in words.CA_PROVINCES}
|
||||
self.assertEqual(set(keys), every)
|
||||
|
||||
def test_every_code_the_records_use(self):
|
||||
for rec in records.load_records(ROOT):
|
||||
keys = facets.place_keys(rec)
|
||||
self.assertTrue(keys, rec["id"])
|
||||
for key in keys:
|
||||
self.assertTrue(key in facets.GROUP_OF or key == facets.ACROSS_CANADA, f"{rec['id']}: {key}")
|
||||
self.assertTrue(facets.place_groups(rec), rec["id"])
|
||||
|
||||
def test_tokens(self):
|
||||
rec = fake(1, regions=["AZ", "NM"])
|
||||
self.assertEqual(facets.where_tokens(rec), ["US", "US-AZ", "US-NM", "g:southwest"])
|
||||
across = fake(2, regions=[words.ALL_CANADA], country="CA")
|
||||
self.assertEqual(facets.place_keys(across), ["CA-*"])
|
||||
self.assertEqual(set(facets.place_groups(across)),
|
||||
{"north", "western-canada", "central-canada", "atlantic-canada"})
|
||||
# a US trail that names a province is in that province's group
|
||||
ect = fake(3, regions=["ME", "QC", "NB"])
|
||||
self.assertEqual(facets.place_keys(ect), ["US-ME", "CA-QC", "CA-NB"])
|
||||
self.assertIn("atlantic-canada", facets.place_groups(ect))
|
||||
|
||||
def test_breadcrumb_by_place(self):
|
||||
body = trail.render(fake(1, regions=["CO"]), GH)[2]
|
||||
crumbs = body[body.index('<nav class="breadcrumb"'):body.index("</nav>")]
|
||||
self.assertIn('<a href="/regions/">Places</a>', crumbs)
|
||||
self.assertIn('<a href="/regions/#mountain-west">Mountain West</a>', crumbs)
|
||||
self.assertIn('<a href="/regions/us-co/">Colorado</a>', crumbs)
|
||||
|
||||
|
||||
class MissingValuesTest(unittest.TestCase):
|
||||
def recs(self, n_with, n_without):
|
||||
return ([fake(i, hike={"months": [7, 8], "season": "July and August", "terrain": ["alpine"]})
|
||||
for i in range(n_with)] + [fake(100 + i) for i in range(n_without)])
|
||||
|
||||
def test_coverage_threshold(self):
|
||||
self.assertTrue(facets.offered(self.recs(4, 8), "season")) # one third: offered
|
||||
self.assertFalse(facets.offered(self.recs(3, 8), "season")) # less: not offered
|
||||
form = home.finder_form(self.recs(3, 8))
|
||||
self.assertNotIn('name="month"', form)
|
||||
self.assertNotIn('name="terrain"', form)
|
||||
form = home.finder_form(self.recs(4, 8))
|
||||
self.assertIn('name="month"', form)
|
||||
self.assertIn('name="terrain"', form)
|
||||
|
||||
def test_missing_count_is_said(self):
|
||||
form = home.finder_form(self.recs(10, 12))
|
||||
self.assertIn('data-missing="season" hidden>12 trails have no season on file.', form)
|
||||
self.assertIn('data-missing="terrain" hidden>12 trails have no terrain on file.', form)
|
||||
self.assertEqual(facets.missing_text(1, "season"), "1 trail has no season on file.")
|
||||
self.assertEqual(facets.missing_text(0, "season"), "")
|
||||
# full coverage: no note
|
||||
self.assertNotIn('data-missing="season"', home.finder_form(self.recs(5, 0)))
|
||||
|
||||
def test_rows_without_a_value_carry_none(self):
|
||||
# the script leaves out a row whose data-months is empty while a month is chosen
|
||||
row = home.entry(fake(1))
|
||||
self.assertIn('data-months=""', row)
|
||||
self.assertIn('data-terrain=""', row)
|
||||
row = home.entry(fake(1, hike={"months": [7, 8, 9]}))
|
||||
self.assertIn('data-months="7 8 9"', row)
|
||||
|
||||
def test_script_leaves_out_missing_values(self):
|
||||
with open(os.path.join(WEB, "assets", "app.js"), encoding="utf-8") as f:
|
||||
js = f.read()
|
||||
self.assertIn("if (s.month && words(d.months).indexOf(s.month) === -1) return false;", js)
|
||||
self.assertIn("note.hidden = !on[note.dataset.missing]", js)
|
||||
|
||||
|
||||
# Words that must not appear on a browsing page (home, places, lists, Routes, and a
|
||||
# trail page above "About this data"). Record text can say what it likes; these are
|
||||
# the site's own words, so they are checked in the site's own markup: headings,
|
||||
# labels, legends, buttons, counts, empty states, alt text and descriptions.
|
||||
BANNED = (r"\btrails and routes\b", r"\bperson-defined\b", r"\bways in\b", r"\bcollections?\b",
|
||||
r"\brecord only\b", r"\bregions\b", r"\btrack polic(y|ies)\b", r"\btier\b", r"\bheld\b",
|
||||
r"\bsource status\b", r"\bverification\b", r"\blisting\b", r"\bcreator\b", r"\bmaker\b",
|
||||
r"\brecords?\b", r"\bentry\b", r"\bdesignated trail\b")
|
||||
|
||||
|
||||
def site_words(doc):
|
||||
"""The text the site writes on a page, without the trails' own text: rows' descriptions,
|
||||
names, summaries and the record-sourced notes are dropped, and so is "About this data"."""
|
||||
if '<details class="about-data"' in doc:
|
||||
doc = doc[:doc.index('<details class="about-data"')]
|
||||
doc = doc[doc.index('<main id="main">'):]
|
||||
for cls in ("entry__desc", "entry__name", "trail-lede", "titleblock__sub", "entry__partial",
|
||||
"note", "record-text", "map__reason", "glance__warn", "shelf__items", "onward__list"):
|
||||
doc = re.sub(rf'<(\w+) class="{cls}"[^>]*>.*?</\1>', " ", doc, flags=re.S)
|
||||
doc = re.sub(r"<dd>.*?</dd>", " ", doc, flags=re.S) # glance values are the trail's facts
|
||||
doc = re.sub(r'<div class="notice notice--partial">.*?</div>', " ", doc, flags=re.S) # quotes the record
|
||||
doc = re.sub(r'<li class="guide">.*?</li>', " ", doc, flags=re.S)
|
||||
doc = re.sub(r'<a [^>]*href="(?:https?:|/trails/)[^"]*"[^>]*>.*?</a>', " ", doc, flags=re.S)
|
||||
attrs = " ".join(re.findall(r'(?:alt|aria-label|title|placeholder|content)="([^"]*)"', doc))
|
||||
return html.unescape(re.sub(r"<[^>]+>", " ", doc) + " " + attrs)
|
||||
|
||||
|
||||
class BuiltVocabularyTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
os.makedirs(os.path.dirname(OUT), exist_ok=True)
|
||||
subprocess.run([sys.executable, os.path.join(WEB, "build.py"), "--out", OUT],
|
||||
check=True, stdout=subprocess.DEVNULL)
|
||||
|
||||
def read(self, rel):
|
||||
with open(os.path.join(OUT, *rel.split("/")), encoding="utf-8") as f:
|
||||
return f.read()
|
||||
|
||||
def browsing_pages(self):
|
||||
rels = ["index.html", "regions/index.html", "lists/index.html", "routes/index.html", "404.html"]
|
||||
for d in ("regions", "lists"):
|
||||
for name in sorted(os.listdir(os.path.join(OUT, d))):
|
||||
if os.path.isfile(os.path.join(OUT, d, name, "index.html")):
|
||||
rels.append(f"{d}/{name}/index.html")
|
||||
rels += [f"trails/{t}/index.html" for t in sorted(os.listdir(os.path.join(OUT, "trails")))
|
||||
if os.path.isfile(os.path.join(OUT, "trails", t, "index.html"))]
|
||||
return rels
|
||||
|
||||
def test_no_banned_word_on_a_browsing_page(self):
|
||||
bad = []
|
||||
for rel in self.browsing_pages():
|
||||
words_ = site_words(self.read(rel))
|
||||
for pattern in BANNED:
|
||||
m = re.search(pattern, words_, re.I)
|
||||
if m:
|
||||
bad.append((rel, m.group(0), words_[max(0, m.start() - 40):m.end() + 40]))
|
||||
self.maxDiff = None
|
||||
self.assertEqual(bad[:40], [])
|
||||
|
||||
def test_navigation_has_three_items(self):
|
||||
doc = self.read("index.html")
|
||||
nav = re.search(r'<nav aria-label="Main"><ul class="nav">(.*?)</ul></nav>', doc).group(1)
|
||||
self.assertEqual(re.findall(r">([^<]+)</a>", nav), ["Trails", "Places", "About"])
|
||||
|
||||
def test_one_count_noun(self):
|
||||
doc = self.read("index.html")
|
||||
n = len(re.findall(r'<li class="entry" ', doc))
|
||||
self.assertEqual(n, len(records.load_records(ROOT)))
|
||||
self.assertIn(f"<strong>{n}</strong> of {n} trails", doc)
|
||||
self.assertIn(f"{n} long-distance trails", doc)
|
||||
|
||||
def test_route_badges_link_to_the_routes_list(self):
|
||||
for rel in ("index.html", "routes/index.html"):
|
||||
doc = self.read(rel)
|
||||
for m in re.finditer(r'<(\w+) class="tag tag--route"([^>]*)>Route<', doc):
|
||||
self.assertEqual((m.group(1), m.group(2)), ("a", ' href="/routes/"'), rel)
|
||||
|
||||
def test_old_urls_still_built(self):
|
||||
recs = records.load_records(ROOT)
|
||||
paths = ["index.html", "regions/index.html", "routes/index.html", "about/index.html", "data/index.html",
|
||||
"data/schema/index.html", "data/changelog/index.html", "sources/index.html",
|
||||
"logos/index.html", "404.html", "data/trails.csv", "data/trails.json", "data/index.geojson",
|
||||
"data/overview.geojson", "data/all-gpx.zip", "data/all-geojson.zip", "licences/LICENSE"]
|
||||
paths += [f"trails/{r['id']}/index.html" for r in recs]
|
||||
paths += [f"trails/{r['id']}/trail.toml" for r in recs]
|
||||
for key in {k for r in recs for k in facets.place_keys(r) if k != facets.ACROSS_CANADA}:
|
||||
paths.append(f"regions/{key.lower()}/index.html")
|
||||
for rel in paths:
|
||||
self.assertTrue(os.path.isfile(os.path.join(OUT, *rel.split("/"))), rel)
|
||||
|
||||
def test_about_holds_the_dataset_terms(self):
|
||||
doc = self.read("about/index.html")
|
||||
for want in ('id="how-trails-are-chosen"', "Held", "Deferred", "Candidate", "Track policy",
|
||||
'href="/data/"', 'href="/sources/"', 'href="/logos/"', 'id="correct-or-add"'):
|
||||
self.assertIn(want, doc, want)
|
||||
for rel in ("data/index.html", "sources/index.html", "logos/index.html", "data/schema/index.html"):
|
||||
self.assertIn('<li><a href="/about/">About</a></li>', self.read(rel), rel)
|
||||
|
||||
def test_trail_page_ways_onward(self):
|
||||
doc = self.read("trails/sierra-high-route/index.html")
|
||||
foot = doc[doc.index('<nav class="onward"'):doc.index('<details class="about-data"')]
|
||||
self.assertIn("More in California", foot)
|
||||
doc = self.read("trails/kings-canyon-high-basin-route/index.html")
|
||||
self.assertIn("More routes by Andrew Skurka", doc)
|
||||
self.assertIn('href="/trails/yosemite-high-route/"', doc[doc.index('<nav class="onward"'):])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,319 @@
|
||||
"""Tests for the hiker's part of the site: the [hike] facts on a trail page, the
|
||||
"About this data" part, the words on the browsing surfaces, and the home page's
|
||||
collections (olt/hike.py, olt/browse.py, olt/trail.py, olt/home.py).
|
||||
|
||||
These render fixtures; they do not need the built site.
|
||||
"""
|
||||
import copy
|
||||
import html
|
||||
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, hike, home, site, trail, words # noqa: E402
|
||||
from test_pages import sample_record # noqa: E402
|
||||
|
||||
GH = site.Site("N", "T", repo_url="https://github.com/o/r")
|
||||
|
||||
FULL_HIKE = {
|
||||
"summary": "A long walk along the crest of the Example Range. It crosses three passes. Water is scarce in Mt. Dry country.",
|
||||
"official_url": "https://trail.example/",
|
||||
"start": "South Gate, Arizona",
|
||||
"end": "North Gate, Utah",
|
||||
"shape": "point-to-point",
|
||||
"days": [150, 210],
|
||||
"season": "March to October",
|
||||
"high_point": "Example Peak",
|
||||
"high_point_m": 2025,
|
||||
"terrain": ["forest", "alpine"],
|
||||
"permit": "A permit is needed for the national park section",
|
||||
"unfinished": "Forty miles are still on roads",
|
||||
"checked": "2026-11-13",
|
||||
"source": [{"url": "https://trail.example/facts", "publisher": "Example Trail Association",
|
||||
"facts": ["start", "end", "days", "season"]}],
|
||||
}
|
||||
|
||||
|
||||
def with_line(rec):
|
||||
"""A fixture record with a track and its downloads, so the download panel is drawn."""
|
||||
rec = copy.deepcopy(rec)
|
||||
rec["source"].update({"status": "verified", "licence": "CC-BY-4.0", "attribution": "Example Trail Association (CC BY 4.0)",
|
||||
"line_source": "Example Trail Association", "line_file": "line.geojson",
|
||||
"line_absent_reason": ""})
|
||||
rec["verification"] = {"verified": True, "date": "2026-11-10", "measured_km": 60.0,
|
||||
"difference_percent": -40.0, "parts": 3, "note": "Only part is built."}
|
||||
rec["source"]["length_gap_note"] = "The trail is not finished."
|
||||
rec["derived"].update({"has_line": True, "status": "included", "files": {"line": "x/line.geojson"},
|
||||
"downloads": [{"role": "main", "format": "GPX", "file": "x.gpx", "bytes": 1000},
|
||||
{"role": "main", "format": "GeoJSON", "file": "x.geojson", "bytes": 3000}]})
|
||||
return rec
|
||||
|
||||
|
||||
def render(rec, s=GH):
|
||||
return trail.render(rec, s)[2]
|
||||
|
||||
|
||||
def top_part(body):
|
||||
"""The hiker's part of a trail page: everything before "About this data"."""
|
||||
return body[:body.index('<details class="about-data"')]
|
||||
|
||||
|
||||
def text(fragment):
|
||||
return re.sub(r"\s+", " ", html.unescape(re.sub(r"<[^>]+>", " ", fragment)))
|
||||
|
||||
|
||||
DATASET_WORDS = ("record", "Record", "tier", "Tier", "Held", "held", "Deferred", "Candidate", "wave",
|
||||
"person-defined", "Person-defined", "track policy", "Track policy", "creator", "Creator",
|
||||
"maker", "listing", "Listing", "collection", "Collection", "Ways in", "trails and routes",
|
||||
"Trails and routes", "record only", "source status", "Source status", "verification",
|
||||
"Verification", "line", "Line", "Regions", "entry")
|
||||
|
||||
|
||||
class FormatTest(unittest.TestCase):
|
||||
def test_days(self):
|
||||
cases = {(4, 6): "4 to 6 days", (1, 1): "1 day", (5, 5): "5 days", (10, 14): "10 to 14 days",
|
||||
(14, 21): "2 to 3 weeks", (20, 35): "3 to 5 weeks", (21, 21): "about 3 weeks",
|
||||
(150, 210): "5 to 7 months", (40, 70): "1 to 2 months", (180, 180): "about 6 months"}
|
||||
for days, want in cases.items():
|
||||
self.assertEqual(words.fmt_days(list(days)), want, days)
|
||||
self.assertEqual(words.fmt_days(7), "7 days")
|
||||
self.assertEqual(words.fmt_days([]), "")
|
||||
self.assertEqual(words.fmt_days(None), "")
|
||||
|
||||
def test_elevation_follows_the_unit_toggle(self):
|
||||
e = str(words.elevation(2025))
|
||||
# the same km/mi pair as lengths, so html[data-units] orders metres and feet too
|
||||
self.assertIn('<span class="len__km">2,025 m</span>', e)
|
||||
self.assertIn('<span class="len__mi">6,644 ft</span>', e)
|
||||
self.assertIn('class="len len--inline"', e)
|
||||
|
||||
def test_first_sentence(self):
|
||||
self.assertEqual(hike.first_sentence("One. Two."), "One.")
|
||||
self.assertEqual(hike.first_sentence("Past Mt. Hood and St. Helens. Then on."), "Past Mt. Hood and St. Helens.")
|
||||
self.assertEqual(hike.first_sentence("By J. Smith in 1970. More."), "By J. Smith in 1970.")
|
||||
self.assertEqual(hike.first_sentence("Only one"), "Only one")
|
||||
|
||||
|
||||
class TrailPageTest(unittest.TestCase):
|
||||
def test_full_hike_table(self):
|
||||
rec = sample_record("X Trail")
|
||||
rec["hike"] = copy.deepcopy(FULL_HIKE)
|
||||
top = top_part(render(rec))
|
||||
t = text(top)
|
||||
self.assertIn("A long walk along the crest of the Example Range. It crosses three passes.", t)
|
||||
self.assertIn('href="https://trail.example/"', top)
|
||||
self.assertIn("Official site", t)
|
||||
for want in ("Time 5 to 7 months", "Season March to October", "Example Peak",
|
||||
"2,025 m", "6,644 ft", "Shape End to end. South Gate, Arizona to North Gate, Utah",
|
||||
"Terrain Forest, Alpine", "Permits A permit is needed for the national park section.",
|
||||
"Not finished. Forty miles are still on roads."):
|
||||
self.assertIn(want, t, want)
|
||||
self.assertNotIn("Estimated from the length", t) # a source states the time
|
||||
self.assertIn("Walking is not on file for this trail yet.", t)
|
||||
# where the facts were read: in "About this data", with the facts in plain words
|
||||
about = render(rec)[render(rec).index('<details class="about-data"'):]
|
||||
self.assertIn("Where the hiking facts come from", about)
|
||||
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")
|
||||
|
||||
def test_partial_hike_table(self):
|
||||
rec = sample_record("X Trail")
|
||||
rec["hike"] = {"shape": "loop", "start": "Lake Camp", "days": [4, 6], "checked": "2026-11-13"}
|
||||
top = top_part(render(rec))
|
||||
t = text(top)
|
||||
self.assertIn("Shape Loop. Starts and ends at Lake Camp", t)
|
||||
self.assertIn("Time 4 to 6 days", t)
|
||||
self.assertIn("Season, terrain and walking are not on file for this trail yet.", t)
|
||||
for absent in ("Season March", "High point", "Terrain Alpine", "Permits", "Not finished", "Official site"):
|
||||
self.assertNotIn(absent, t, absent)
|
||||
# no summary: the lede is built from the record
|
||||
self.assertIn("A trail of 100 km 62 mi in Arizona, United States.", t)
|
||||
about = render(rec)[render(rec).index('<details class="about-data"'):]
|
||||
self.assertIn("The record names no page for these facts.", about)
|
||||
|
||||
def test_no_hike_table(self):
|
||||
rec = sample_record("X Trail")
|
||||
body = render(rec)
|
||||
top = top_part(body)
|
||||
t = text(top)
|
||||
self.assertIn("A trail of 100 km 62 mi in Arizona, United States.", t)
|
||||
self.assertIn("Length", t)
|
||||
self.assertIn("Where Arizona , United States", t)
|
||||
# every trail has a time: here estimated from its 100 km, and labelled so
|
||||
self.assertIn("Time About 4 to 5 days Estimated from the length, at 20 to 30 km (12 to 19 mi) a day.", t)
|
||||
self.assertIn("Season, terrain and walking are not on file for this trail yet.", t)
|
||||
self.assertNotIn("Where the hiking facts come from", body)
|
||||
# no track: the page says so plainly and points at the source
|
||||
self.assertIn("No GPX here", t)
|
||||
self.assertIn("GPX Not here, see the official site", t)
|
||||
self.assertIn('href="#track"', top)
|
||||
self.assertIn('id="track"', top)
|
||||
|
||||
def test_top_of_page_uses_plain_words(self):
|
||||
for hike_table in (None, FULL_HIKE):
|
||||
for rec in (sample_record("X Trail"), with_line(sample_record("X Trail"))):
|
||||
rec = copy.deepcopy(rec)
|
||||
rec["wave"] = "held"
|
||||
rec["tier"] = "deferred"
|
||||
if hike_table:
|
||||
rec["hike"] = copy.deepcopy(hike_table)
|
||||
t = text(top_part(render(rec)))
|
||||
for word in DATASET_WORDS:
|
||||
self.assertNotRegex(t, rf"\b{word}", word)
|
||||
|
||||
def test_about_this_data_is_collapsed_and_complete(self):
|
||||
rec = with_line(sample_record("X Trail"))
|
||||
body = render(rec)
|
||||
about = body[body.index('<details class="about-data"'):]
|
||||
self.assertTrue(about.startswith('<details class="about-data" id="about-data">')) # closed by default
|
||||
for part in ('id="record-title"', 'id="verify-title"', 'id="source-title"', 'id="osm-title"',
|
||||
'id="logo-title"', 'id="links-title"', 'id="correct-title"', '<details class="rawrecord">'):
|
||||
self.assertIn(part, about, part)
|
||||
self.assertNotIn(part, top_part(body), part)
|
||||
|
||||
def test_credit_licence_and_partial_warning_stay_in_view(self):
|
||||
rec = with_line(sample_record("X Trail"))
|
||||
top = top_part(render(rec))
|
||||
# the credit and licence beside the downloads, and on the map's caption
|
||||
panel = top[top.index('id="download"'):]
|
||||
self.assertIn('id="credit-text">Example Trail Association (CC BY 4.0)<', panel)
|
||||
self.assertIn('Licence: <a href="https://creativecommons.org/licenses/by/4.0/">CC BY 4.0</a>', panel)
|
||||
self.assertLess(panel.index('<ul class="downloads">'), panel.index('class="credit"'))
|
||||
caption = top[top.index('<figcaption class="mapfig__caption">'):]
|
||||
self.assertIn("Credit: Example Trail Association (CC BY 4.0).", caption)
|
||||
# the partial warning above the buttons, and in the glance
|
||||
self.assertLess(panel.index("notice--partial"), panel.index('<ul class="downloads">'))
|
||||
self.assertIn("Partial GPX to download here", top)
|
||||
self.assertIn("Track measures 60.0 km of 100 km published", text(top))
|
||||
|
||||
def test_report_a_problem_stays_in_view(self):
|
||||
top = top_part(render(sample_record("X Trail")))
|
||||
self.assertIn('>Report a problem</a>', top)
|
||||
self.assertIn("template=correction.yml", top)
|
||||
self.assertIn("Not for navigation", top)
|
||||
# without a repository there is nothing to link
|
||||
self.assertNotIn("Report a problem", top_part(render(sample_record("X Trail"), site.Site("N", "T"))))
|
||||
|
||||
|
||||
def fake(i, km=100, **kw):
|
||||
rec = sample_record(f"T{i}")
|
||||
rec["id"] = f"t{i}"
|
||||
rec["length_km"] = km
|
||||
rec["derived"] = dict(rec["derived"])
|
||||
for k, v in kw.items():
|
||||
if k == "hike":
|
||||
rec["hike"] = v
|
||||
elif k == "tier":
|
||||
rec["tier"] = v
|
||||
elif k == "line":
|
||||
rec["derived"]["has_line"] = v
|
||||
elif k == "regions":
|
||||
rec["regions"] = v
|
||||
elif k == "country":
|
||||
rec["country"] = v
|
||||
return rec
|
||||
|
||||
|
||||
def by_key(key):
|
||||
return browse.by_key(key)
|
||||
|
||||
|
||||
class ListTest(unittest.TestCase):
|
||||
def test_each_rule(self):
|
||||
route = fake(1)
|
||||
route["derived"]["kind"] = "route"
|
||||
cases = {
|
||||
"national-scenic-trails": (fake(1, tier="national"), fake(2)),
|
||||
"routes": (route, fake(2)),
|
||||
"longest": (fake(1, km=2000), fake(2, km=1999)),
|
||||
"under-100-km": (fake(1, km=99), fake(2, km=100)),
|
||||
# by Time: stated, or estimated from the length
|
||||
"a-week-or-less": (fake(1, hike={"days": [4, 7]}), fake(2, hike={"days": [20, 35]})),
|
||||
"one-to-two-weeks": (fake(1, km=250), fake(2, km=100)),
|
||||
"loops": (fake(1, hike={"shape": "loop"}), fake(2, hike={"shape": "point-to-point"})),
|
||||
"with-gpx": (fake(1, line=True), fake(2)),
|
||||
"canada": (fake(1, regions=["ON"], country="CA"), fake(2)),
|
||||
"united-states": (fake(1), fake(2, regions=["ON"], country="CA")),
|
||||
"off-trail": (fake(1, hike={"travel": "some-cross-country"}), fake(2, hike={"travel": "trail-and-road"})),
|
||||
"terrain-desert": (fake(1, hike={"terrain": ["desert"]}), fake(2, hike={"terrain": ["forest"]})),
|
||||
}
|
||||
for key, (inside, outside) in cases.items():
|
||||
lst = by_key(key)
|
||||
self.assertTrue(lst.test(inside), key)
|
||||
self.assertFalse(lst.test(outside), key)
|
||||
self.assertTrue(by_key("a-week-or-less").test(fake(3, km=100))) # 4 to 5 days, estimated
|
||||
# a trail without [hike] is in no list that needs a [hike] fact
|
||||
for key in ("loops", "terrain-alpine", "off-trail"):
|
||||
self.assertFalse(by_key(key).test(fake(3)), key)
|
||||
|
||||
def test_paths(self):
|
||||
self.assertEqual(browse.path(by_key("routes")), "/routes/")
|
||||
self.assertEqual(browse.path(by_key("loops")), "/lists/loops/")
|
||||
|
||||
def test_threshold(self):
|
||||
self.assertFalse(browse.is_shown(browse.MIN_SIZE - 1, 100))
|
||||
self.assertTrue(browse.is_shown(browse.MIN_SIZE, 100))
|
||||
self.assertTrue(browse.is_shown(75, 100))
|
||||
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)]
|
||||
for i in range(5):
|
||||
recs[i]["tier"] = "national"
|
||||
keys = [lst.key for lst, _ in browse.shown(recs)]
|
||||
self.assertNotIn("loops", keys)
|
||||
self.assertIn("national-scenic-trails", keys)
|
||||
self.assertNotIn("united-states", keys) # every one of them: nearly everything
|
||||
body = home.render(recs, GH)
|
||||
self.assertNotIn('href="/lists/loops/"', body)
|
||||
self.assertIn('href="/lists/national-scenic-trails/"', body)
|
||||
recs[3]["hike"] = {"shape": "loop"}
|
||||
self.assertIn("loops", [lst.key for lst, _ in browse.shown(recs)])
|
||||
|
||||
def test_rules_name_no_trail(self):
|
||||
ids = [d for d in os.listdir(os.path.dirname(WEB)) if os.path.isfile(os.path.join(os.path.dirname(WEB), d, "trail.toml"))]
|
||||
for name in ("browse.py",):
|
||||
with open(os.path.join(WEB, "olt", name), encoding="utf-8") as f:
|
||||
source = f.read()
|
||||
for tid in ids:
|
||||
self.assertNotIn(f'"{tid}"', source, f"{name}: {tid}")
|
||||
|
||||
|
||||
class ListRowTest(unittest.TestCase):
|
||||
def test_row_words_and_description(self):
|
||||
rec = fake(1)
|
||||
rec["wave"] = "held"
|
||||
rec["tier"] = "deferred"
|
||||
row = home.entry(rec)
|
||||
t = text(row)
|
||||
for word in DATASET_WORDS:
|
||||
self.assertNotRegex(t, rf"\b{word}", word)
|
||||
self.assertIn("See the official site", t)
|
||||
rec["hike"] = {"summary": "A fine walk. Long too.", "days": [4, 6]}
|
||||
t = text(home.entry(rec))
|
||||
self.assertIn("A fine walk.", t)
|
||||
self.assertNotIn("Long too.", t)
|
||||
self.assertIn("4 to 6 days", t)
|
||||
|
||||
def test_route_rows_say_how_to_get_the_track(self):
|
||||
rec = fake(1)
|
||||
rec["derived"]["kind"] = "route"
|
||||
rec["kind"] = "route"
|
||||
rec["route"] = {"creator": "A Person", "line_policy": "sold"}
|
||||
rec["guide"] = []
|
||||
self.assertIn("Sold by its author", text(home.entry(rec)))
|
||||
self.assertIn("Route by A Person", text(home.entry(rec)))
|
||||
self.assertIn('<a class="tag tag--route" href="/routes/">Route</a>', home.entry(rec))
|
||||
self.assertNotRegex(text(home.entry(rec)), r"\b(creator|maker|person-defined)\b")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
+16
-9
@@ -190,9 +190,13 @@ class BuiltSiteTest(unittest.TestCase):
|
||||
f"{rec['length_km']:,} km ({words.fmt_percent(v['difference_percent'])})", text)
|
||||
self.assertIn(re.sub(r"\s+", " ", rec["source"]["length_gap_note"]), text, rec["id"])
|
||||
short = rec["id"] in expected and rec["verification"]["difference_percent"] < 0
|
||||
self.assertEqual("In the dataset, partial" in page, short, rec["id"])
|
||||
glance = page[page.index('<section class="glance'):page.index("</section>", page.index('<section class="glance'))]
|
||||
self.assertEqual("Partial GPX to download here" in glance, short, rec["id"])
|
||||
if rec["derived"]["has_line"]:
|
||||
self.assertRegex(page, r'<dt>Track</dt><dd><a href="#download">In the dataset', rec["id"])
|
||||
self.assertRegex(glance, r'<dt>GPX</dt><dd><a href="#download">(Partial )?GPX to download here</a>', rec["id"])
|
||||
# the partial warning is in view, outside "About this data"
|
||||
if rec["id"] in expected:
|
||||
self.assertLess(page.index("notice--partial"), page.index('<details class="about-data"'), rec["id"])
|
||||
rows_seen = set()
|
||||
for path in html_files(OUT):
|
||||
with open(path, encoding="utf-8") as f:
|
||||
@@ -257,17 +261,20 @@ class BuiltSiteTest(unittest.TestCase):
|
||||
def test_no_raw_tokens_in_the_main_flow(self):
|
||||
for rec in self.records:
|
||||
page = self.pages[rec["id"]]
|
||||
main = page[page.index('<div class="detail__main">'):page.index('<details class="rawrecord">')]
|
||||
top = page[page.index('<main id="main">'):page.index('<details class="about-data"')]
|
||||
self.assertNotIn('<code class="raw">', top, rec["id"])
|
||||
main = page[page.index('<div class="about-data__body'):page.index('<details class="rawrecord">')]
|
||||
codes = set(html.unescape(c) for c in re.findall(r'<code class="raw">(.*?)</code>', main))
|
||||
self.assertLessEqual(codes, {rec["id"]}, rec["id"])
|
||||
# main-column sections are not landmarks; the aside panels are
|
||||
# "About this data" sections are not landmarks; the glance and the aside panels are
|
||||
self.assertNotIn('<section class="block" aria-labelledby', page, rec["id"])
|
||||
self.assertIn('<section class="panel" aria-labelledby="links-title">', page, rec["id"])
|
||||
self.assertIn('<section class="glance detail__glance" aria-labelledby="glance-title">', page, rec["id"])
|
||||
self.assertIn('<h2 id="links-title">Links</h2>', main, rec["id"])
|
||||
|
||||
def test_record_without_a_line_says_so_once(self):
|
||||
for rec in self.records:
|
||||
page = self.pages[rec["id"]]
|
||||
main = page_text(page[page.index('<div class="detail__main">'):page.index('<details class="rawrecord">')])
|
||||
main = page_text(page[page.index('<div class="about-data__body'):page.index('<details class="rawrecord">')])
|
||||
helper = "Where to ask for the track: a layer or relation page"
|
||||
if rec["derived"]["has_line"]:
|
||||
self.assertEqual(helper in main, bool(rec["source"].get("url")), rec["id"])
|
||||
@@ -481,9 +488,9 @@ class RenderUnitTest(unittest.TestCase):
|
||||
f.write('id = "x"\n')
|
||||
rec = sample_record(name="A & B")
|
||||
n = pages.render_site([rec], out, repo, site=site.Site("N", "T"))
|
||||
# trail page + home + 404 + regions index + 1 region + routes,
|
||||
# sources, logos, about, data, schema, changelog
|
||||
self.assertEqual(n, 12)
|
||||
# trail page + home + 404 + places hub + 1 place + lists hub + routes,
|
||||
# sources, logos, about, data, schema, changelog (no list holds MIN_SIZE trails)
|
||||
self.assertEqual(n, 13)
|
||||
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:
|
||||
|
||||
Reference in new issue
Block a user