Add a page for each kind of trail in each park, mountain range and wilderness area that has three or more of them, built by the same rules as the state pages, and link each from its place page

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Sonnet 5.5 committed 2026-11-20 18:15:24 -07:00
1 parent 4a89833162
commit b75d39c7b6
6 files changed
+313 -41

No files matched your search

+8
View File
@@ -1,5 +1,13 @@
# Changelog
## 2026-11-20 - Lists inside parks, mountain ranges and wilderness areas
- 131 new pages show one kind of trail in one park, mountain range or wilderness area: 39 for parks, 71 for ranges and 21 for wilderness areas. Examples: the trails under 100 miles in the Wind River Range, the loops in the Sangre de Cristo Mountains, the routes in Grand Canyon National Park. They answer searches such as "backpacking loops in the Adirondacks" or "short hikes in Yosemite", and each has the same filter bar, trail rows and map as the place's own page, with the count in its title.
- A page exists only when the place has 3 or more trails of that kind and they are not nearly all the trails of the place (more than three in four would repeat the place's own page). The kinds crossed with a place are the ones already crossed with a state: routes, the length bands, loops, cross-country, trails with a GPX to download and the main kinds of terrain.
- Each place's page links to its lists with how many trails are in each, and each list page links back to the place, to the place's other lists, and to the same list in the other places.
- A title keeps its count of trails and says "in" or "in the" as the place's own page does; where the full words would not fit in a title, a shorter name for the kind of trail is used ("Loops", "Trails Under 100 Miles"). The 19 pages whose place name alone is long (Sequoia and Kings Canyon National Parks, the Sequoia-Kings Canyon Wilderness) go a few characters over the usual length rather than lose their count.
- For contributors: `placefacets.plan_places` builds these pages with the same rule code as the state pages (`placefacets._plan`); the state pages are byte for byte as before.
## 2026-11-20 - Faster builds and tests, and reproducible downloads
- The site builds in about a quarter of the time on a warm cache and the whole test suite runs in about a quarter of its former time. The pages are unchanged: every file of a build matches a build of the previous version except the two bulk downloads (all GPX, all GeoJSON).
+19 -9
View File
@@ -50,6 +50,8 @@ class List:
# The words for this kind of trail in a place page's title: "Loop Hiking Trails" gives
# "Loop Hiking Trails in Colorado: 6 Trails". Empty: no page for each place.
noun: str = ""
# A shorter noun for the same title where the place's name is long; empty: the noun.
short: str = ""
# (list's trails, all trails) -> a plain sentence or two that says what the list covers
# where that is not every trail: how many have the fact the list is built on.
note: Optional[Callable] = None
@@ -174,7 +176,8 @@ LISTS = (
page_title="National Recreation Trails: {n} Long Hiking Trails", group="standing"),
List("routes", "Routes", facets.ROUTE_DEFINITION,
lambda r: facets.kind(r) == "route", page_title="Long Hiking Routes by Author: {n} Routes",
group="standing", noun="Long Hiking Routes"),
group="standing", noun="Long Hiking Routes",
short="Routes"),
List("high-routes", "High routes",
"Routes whose own name says High Route: through high country, often off the trail.",
_high_route, page_title="High Routes: {n} Long Hiking Routes", group="walking"),
@@ -186,22 +189,26 @@ LISTS = (
f"Trails of {HALF_MI} miles ({_km(HALF_MI)} km) or more and shorter than {LONG_MI:,} miles ({_km(LONG_MI)} km).",
_length_band(HALF_MI, LONG_MI), sort="length-desc",
page_title=f"Hiking Trails of {HALF_MI} to {LONG_MI:,} Miles: {{n}} Long Trails", group="length",
noun=f"Hiking Trails of {HALF_MI} to {LONG_MI:,} Miles"),
noun=f"Hiking Trails of {HALF_MI} to {LONG_MI:,} Miles",
short=f"{HALF_MI} to {LONG_MI:,} Mile Trails"),
List("200-to-500-miles", f"{MID_MI} to {HALF_MI} miles",
f"Trails of {MID_MI} miles ({_km(MID_MI)} km) or more and shorter than {HALF_MI} miles ({_km(HALF_MI)} km).",
_length_band(MID_MI, HALF_MI), sort="length-desc",
page_title=f"Hiking Trails of {MID_MI} to {HALF_MI} Miles: {{n}} Long Trails", group="length",
noun=f"Hiking Trails of {MID_MI} to {HALF_MI} Miles"),
noun=f"Hiking Trails of {MID_MI} to {HALF_MI} Miles",
short=f"{MID_MI} to {HALF_MI} Mile Trails"),
List("100-to-200-miles", f"{SHORT_MI} to {MID_MI} miles",
f"Trails of {SHORT_MI} miles ({_km(SHORT_MI)} km) or more and shorter than {MID_MI} miles ({_km(MID_MI)} km).",
_length_band(SHORT_MI, MID_MI), sort="length-desc",
page_title=f"Hiking Trails of {SHORT_MI} to {MID_MI} Miles: {{n}} Long Trails", group="length",
noun=f"Hiking Trails of {SHORT_MI} to {MID_MI} Miles"),
noun=f"Hiking Trails of {SHORT_MI} to {MID_MI} Miles",
short=f"{SHORT_MI} to {MID_MI} Mile Trails"),
List("under-100-miles", f"Under {SHORT_MI} miles",
f"Trails shorter than {SHORT_MI} miles ({_km(SHORT_MI)} km).",
lambda r: r["length_km"] < SHORT_KM, sort="length-asc",
page_title=f"Hiking Trails Under {SHORT_MI} Miles: {{n}} Long Trails", group="length",
noun=f"Hiking Trails Under {SHORT_MI} Miles"),
noun=f"Hiking Trails Under {SHORT_MI} Miles",
short=f"Trails Under {SHORT_MI} Miles"),
List("under-200-miles", f"Under {MID_MI} miles",
f"Trails shorter than {MID_MI} miles ({_km(MID_MI)} km): the two shortest bands together.",
lambda r: r["length_km"] < MID_KM, sort="length-asc",
@@ -228,12 +235,14 @@ LISTS = (
page_title="Long Trails That Take a Month or More: {n} Trails", group="time", note=time_note),
List("loops", "Loops", "Trails that finish where they start.",
lambda r: facets.shape(r) == "loop", page_title="Loop Hiking Trails: {n} Long Trail Loops",
group="walking", noun="Loop Hiking Trails"),
group="walking", noun="Loop Hiking Trails",
short="Loops"),
List("off-trail", "Cross-country",
"Trails with stretches of walking where there is no trail.",
lambda r: facets.walking(r) in facets.CROSS_COUNTRY,
page_title="Cross-Country Hiking: {n} Long Trails and Routes", group="walking",
noun="Cross-Country Hiking"),
noun="Cross-Country Hiking",
short="Cross-Country Hikes"),
List("mostly-cross-country", "Mostly cross-country",
"Trails where there is no trail for most of the way.",
lambda r: facets.walking(r) == "mostly-cross-country",
@@ -261,7 +270,8 @@ LISTS = (
List("with-gpx", "With a GPX to download",
"Trails with a GPX file of the track on their page.",
facets.gpx_here, page_title="Long Trails with a GPX to Download: {n} Trails", group="where",
noun="Hiking Trails with a GPX"),
noun="Hiking Trails with a GPX",
short="Trails with a GPX"),
List("canada", "In Canada", "Trails in Canada, or crossing into it.",
lambda r: "CA" in common.countries(r), page_title="Hiking Trails in Canada: {n} Long Trails",
group="where"),
@@ -272,7 +282,7 @@ LISTS = (
List(f"terrain-{t}", label, f"Trails with {t} among their main terrain.",
lambda r, t=t: t in facets.terrain(r),
page_title=f"{TERRAIN_ADJECTIVE.get(t, label)} Hiking Trails: {{n}} Long Trails", group="terrain",
noun=f"{TERRAIN_ADJECTIVE.get(t, label)} Hiking Trails")
noun=f"{TERRAIN_ADJECTIVE.get(t, label)} Hiking Trails", short=f"{TERRAIN_ADJECTIVE.get(t, label)} Trails")
for t, label in words.TERRAIN.items()
) + tuple(_month_list(m) for m in range(1, 13))
+2 -2
View File
@@ -154,7 +154,7 @@ def _render_site(records, out_dir, repo_root, site=None):
pages += 1
shown = browse.shown(records)
facet_plan = placefacets.plan(records)
facet_plan = placefacets.plan(records) + placefacets.plan_places(place_infos, records)
facets_of_place = placefacets.pages_by_place(facet_plan)
t, d, b = regions.regions_index_page(records, site, infos=place_infos)
add("/regions/", t, d, b) # every trail is on it: the newest of them
@@ -185,7 +185,7 @@ def _render_site(records, out_dir, repo_root, site=None):
add(path, t, d, b, maps=needs_map, recs=recs)
# Further place pages (parks, ranges and wilderness areas, olt/placepages.py).
for builder in EXTRA_PAGE_BUILDERS:
for built in builder(records, site, repo_root):
for built in builder(records, site, repo_root, facet_pages=facets_of_place):
region_paths.append(built.path)
add(built.path, built.title, built.description, built.body,
maps=built.needs_map, recs=built.recs)
+80 -27
View File
@@ -5,7 +5,7 @@ least MIN_SIZE trails in the list, no more than MAX_SHARE of the place's trails
would repeat the place page), and its trails are not nearly the same set as another such page of
the same place. A new trail or a corrected record moves pages in and out with no change here.
"""
from . import bounds, browse, common, facets, home, regions, summary
from . import bounds, browse, common, facets, home, places as places_mod, regions, summary
from .markup import Markup, esc
SAME_SET = 0.8 # two pages of one place whose trails overlap by this share (of the smaller union) are one page
@@ -15,40 +15,68 @@ def _jaccard(a, b):
return len(a & b) / len(a | b)
def plan(records):
"""[{slug, info, lst, recs, path}] for every page, in place then list order."""
PLACE_MIN = 3 # a park, range or wilderness area's list page needs this many trails
# Lists crossed with a park, range or wilderness area: those that cross a state, less any named here.
# A list that is itself a place or a holder has no noun, so none is crossed.
PLACE_LISTS_OUT = frozenset()
def _plan(units, records, min_size, path_of, lists, max_share):
"""[{slug, info, lst, recs, path, kind}]: for each unit (slug, info) and each list, a page when the
place has min_size trails in the list, no more than max_share of the place's trails are in it,
and its trails are not nearly the same set as another page of the same place."""
shown = {lst.key for lst, _ in browse.shown(records)}
by_slug, _ = regions.collect_regions(records)
out = []
for slug in sorted(by_slug):
info = by_slug[slug]
for slug, info in units:
here = info["records"]
kept = []
for lst in browse.facet_lists():
for lst in lists:
if lst.key not in shown:
continue
recs = browse.members(lst, here)
if len(recs) < browse.MIN_SIZE or len(recs) > browse.MAX_SHARE * len(here):
if len(recs) < min_size or len(recs) > max_share * len(here) or len(recs) >= len(here):
continue
ids = {r["id"] for r in recs}
if any(_jaccard(ids, other) >= SAME_SET for other in kept):
continue
kept.append(ids)
out.append({"slug": slug, "info": info, "lst": lst, "recs": recs,
"path": f"/regions/{slug}/{lst.key}/"})
"path": path_of(slug, info, lst), "kind": info["kind"]})
return out
def plan(records):
"""[{slug, info, lst, recs, path, kind}] for every state page, in place then list order."""
by_slug, _ = regions.collect_regions(records)
return _plan([(slug, by_slug[slug]) for slug in sorted(by_slug)], records, browse.MIN_SIZE,
lambda slug, info, lst: f"/regions/{slug}/{lst.key}/", browse.facet_lists(), browse.MAX_SHARE)
def plan_places(infos, records, max_share=browse.MAX_SHARE):
"""The same for parks, ranges and wilderness areas: infos as olt/places.py collect gives them.
The path is the place's own with the list's key after it."""
units = [(i["slug"], i) for i in sorted(infos.values() if isinstance(infos, dict) else infos,
key=lambda i: (places_mod.KIND_ORDER[i["kind"]], i["name"].lower()))]
lists = [lst for lst in browse.facet_lists() if lst.key not in PLACE_LISTS_OUT]
return _plan(units, records, PLACE_MIN, lambda slug, info, lst: f"{info['path']}{lst.key}/", lists, max_share)
def key_of(p):
"""What pages_by_place keys a page by: (kind, slug) for a place, the slug for a state."""
return p["slug"] if p["kind"] == "state" else (p["kind"], p["slug"])
def label(lst):
"""A short name for the page in a list of links."""
return lst.title
def pages_by_place(pages):
"""slug -> [page], in plan order."""
"""slug (a state) or (kind, slug) (a park, range or wilderness area) -> [page], in plan order."""
out = {}
for p in pages:
out.setdefault(p["slug"], []).append(p)
out.setdefault(key_of(p), []).append(p)
return out
@@ -61,7 +89,7 @@ def pages_by_list(pages):
def places_nav(lst, pages):
"""HTML for a list's page: the places that have a page of their own for it."""
here = pages_by_list(pages).get(lst.key, [])
here = [p for p in pages_by_list(pages).get(lst.key, []) if p["kind"] == "state"]
if not here:
return ""
links = " · ".join(f'<a href="{esc(p["path"])}">{esc(p["info"]["name"])}</a> ({len(p["recs"])})'
@@ -70,32 +98,55 @@ def places_nav(lst, pages):
f'{esc(lst.title)} in a state or province, and how many there: {links}</nav>')
def _kind(info):
"""The PageKind of the place's own page: its where-filter, its map box and how it is named."""
from . import placepages
return regions.STATE if info["kind"] == "state" else placepages.PAGE_KINDS[info["kind"]]
def _own_path(info):
return facets.place_path(info["key"]) if info["kind"] == "state" else info["path"]
def page(p, records, site, all_pages):
"""(title, description, body, needs_map) for one place-and-list page."""
"""(title, description, body, needs_map) for one place-and-list page, of a state or of a park,
range or wilderness area. Every string that depends on the kind of place comes from the place."""
lst, info, recs = p["lst"], p["info"], p["recs"]
kind = _kind(info)
here = info["records"]
name = info["name"]
state = info["kind"] == "state"
in_name = kind.in_name(info) if kind.in_name else name
phrase = kind.phrase(info) if kind.phrase else f"in {in_name}"
title_name = name if state else info["title_name"]
prep = "in" if state else places_mod.prep_of(info)
only_routes = all(facets.kind(r) == "route" for r in recs)
count = f"{len(recs)} {'Routes' if only_routes else 'Trails'}"
title = common.fit_title([f"{lst.noun} in {name}: {count}", f"{lst.noun} in {name}"], site)
h1 = f"{lst.noun} in {name}"
short = lst.short or lst.noun
# The state goes first, then the long noun; the count is never dropped (a title that still
# does not fit, where the place's own name is long, keeps its count and goes over).
ladder = [f"{lst.noun} {prep} {title_name}: {count}", f"{lst.noun} {prep} {name}: {count}",
f"{short} {prep} {title_name}: {count}", f"{short} {prep} {name}: {count}"]
title = common.fit_title(ladder, site)
h1 = f"{lst.noun} {phrase}"
n_gpx = sum(1 for r in recs if facets.gpx_here(r))
gpx = f", {n_gpx} with a GPX here" if n_gpx else ""
lede = (f"{esc(lst.blurb)} {len(recs)} of the {len(here)} trails in {esc(name)}{gpx}. "
f'<a href="{esc(facets.place_path(info["key"]))}">All the trails in {esc(name)}</a>.')
siblings = [q for q in pages_by_place(all_pages)[p["slug"]] if q is not p]
others = [q for q in pages_by_list(all_pages)[lst.key] if q is not p]
lede = (f"{esc(lst.blurb)} {len(recs)} of the {len(here)} trails {esc(phrase)}{gpx}. "
f'<a href="{esc(_own_path(info))}">All the trails {esc(phrase)}</a>.')
siblings = [q for q in pages_by_place(all_pages)[key_of(p)] if q is not p]
others = [q for q in pages_by_list(all_pages)[lst.key] if q is not p and q["kind"] == p["kind"]]
nav = ""
if siblings:
nav += (f'<nav class="region-nav" aria-label="More in {esc(name)}">More in {esc(name)}: '
nav += (f'<nav class="region-nav" aria-label="More {esc(phrase)}">More {esc(phrase)}: '
+ " · ".join(f'<a href="{esc(q["path"])}">{esc(q["lst"].title)}</a> ({len(q["recs"])})' for q in siblings)
+ "</nav>")
if others:
nav += (f'<nav class="region-nav" aria-label="{esc(lst.title)} elsewhere">{esc(lst.title)} elsewhere: '
+ " · ".join(f'<a href="{esc(q["path"])}">{esc(q["info"]["name"])}</a> ({len(q["recs"])})'
for q in sorted(others, key=lambda q: q["info"]["name"])) + "</nav>")
crumbs = (f'<li><a href="/">Trails</a></li><li><a href="/regions/">Places</a></li>'
f'<li><a href="{esc(facets.place_path(info["key"]))}">{esc(name)}</a></li>')
crumbs = ('<li><a href="/">Trails</a></li><li><a href="/regions/">Places</a></li>'
f'<li><a href="{esc(_own_path(info))}">{esc(name)}</a></li>')
place = kind.facts_place(info)
body = f"""<div class="page-head"><div class="container">
<nav class="breadcrumb" aria-label="Breadcrumb"><ol>{crumbs}<li aria-current="page">{esc(lst.title)}</li></ol></nav>
<header class="titleblock"><div class="titleblock__text">
@@ -105,13 +156,15 @@ def page(p, records, site, all_pages):
</div></header>
</div></div>
<div class="container section place">
{home.browse_view(home.listing(recs, default_sort=lst.sort, top=2, where="", season=lst.group == "month"), home.overview_map(recs, f"Map of the trails in {name}: {lst.title}", place=bounds.place_box(info["key"])),
about=summary.facts(recs, records, place=(name, [info["key"]])), about_title=f"About these trails in {name}")}
{home.browse_view(home.listing(recs, default_sort=lst.sort, top=2, where="" if state else kind.where, season=lst.group == "month"), home.overview_map(recs, f"Map of the trails {phrase}: {lst.title}", place=kind.box(info)),
about=summary.facts(recs, records, place=place), about_title=f"About these trails {phrase}")}
<nav class="region-nav" aria-label="Lists"><a href="{esc(browse.path(lst))}">{esc(lst.title)} everywhere</a> · <a href="/lists/">All lists</a></nav>
{nav}
</div>"""
by_length = sorted(recs, key=lambda r: (r["length_km"], r["id"]))
first = (f"{count} in {name}, from {common.plain_name(by_length[0])}, {regions.trail_miles(by_length[0], [info["key"]])}, "
f"to {common.plain_name(by_length[-1])}, {regions.trail_miles(by_length[-1], [info["key"]])}.")
desc = regions._fit([f"{lst.blurb} {first}", f"{lst.noun} in {name}: {first}"])
keys = place[1]
first = (f"{count} {phrase}, from {common.plain_name(by_length[0])}, {regions.trail_miles(by_length[0], keys)}, "
f"to {common.plain_name(by_length[-1])}, {regions.trail_miles(by_length[-1], keys)}.")
desc = regions._fit([f"{lst.blurb} {first}", f"{lst.noun} {phrase}: {first}"] if state
else [f"{lst.blurb} {first}", first])
return title, desc, Markup(body), home.has_overview_map(recs)
+6 -3
View File
@@ -84,14 +84,17 @@ WILDERNESS = _kind()
PAGE_KINDS = {"park": PARK, "range": RANGE, "wilderness": WILDERNESS}
def build(records, site, repo_root):
def build(records, site, repo_root, facet_pages=None):
"""[Built] for every place with a page, parks then ranges then wilderness areas,
each A to Z. The plug-in point's shape (olt/pages.py EXTRA_PAGE_BUILDERS)."""
each A to Z. The plug-in point's shape (olt/pages.py EXTRA_PAGE_BUILDERS).
facet_pages: {(kind, slug): [page]} of the place-plus-list pages (olt/placefacets.py), linked from each."""
infos = places.collect(records, places.load(repo_root))
out = []
for info in sorted(infos.values(),
key=lambda i: (places.KIND_ORDER[i["kind"]], i["name"].lower())):
here = [(q["lst"].title, q["path"], len(q["recs"]))
for q in (facet_pages or {}).get((info["kind"], info["slug"]), [])]
title, description, body, needs_map = regions.place_page(
info, records, site, PAGE_KINDS[info["kind"]])
info, records, site, PAGE_KINDS[info["kind"]], facet_pages=here)
out.append(Built(info["path"], title, description, body, needs_map, info["records"]))
return out
+198
View File
@@ -0,0 +1,198 @@
"""Pages for one kind of trail in a park, a mountain range or a wilderness area
(olt/placefacets.py plan_places and page): /ranges/<slug>/loops/ and the like.
Fixtures only, as in test_place_page.py."""
import os
import re
import sys
import tempfile
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, pages, placefacets, placepages, places # noqa: E402
from test_facets import BANNED # noqa: E402
from test_hike import fake # noqa: E402
from test_place_page import S, entry_of, rec, text, write_registry # noqa: E402
RANGE = entry_of("range", "wind-river-range", "Wind River Range", ["WY"])
PARK = entry_of("park", "yosemite", "Yosemite National Park", ["CA"])
def in_place(i, kind, slug, *, loop, km=150):
r = rec(i, f"Trail {i}", [(kind, slug)], km=km, regs=("WY",))
r["hike"] = dict(r["hike"], shape="loop" if loop else "point-to-point")
return r
def world(n_loops, n_other, entries=(RANGE,), kind="range", slug="wind-river-range"):
"""n_loops loops and n_other other trails in the place, and enough loops and long trails
elsewhere that the loops list is shown at all."""
recs = [in_place(100 + i, kind, slug, loop=True) for i in range(n_loops)]
recs += [in_place(200 + i, kind, slug, loop=False) for i in range(n_other)]
recs += [fake(300 + i, km=500, regions=["NY"], hike={"shape": "loop"}) for i in range(4)]
recs += [fake(400 + i, km=900, regions=["NY"]) for i in range(30)]
return recs
def plan_for(records, entries=(RANGE,)):
with tempfile.TemporaryDirectory() as d:
write_registry(d, list(entries))
infos = places.collect(records, places.load(d))
return infos, placefacets.plan_places(infos, records)
class PlanTest(unittest.TestCase):
def keys(self, plan):
return {p["lst"].key for p in plan}
def test_a_place_list_page_exists_at_three_trails_not_two(self):
_, plan = plan_for(world(3, 4))
self.assertIn("loops", self.keys(plan))
_, plan = plan_for(world(2, 5))
self.assertNotIn("loops", self.keys(plan))
def test_not_built_when_the_list_holds_every_trail_on_the_place_page(self):
_, plan = plan_for(world(7, 0))
self.assertNotIn("loops", self.keys(plan))
def test_not_built_when_the_list_is_not_shown_at_all(self):
# no loops elsewhere, and 3 here: the list has 3 trails in all, under the least to be shown
recs = [in_place(100 + i, "range", "wind-river-range", loop=True) for i in range(3)]
recs += [in_place(200 + i, "range", "wind-river-range", loop=False) for i in range(4)]
_, plan = plan_for(recs)
self.assertNotIn("loops", self.keys(plan))
def test_the_path_is_the_places_own_then_the_list_key(self):
_, plan = plan_for(world(3, 4))
p = next(p for p in plan if p["lst"].key == "loops")
self.assertEqual(p["path"], "/ranges/wind-river-range/loops/")
self.assertEqual(p["kind"], "range")
infos, plan = plan_for(world(3, 4, (PARK,), "park", "yosemite"), (PARK,))
self.assertEqual(next(p for p in plan if p["lst"].key == "loops")["path"], "/parks/yosemite/loops/")
def test_the_state_plan_is_unchanged_and_still_needs_five(self):
recs = world(3, 4)
self.assertEqual({p["kind"] for p in placefacets.plan(recs)} - {"state"}, set())
self.assertTrue(all(len(p["recs"]) >= browse.MIN_SIZE for p in placefacets.plan(recs)))
def test_losing_a_trail_removes_the_page_and_every_link_to_it(self):
full = world(3, 4)
infos, plan = plan_for(full)
before = str(page_of(infos, plan, "loops")[2])
self.assertIn("/ranges/wind-river-range/loops/", str(place_body(infos, plan, full)))
short = [r for r in full if r["id"] != full[0]["id"]]
infos, plan = plan_for(short)
self.assertNotIn("loops", self.keys(plan))
self.assertNotIn("/ranges/wind-river-range/loops/", str(place_body(infos, plan, short)))
self.assertIn("Loops", before)
def page_of(infos, plan, key):
p = next(p for p in plan if p["lst"].key == key)
return placefacets.page(p, [r for i in infos.values() for r in i["records"]], S, plan)
def place_body(infos, plan, records):
info = next(iter(infos.values()))
here = [(q["lst"].title, q["path"], len(q["recs"]))
for q in placefacets.pages_by_place(plan).get((info["kind"], info["slug"]), [])]
from olt import regions
return regions.place_page(info, records, S, placepages.PAGE_KINDS[info["kind"]], facet_pages=here)[2]
class PageTest(unittest.TestCase):
def setUp(self):
self.recs = world(3, 4)
self.infos, self.plan = plan_for(self.recs)
self.p = next(p for p in self.plan if p["lst"].key == "loops")
self.title, self.desc, self.body, _ = placefacets.page(self.p, self.recs, S, self.plan)
self.text = text(self.body)
def test_title_h1_and_lede_use_the_list_noun_and_the_places_own_words(self):
noun = self.p["lst"].noun
self.assertRegex(self.title, rf"^{noun} in the Wind River Range(, Wyoming)?: 3 Trails$")
self.assertIn(f"<h1>{noun} in the Wind River Range</h1>", str(self.body))
self.assertIn("3 of the 7 trails in the Wind River Range", self.text)
self.assertLessEqual(len(self.title), common.TITLE_LIMIT)
def test_a_park_uses_its_own_preposition(self):
infos, plan = plan_for(world(3, 4, (PARK,), "park", "yosemite"), (PARK,))
t = page_of(infos, plan, "loops")[0]
self.assertIn("in Yosemite National Park: 3 Trails", t)
self.assertNotIn("in the Yosemite", t)
def test_the_count_in_the_lede_and_the_rows_agree(self):
rows = len(re.findall(r'data-trail="', str(self.body))) or len(re.findall(r'class="row[ "]', str(self.body)))
self.assertIn("3 of the 7 trails", self.text)
if rows:
self.assertGreaterEqual(rows, 3)
def test_it_links_back_to_the_place_and_the_breadcrumb_goes_through_it(self):
body = str(self.body)
self.assertIn('<li><a href="/ranges/wind-river-range/">Wind River Range</a></li>', body)
self.assertIn('All the trails in the Wind River Range</a>', body)
self.assertIn(f'href="{browse.path(self.p["lst"])}"', body)
def test_the_place_page_links_to_its_list_pages_with_exact_counts(self):
body = text(place_body(self.infos, self.plan, self.recs))
self.assertIn("(3)", body)
self.assertIn(f"{self.p['lst'].title} (3)", body)
def test_siblings_link_to_each_other(self):
recs = world(3, 4)
for r in recs[:3] + recs[3:5]:
r["length_km"] = 100.0 # 5 trails under 100 miles... keep it simple: two pages for one place
infos, plan = plan_for(recs)
mine = [q for q in plan if q["info"]["slug"] == "wind-river-range"]
if len(mine) > 1:
body = str(placefacets.page(mine[0], recs, S, plan)[2])
self.assertIn(mine[1]["path"], body)
def test_no_banned_word_and_no_km_of_a_place(self):
shown = self.text + " " + self.title + " " + self.desc
for pattern in BANNED:
self.assertFalse(re.search(pattern, shown, re.I), pattern)
def test_the_first_screen_comes_before_the_summary(self):
body = str(self.body)
self.assertLess(body.index("browse-view") if "browse-view" in body else body.index("<h1>"),
body.index("About these trails"))
class RealDataTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
from olt import records
cls.records = records.load_records(records.ROOT)
cls.infos = places.collect(cls.records, places.load(records.ROOT))
cls.plan = placefacets.plan_places(cls.infos, cls.records)
def test_every_page_has_three_trails_and_fewer_than_its_place(self):
self.assertTrue(self.plan)
for p in self.plan:
self.assertGreaterEqual(len(p["recs"]), placefacets.PLACE_MIN, p["path"])
self.assertLess(len(p["recs"]), len(p["info"]["records"]), p["path"])
def test_the_number_of_pages_stays_reasonable(self):
self.assertLess(len(self.plan), 250)
def test_every_title_fits_and_keeps_its_count_and_is_unique(self):
titles, over = set(), []
for p in self.plan:
t = placefacets.page(p, self.records, S, self.plan)[0]
self.assertRegex(t, r": \d+ (Trails|Routes)$", t)
titles.add(t)
if len(t) > common.TITLE_LIMIT:
over.append(t)
self.assertEqual(len(titles), len(self.plan))
# only a long place name pushes a title over, and then the shortest noun still keeps the count
self.assertLess(len(over), 25, over)
for t in over:
self.assertGreaterEqual(len(t.rsplit(": ", 1)[0].split(" in ", 1)[-1].split(" on ", 1)[-1]), 25, t)
if __name__ == "__main__":
unittest.main()