Add place plus list pages, and retitle the lists to match how people search
Validate / validate (push) Canceled after 0s
Validate / history (push) Canceled after 0s
Validate / site (push) Canceled after 0s
Validate / deploy (push) Canceled after 0s
Mirror to forge / mirror (push) Canceled after 0s

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-20 18:51:53 -07:00
commit 013ddbefc3
13 files changed
+628 -87

No files matched your search

+20
View File
@@ -1,5 +1,25 @@
# Changelog
## 2026-11-20 - The bulk downloads follow content, not file times
- For contributors: the build now decides whether `all-gpx.zip` and `all-geojson.zip` are up to date by what goes into them, as it does for the rest of the pages, and no longer by the modification times of their files. A file touched with no change leaves them alone, and a changed file with an old time rebuilds them. Nothing a visitor sees changes.
## 2026-11-20 - List titles in the words people search with
- The longest list now opens with the answer: "Longest Hiking Trails in the US and Canada: 25 Trails", and its first line names the longest trail and its length (the Sea-to-Sea Route, 7,775 miles). Two of the 25 cross into Canada, so the title says so. The line is worked out from the trails, so it follows them.
- The length bands: "Hiking Trails Under 100 Miles" is now "Short Thru-Hikes and Loops Under 100 Miles: 102 Trails" and "Thru-Hikes Under 200 Miles" is now "Thru-Hikes and Loops Under 200 Miles: 143 Trails", because 38 of the 102 trails under 100 miles and 43 of the 143 under 200 are loops, not thru-hikes. Their first lines say "short thru-hikes and loops".
- The time bands: "Long Trails to Hike in a Week or Less" is now "Backpacking Trips of a Week or Less: 82 Long Trails", "One to Two Weeks" is "One-to-Two-Week Backpacking Trips: 60 Long Trails", "2 to 4 Weeks" is "Backpacking Trips of 2 to 4 Weeks: 27 Long Trails" and "a Month or More" is "Month-Long Backpacking Trips and Longer: 54 Trails". "in a Weekend" is now "Long-Weekend Backpacking Trips: 17 Long Trails", because every trail in it takes 3 or 4 days to walk.
- Loops: "Loop Hiking Trails" is now "Backpacking Loops: 52 Long Trail Loops". The cross-country list is now "Long Trails with Cross-Country Stretches: 54 Trails", because 38 of its 54 trails have only some cross-country walking and 16 have no trail for most of the way.
- The same words carry into the pages of a state: "Backpacking Loops in Arizona: 9 Trails", "Long Hikes Under 100 Miles in Arizona: 9 Trails", and a new kind, "Backpacking Trips of a Week or Less", which adds 3 state pages (Arizona, California and Wyoming). No address changed.
## 2026-11-20 - Lists inside parks, mountain ranges and wilderness areas
- 84 new pages show one kind of trail in one park, mountain range or wilderness area: 21 for parks, 49 for ranges and 14 for wilderness areas. Examples: "Trails Under 100 Miles in the Wind River Range: 5 Trails", "Routes in Yosemite National Park: 6 Routes", "Lake Trails in Yosemite National Park: 6 Trails". They answer searches such as "short hikes in the Wind River Range", 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, not counting any of 1,000 miles or more: those cross a place without being in it. They are shown on the page when there are 3 others. Trails of 500 miles or more are not crossed with a park or a wilderness area at all, since none lies inside one. A page is not built when its trails are more than three in four of the place's trails (it would repeat the place's own page), when they are nearly the same as another page of the same place, or when a park, a range or a wilderness area holds exactly the same trails for the same list: then one page is built, the park's first, then the range's, then the wilderness area's. The kinds crossed with a place are the ones already crossed with a state: routes, the length bands, a week or less, 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 to the place, to the place's other lists, and to the same list in other places of the same kind (a park to parks, a range to ranges).
- Every title follows one pattern, the same words in the title and the page heading: a fixed short name for the kind of trail, the place's "in" or "in the" and its name, then the count ("Trails Under 100 Miles in the Wind River Range: 5 Trails"; the routes list says "Routes"). A place in one state has the state added when the title stays within the usual length. The 19 pages whose place name alone is long (Sequoia and Kings Canyon National Parks, the Sequoia-Kings Canyon Wilderness, the Appalachian Mountains) run past 60 characters 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 apart from the reworded list titles above.
## 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).
+13 -11
View File
@@ -10,6 +10,7 @@ sys.dont_write_bytecode = True
import argparse
import concurrent.futures
import filecmp
import hashlib
import json
import multiprocessing
@@ -572,21 +573,14 @@ ARCHIVE_TIME = (1980, 1, 1, 0, 0, 0) # the earliest time a zip can hold
def build_archive(name, recs, out_dir, stats):
"""Write /data/<name> (zip, deflate) unless it already holds exactly these files
and is newer than every one of them and than this script."""
"""Write /data/<name> (zip, deflate) unless the archive there is already the one these files
make. What goes in is decided by content (the files' bytes, this build's code and the README),
never by file times: the store holds the archive made from exactly that, and the one in the
output is up to date when it is the same bytes."""
path = os.path.join(out_dir, "data", name)
members = archive_members(name, recs, out_dir, ROOT)
members = [(arc, src) for arc, src in members if os.path.isfile(src)]
expected = ["README.txt"] + [arc for arc, _ in members]
newest = max([mtime(__file__)] + [mtime(src) for _, src in members])
if os.path.isfile(path) and mtime(path) >= newest:
try:
with zipfile.ZipFile(path) as zf:
if zf.namelist() == expected:
stats.skipped += 1
return
except (OSError, zipfile.BadZipFile):
pass
# The store keeps an archive by what goes into it, so one whose files have not changed (in
# content: it does not matter when they were written) is copied, not compressed again.
digest = hashlib.sha256(code_digest().encode() + archive_readme(name).encode())
@@ -595,6 +589,14 @@ def build_archive(name, recs, out_dir, stats):
with open(src, "rb") as f:
digest.update(hashlib.sha256(f.read()).digest())
kept = os.path.join(store_dir(), "archives", f"{name}.{digest.hexdigest()}")
if os.path.isfile(path) and os.path.isfile(kept) and filecmp.cmp(path, kept, shallow=False):
try:
with zipfile.ZipFile(path) as zf:
if zf.namelist() == expected:
stats.skipped += 1
return
except (OSError, zipfile.BadZipFile):
pass
tmp = path + ".tmp" # written beside, then moved over: never a half-written archive
try:
try:
+51 -29
View File
@@ -50,9 +50,14 @@ 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
# list's trails -> a first sentence for the list's page that answers the question the list is
# asked as (the longest trail and its length), put before the blurb.
lede: Optional[Callable] = None
# A larger least size than MIN_SIZE, where the list is thin by nature (a month's list).
min_size: int = 0
# False for a list that is one of a fixed set, so none may go missing: a month's list, however
@@ -67,6 +72,14 @@ def _km(mi):
return words.fmt_int(mi * words.KM_PER_MI)
def longest_lede(recs):
"""The longest hiking trail of the list, by name and length, in the words the question is asked in."""
top = max(recs, key=lambda r: (r["length_km"], r["id"]))
where = "in the US" if "US" in common.countries(top) else "here"
mi = words.fmt_int(top["derived"]["length_mi"])
return f"The longest hiking trail {where} is {common.plain_name(top)}, {mi} miles ({words.fmt_int(top['length_km'])} km)."
def _band(key):
return lambda r: facets.time_band(r) == key
@@ -174,66 +187,74 @@ 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"),
List("longest", "The longest",
List("longest", "The longest hiking trails",
f"Trails of {LONG_MI:,} miles ({_km(LONG_MI)} km) or more.",
lambda r: r["length_km"] >= LONG_KM, sort="length-desc",
page_title=f"Longest Hiking Trails: {{n}} Trails of {LONG_MI:,}+ Miles", group="length"),
page_title=f"Longest Hiking Trails in the US and Canada: {{n}} Trails", group="length",
lede=longest_lede),
List("500-to-1000-miles", f"{HALF_MI} to {LONG_MI:,} miles",
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).",
f"Short thru-hikes and loops: 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"),
page_title=f"Short Thru-Hikes and Loops Under {SHORT_MI} Miles: {{n}} Trails", group="length",
noun=f"Long Hikes 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.",
f"Short thru-hikes and loops: 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",
page_title=f"Thru-Hikes Under {MID_MI} Miles: {{n}} Long Trails", group="length"),
page_title=f"Thru-Hikes and Loops Under {MID_MI} Miles: {{n}} Trails", group="length"),
List("weekend", "A weekend or long weekend",
f"Trails that take {WEEKEND_DAYS} days or fewer to walk whole.",
f"Backpacking trips of {WEEKEND_DAYS} days or fewer: trails that take that long to walk whole.",
lambda r: _mid_days(r) <= WEEKEND_DAYS, sort="time-asc",
page_title="Long Trails to Hike in a Weekend: {n} Trails", group="time", note=time_note),
page_title="Long-Weekend Backpacking Trips: {n} Long Trails", group="time", note=time_note),
List("a-week-or-less", "A week or less",
"Trails most people walk in a week or less, as a source states it or as estimated from the length.",
_band("week"), sort="time-asc", page_title="Long Trails to Hike in a Week or Less: {n} Trails",
group="time", note=time_note),
"Backpacking trips of a week or less: trails most people walk in a week or less, as a source states it or as estimated from the length.",
_band("week"), sort="time-asc", page_title="Backpacking Trips of a Week or Less: {n} Long Trails",
group="time", note=time_note, noun="Backpacking Trips of a Week or Less", short="Trips of a Week or Less"),
List("one-to-two-weeks", "One to two weeks",
"Trails that take one to two weeks, as a source states it or as estimated from the length.",
_band("two-weeks"), sort="time-asc", page_title="Long Trails to Hike in One to Two Weeks: {n} Trails",
"Backpacking trips of one to two weeks, as a source states it or as estimated from the length.",
_band("two-weeks"), sort="time-asc", page_title="One-to-Two-Week Backpacking Trips: {n} Long Trails",
group="time", note=time_note),
List("two-to-four-weeks", "Two weeks to a month",
"Trails that take two to four weeks to walk whole.",
_band("month"), sort="time-asc", page_title="Long Trails to Hike in 2 to 4 Weeks: {n} Trails",
"Backpacking trips of two to four weeks: trails that take that long to walk whole.",
_band("month"), sort="time-asc", page_title="Backpacking Trips of 2 to 4 Weeks: {n} Long Trails",
group="time", note=time_note),
List("a-month-or-more", "A month or more",
"Trails that take more than four weeks to walk whole.",
"Month-long backpacking trips and longer: trails that take more than four weeks to walk whole.",
lambda r: facets.time_band(r) in ("months", "long"), sort="time-asc",
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"),
page_title="Month-Long Backpacking Trips and Longer: {n} Trails", group="time", note=time_note),
List("loops", "Loops", "Backpacking loops: trails that finish where they start.",
lambda r: facets.shape(r) == "loop", page_title="Backpacking Loops: {n} Long Trail Loops",
group="walking", noun="Backpacking Loops",
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"),
page_title="Long Trails with Cross-Country Stretches: {n} Trails", group="walking",
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 +282,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 +294,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)
+127 -31
View File
@@ -3,9 +3,12 @@
For every place and every list that has a `noun` (olt/browse.py), the page exists when the place has at
least MIN_SIZE trails in the list, no more than MAX_SHARE of the place's trails are in it (else it
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.
the same place. For a park, range or wilderness area, a trail of 1,000 miles or more is shown but does
not count toward the 3 needed, and pages of different places for one list that hold exactly the same
trails are one page (the park's, else the range's, else the wilderness area's). 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 +18,98 @@ 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()
# A trail this long crosses a place and is not "in" it: it is shown on a place's list page but does
# not count toward the PLACE_MIN needed to build one.
VERY_LONG_KM = browse.LONG_KM
# Length bands of 500 miles or more are not crossed with a park or a wilderness area: no trail that
# long lies inside one. A range may keep them.
OUT_BY_KIND = {"park": frozenset({"500-to-1000-miles"}), "wilderness": frozenset({"500-to-1000-miles"})}
def _plan(units, records, min_size, path_of, lists, max_share, count_long=True):
"""[{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. With count_long False
a trail of VERY_LONG_KM or more is shown but not counted toward min_size."""
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():
if lst.key not in shown:
for lst in lists:
if lst.key not in shown or lst.key in OUT_BY_KIND.get(info["kind"], ()):
continue
recs = browse.members(lst, here)
if len(recs) < browse.MIN_SIZE or len(recs) > browse.MAX_SHARE * len(here):
counted = len(recs) if count_long else sum(1 for r in recs if r["length_km"] < VERY_LONG_KM)
if counted < 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 _one_page_per_set(_plan(units, records, PLACE_MIN, lambda slug, info, lst: f"{info['path']}{lst.key}/",
lists, max_share, count_long=False))
def _one_page_per_set(pages):
"""Of the place pages of one list that hold exactly the same trails, keep one: the park's, else
the range's, else the wilderness area's; of two of a kind, the place with fewer trails (the more
specific), then the name. The others are dropped, and nothing links to them."""
rank = {"park": 0, "range": 1, "wilderness": 2}
best = {}
for p in pages:
k = (p["lst"].key, frozenset(r["id"] for r in p["recs"]))
mine = (rank[p["kind"]], len(p["info"]["records"]), p["info"]["name"].lower())
if k not in best or mine < best[k][0]:
best[k] = (mine, p)
keep = {id(v[1]) for v in best.values()}
return [p for p in pages if id(p) in keep]
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 place_noun(lst):
"""The short noun a place page's title and heading use for the list, the same whatever the name."""
return lst.short or lst.noun
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 +122,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 +131,65 @@ 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"]
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}"
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)
if state:
only_routes = all(facets.kind(r) == "route" for r in recs)
count = f"{len(recs)} {'Routes' if only_routes else 'Trails'}"
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}"]
h1 = f"{lst.noun} {phrase}"
else:
# One fixed pattern: <short noun> <the place's preposition and name>: <N> Trails (Routes for
# the routes list). The state follows a place in one state when the title still fits; a long
# place name runs long and keeps its count. The heading is the title.
count = f"{len(recs)} {'Routes' if lst.key == 'routes' else 'Trails'}"
noun = place_noun(lst)
ladder = [f"{noun} {prep} {title_name}: {count}", f"{noun} {prep} {name}: {count}"]
title = common.fit_title(ladder, site)
if not state:
h1 = title
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 +199,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
+3 -2
View File
@@ -528,7 +528,7 @@ def list_page(lst, recs, total, site, *, records=None, before="", after="", lead
<header class="titleblock"><div class="titleblock__text">
<p class="kicker">A list</p>
<h1>{esc(lst.title)}</h1>
<p class="page-head__lede">{esc(lst.blurb)} {_plural(len(recs))}, {n_gpx} with a GPX here.</p>
<p class="page-head__lede">{esc(lst.lede(recs) + " " if lst.lede else "")}{esc(lst.blurb)} {_plural(len(recs))}, {n_gpx} with a GPX here.</p>
</div></header>
</div></div>
<div class="container section place">
@@ -543,7 +543,8 @@ def list_page(lst, recs, total, site, *, records=None, before="", after="", lead
stats = [f" {_plural(len(recs))}, from {common.plain_name(by_length[0])}, {_miles(by_length[0])} miles, "
f"to {common.plain_name(by_length[-1])}, {_miles(by_length[-1])} miles; {_with_gpx(n_gpx, len(recs)) or 'none with a GPX here'}.",
f" {_plural(len(recs))}, {_with_gpx(n_gpx, len(recs)) or 'none with a GPX here'}.", f" {_plural(len(recs))}."]
desc = _fit([lst.blurb + s for s in stats] + [lst.blurb])
first = f"{lst.lede(recs)} " if lst.lede else ""
desc = _fit([first + lst.blurb + s for s in stats] + [first + lst.blurb, lst.blurb])
return lst.search_title(len(recs)), desc, Markup(body), home.has_overview_map(recs)
+1 -1
View File
@@ -6,7 +6,7 @@
"/regions/mountain-west/": "6151f5a28d366fb48aab7027f08cea6da425201d0e7327780a01dd77cedc7bc7",
"/regions/north/": "85ba3ea850c2df690e311cf09257f2548ed888c07c319a01fd30d5e19cdf1fd4",
"/regions/us-co/": "97daaf3511578896b222570cba630da2d8ca0571504ce43b3685dbe532e40f56",
"/regions/us-co/loops/": "03896834b5369655f7b5f26634b6d23c834b17f1a25b0ec328d44934e20e2dfa",
"/regions/us-co/loops/": "5a116735c701f1840ad00646a02682afc177c585fc06763f5b5a6b8afccff4a8",
"/regions/us-co/with-gpx/": "d82eace3d70eb9b1ef1346f5a3470199bd6a00e6e104fe661bfeb80199af96b8",
"/regions/us-hi/": "1e5681ffbd50e382db7d69528fde602069006bf0cddad494d817369224bd96ad",
"/regions/us-ut/": "906db4153def35fa5418d0b86dba908fd27396bbc2098978ee169516e1b39785",
+19 -5
View File
@@ -227,7 +227,7 @@ class BuildTreeTest(unittest.TestCase):
build.main(["--out", self.out])
self.assertIn("trails processed 0", out.getvalue())
def test_archives_rebuilt_only_when_an_input_is_newer(self):
def test_archives_rebuilt_only_when_an_input_changes_in_content(self):
self.build()
gpx, geojson = self.path("data", "all-gpx.zip"), self.path("data", "all-geojson.zip")
with zipfile.ZipFile(gpx) as zf:
@@ -253,12 +253,26 @@ class BuildTreeTest(unittest.TestCase):
stamps = (os.path.getmtime(gpx), os.path.getmtime(geojson))
self.build()
self.assertEqual((os.path.getmtime(gpx), os.path.getmtime(geojson)), stamps)
# a newer input (here a release.txt) rebuilds both archives
# a release.txt touched to a later time, with the same content, is not a change
later = max(stamps) + 10
os.utime(os.path.join(self.root, "avon", "release.txt"), (later, later))
release = os.path.join(self.root, "avon", "release.txt")
os.utime(release, (later, later))
self.build()
self.assertNotEqual(os.path.getmtime(gpx), stamps[0])
self.assertNotEqual(os.path.getmtime(geojson), stamps[1])
self.assertEqual((os.path.getmtime(gpx), os.path.getmtime(geojson)), stamps)
# nor is an archive older than every input (put back to an old time)
os.utime(gpx, (1000, 1000))
os.utime(geojson, (1000, 1000))
self.build()
self.assertEqual((os.path.getmtime(gpx), os.path.getmtime(geojson)), (1000, 1000))
# but a release.txt with other content rebuilds both archives, with the new content in them
with open(release, "a", encoding="utf-8") as f:
f.write("\nChanged.\n")
os.utime(release, (1, 1)) # and with an old time: the content decides
self.build()
self.assertNotEqual(os.path.getmtime(gpx), 1000)
self.assertNotEqual(os.path.getmtime(geojson), 1000)
with zipfile.ZipFile(gpx) as zf:
self.assertIn("Changed.", zf.read("avon/release.txt").decode("utf-8"))
def test_archive_members_are_regular_files_with_the_usual_mode(self):
self.build()
+71
View File
@@ -0,0 +1,71 @@
"""The wording of the ready-made lists (olt/browse.py): titles in the words people search with.
Addresses and rules do not change; only title, blurb, page_title, noun and lede."""
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, records # noqa: E402
from test_facets import BANNED # noqa: E402
KEYS = ['national-scenic-trails', 'national-recreation-trails', 'routes', 'high-routes', 'longest', '500-to-1000-miles', '200-to-500-miles', '100-to-200-miles', 'under-100-miles', 'under-200-miles', 'weekend', 'a-week-or-less', 'one-to-two-weeks', 'two-to-four-weeks', 'a-month-or-more', 'loops', 'off-trail', 'mostly-cross-country', 'unfinished', 'parks-canada', 'forest-service', 'state-and-provincial-parks', 'clubs-and-associations', 'with-gpx', 'canada', 'united-states', 'terrain-alpine', 'terrain-forest', 'terrain-desert', 'terrain-coast', 'terrain-prairie', 'terrain-canyon', 'terrain-tundra', 'terrain-lakes', 'terrain-farmland', 'hike-in-january', 'hike-in-february', 'hike-in-march', 'hike-in-april', 'hike-in-may', 'hike-in-june', 'hike-in-july', 'hike-in-august', 'hike-in-september', 'hike-in-october', 'hike-in-november', 'hike-in-december']
class ListWordingTest(unittest.TestCase):
def test_list_urls_and_keys_are_unchanged(self):
self.assertEqual([lst.key for lst in browse.LISTS], KEYS)
self.assertEqual(browse.path(browse.by_key("loops")), "/lists/loops/")
self.assertEqual(browse.path(browse.by_key("routes")), "/routes/")
def test_the_reworded_lists_have_the_new_page_titles(self):
want = {
"longest": "Longest Hiking Trails in the US and Canada: 7 Trails",
"under-100-miles": "Short Thru-Hikes and Loops Under 100 Miles: 7 Trails",
"under-200-miles": "Thru-Hikes and Loops Under 200 Miles: 7 Trails",
"a-week-or-less": "Backpacking Trips of a Week or Less: 7 Long Trails",
"weekend": "Long-Weekend Backpacking Trips: 7 Long Trails",
"off-trail": "Long Trails with Cross-Country Stretches: 7 Trails",
"loops": "Backpacking Loops: 7 Long Trail Loops",
}
for key, title in want.items():
self.assertEqual(browse.by_key(key).search_title(7), title)
def test_a_loop_is_never_called_a_thru_hike_alone(self):
# the length bands hold loops too, so their titles say so
for key in ("under-100-miles", "under-200-miles"):
self.assertIn("Loops", browse.by_key(key).page_title)
self.assertNotIn("thru", browse.by_key("loops").page_title.lower())
def test_the_week_band_has_a_noun_and_loops_say_backpacking(self):
self.assertEqual(browse.by_key("a-week-or-less").noun, "Backpacking Trips of a Week or Less")
self.assertEqual(browse.by_key("loops").noun, "Backpacking Loops")
def test_no_banned_word_and_no_best_in_any_list_wording(self):
for lst in browse.LISTS:
for text in (lst.title, lst.blurb, lst.search_title(9), lst.noun, lst.short):
for pattern in BANNED:
self.assertIsNone(re.search(pattern, text, re.I), (lst.key, text))
self.assertIsNone(re.search(r"\bbest\b", text, re.I), (lst.key, text))
def test_every_search_title_is_unique_and_fits(self):
titles = [lst.search_title(99) for lst in browse.LISTS]
self.assertEqual(len(titles), len(set(titles)))
for t in titles:
self.assertLessEqual(len(t), common.TITLE_LIMIT, t)
def test_the_longest_list_names_the_longest_trail_and_its_length_first(self):
recs = records.load_records(records.ROOT)
lst = browse.by_key("longest")
top = max(browse.members(lst, recs), key=lambda r: (r["length_km"], r["id"]))
first = lst.lede(browse.members(lst, recs))
self.assertTrue(first.startswith("The longest hiking trail"), first)
self.assertIn(common.plain_name(top), first)
self.assertIn(f"{top['derived']['length_mi']:,.0f} miles", first)
if __name__ == "__main__":
unittest.main()
+312
View File
@@ -0,0 +1,312 @@
"""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)
class VeryLongTrailsTest(unittest.TestCase):
"""A trail of 1,000 miles or more is shown on a place's list page but does not count to its 3."""
LONG_KM = 1700
def world_of(self, normal, long, kind="range", slug="wind-river-range", entries=(RANGE,), km=150):
recs = [in_place(100 + i, kind, slug, loop=True, km=km) for i in range(normal)]
recs += [in_place(150 + i, kind, slug, loop=True, km=self.LONG_KM) for i in range(long)]
recs += [in_place(200 + i, kind, slug, loop=False, km=150) for i in range(8)]
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 loops(self, recs, **kw):
_, plan = plan_for(recs, **kw)
return next((p for p in plan if p["lst"].key == "loops"), None)
def test_two_ordinary_trails_and_a_very_long_one_make_no_page(self):
self.assertIsNone(self.loops(self.world_of(2, 1)))
self.assertIsNone(self.loops(self.world_of(0, 3)))
def test_three_ordinary_trails_make_a_page_that_also_shows_the_very_long_one(self):
p = self.loops(self.world_of(3, 1))
self.assertIsNotNone(p)
self.assertEqual(len(p["recs"]), 4)
def test_the_state_plan_still_counts_every_trail(self):
plan = placefacets.plan(self.world_of(2, 1))
self.assertTrue(all(len(p["recs"]) >= browse.MIN_SIZE for p in plan))
def test_a_park_or_wilderness_gets_no_page_for_the_500_to_1000_mile_band(self):
for kind in ("park", "wilderness"):
entry = entry_of(kind, "somewhere", "Somewhere", ["WY"])
recs = self.world_of(4, 0, kind, "somewhere", (entry,), km=1000)
_, plan = plan_for(recs, (entry,))
self.assertNotIn("500-to-1000-miles", self.keys(plan), kind)
def test_a_range_keeps_the_500_to_1000_mile_band(self):
recs = self.world_of(4, 0, km=1000)
_, plan = plan_for(recs)
self.assertIn("500-to-1000-miles", self.keys(plan))
def keys(self, plan):
return {p["lst"].key for p in plan}
def shared_world(places, loops=3):
"""places: [(entry, how many other trails it has)]. All of them share the same `loops` loops;
each has its own other trails; and enough loops and long trails elsewhere for the list to be shown."""
every = [(e["kind"], e["slug"]) for e, _ in places]
recs = [rec(100 + i, f"Shared loop {i}", every, km=150) for i in range(loops)]
for r in recs:
r["hike"] = dict(r["hike"], shape="loop")
for n, (e, others) in enumerate(places):
recs += [rec(1000 * (n + 1) + i, f"Own {n} {i}", [(e["kind"], e["slug"])], km=150) for i in range(others)]
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
class ShareAndSameSetTest(unittest.TestCase):
def paths(self, places, loops=3):
entries = [e for e, _ in places]
_, plan = plan_for(shared_world(places, loops), entries)
return sorted(p["path"] for p in plan if p["lst"].key == "loops")
def test_a_page_holding_more_than_three_quarters_of_its_place_is_not_built(self):
self.assertEqual(self.paths([(RANGE, 1)], loops=3), ["/ranges/wind-river-range/loops/"]) # 3 of 4
self.assertEqual(self.paths([(RANGE, 1)], loops=4), []) # 4 of 5
def test_one_set_in_a_park_a_range_and_a_wilderness_is_one_page_under_the_park(self):
park = entry_of("park", "grand-test", "Grand Test National Park", ["WY"])
rng = entry_of("range", "test-range", "Test Range", ["WY"])
wild = entry_of("wilderness", "test-wild", "Test Wilderness", ["WY"])
self.assertEqual(self.paths([(wild, 3), (rng, 4), (park, 5)]), ["/parks/grand-test/loops/"])
self.assertEqual(self.paths([(wild, 3), (rng, 4)]), ["/ranges/test-range/loops/"])
def test_of_two_of_one_kind_the_more_specific_place_wins_then_the_name(self):
a = entry_of("range", "a-range", "A Range", ["WY"])
b = entry_of("range", "b-range", "B Range", ["WY"])
self.assertEqual(self.paths([(a, 6), (b, 3)]), ["/ranges/b-range/loops/"])
self.assertEqual(self.paths([(b, 4), (a, 4)]), ["/ranges/a-range/loops/"])
def test_different_sets_keep_a_page_each(self):
a = entry_of("range", "a-range", "A Range", ["WY"])
b = entry_of("range", "b-range", "B Range", ["WY"])
recs = shared_world([(a, 4), (b, 4)])
for r in recs:
if r["name"] == "Own 1 0":
r["hike"] = dict(r["hike"], shape="loop") # b has a loop of its own
_, plan = plan_for(recs, [a, b])
self.assertEqual(sorted(p["path"] for p in plan if p["lst"].key == "loops"),
["/ranges/a-range/loops/", "/ranges/b-range/loops/"])
def test_the_place_left_without_a_page_links_to_nothing_for_the_list(self):
park = entry_of("park", "grand-test", "Grand Test National Park", ["WY"])
rng = entry_of("range", "test-range", "Test Range", ["WY"])
_, plan = plan_for(shared_world([(rng, 4), (park, 5)]), [rng, park])
self.assertEqual({k for p in plan if p["kind"] == "range" for k in [p["lst"].key]} & {"loops"}, set())
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):
self.assertRegex(self.title, r"^Loops in the Wind River Range(, Wyoming)?: 3 Trails$")
self.assertIn(f"<h1>{self.title}</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_follows_the_one_pattern_and_the_heading_has_the_same_words(self):
titles = set()
for p in self.plan:
title, _, body, _ = placefacets.page(p, self.records, S, self.plan)
info = p["info"]
noun = placefacets.place_noun(p["lst"])
count = f"{len(p['recs'])} {'Routes' if p['lst'].key == 'routes' else 'Trails'}"
prep = places.prep_of(info)
with_state = f"{noun} {prep} {info['title_name']}: {count}"
without = f"{noun} {prep} {info['name']}: {count}"
expect = with_state if len(with_state) <= common.title_room(S) else without
self.assertEqual(title, expect, p["path"])
self.assertIn(f"<h1>{title}</h1>", str(body), p["path"])
titles.add(title)
self.assertEqual(len(titles), len(self.plan))
def test_the_nouns_are_the_fixed_short_ones(self):
got = {p["lst"].key: placefacets.place_noun(p["lst"]) for p in self.plan}
want = {"under-100-miles": "Trails Under 100 Miles", "100-to-200-miles": "100 to 200 Mile Trails",
"200-to-500-miles": "200 to 500 Mile Trails", "500-to-1000-miles": "500 to 1,000 Mile Trails",
"loops": "Loops", "routes": "Routes", "a-week-or-less": "Trips of a Week or Less",
"off-trail": "Cross-Country Hikes", "with-gpx": "Trails with a GPX"}
for key, noun in want.items():
if key in got:
self.assertEqual(got[key], noun)
for key, noun in got.items():
if key.startswith("terrain-"):
self.assertTrue(noun.endswith(" Trails"), noun)
if __name__ == "__main__":
unittest.main()
+2 -2
View File
@@ -188,13 +188,13 @@ class PlaceAndListTitleTest(unittest.TestCase):
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")
self.assertEqual(browse.by_key("loops").search_title(32), "Backpacking Loops: 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.assertTrue(title.startswith("Short Thru-Hikes and Loops Under 100 Miles: 4"))
self.assertLessEqual(len(desc), common.DESCRIPTION_LIMIT)
self.assertTrue(desc.startswith(lst.blurb))
self.assertIn("4 trails", desc)
+1 -1
View File
@@ -55,7 +55,7 @@ class LengthBandTest(unittest.TestCase):
def test_under_200_is_the_two_short_bands(self):
recs = [fake(1, km=mi(50)), fake(2, km=mi(150)), fake(3, km=mi(250))]
self.assertEqual(sorted(keys(recs, "under-200-miles")), ["t1", "t2"])
self.assertTrue(browse.by_key("under-200-miles").search_title(9).startswith("Thru-Hikes Under 200 Miles"))
self.assertTrue(browse.by_key("under-200-miles").search_title(9).startswith("Thru-Hikes and Loops Under 200 Miles"))
class TimeListTest(unittest.TestCase):