Link the place pages from the hub, the states and the trails, and search by place

This commit is contained in:
swaits committed 2026-11-20 10:55:36 -07:00
1 parent 16c5275c94
commit 00c60a4c2c
10 files changed
+387 -35

No files matched your search

+32
View File
@@ -62,6 +62,38 @@ Terms found: none. No route creator's page read on 2026-11-10 states a licence f
Page: the creator's or publisher's own page for the guide, given in each record's first `[[guide]]` and quoted in `route.creator_words_url` where the creator's words are quoted.
## National Park Service park boundaries (public domain)
Used for: the outlines behind the park pages. `tools/place_trails.py` measures each trail's track against the Land Resources Division boundary service and writes the trail's park membership to its record and to `places.toml`. The outlines themselves are not in this repository; they are downloaded to a cache outside it.
Quoted terms: "The data are in the public domain, and may be re-used without restriction."
Page: https://irma.nps.gov/DataStore/Reference/Profile/2224545 (read 2026-11-20). United States federal government work is public domain in the United States under 17 U.S.C. 105 (see "United States federal agencies" above). Credit: National Park Service, Land Resources Division.
## Wilderness Connect wilderness boundaries (public domain)
Used for: the outlines behind the wilderness area pages, all four federal agencies in one file. `tools/place_trails.py` measures each trail's track against them; the outlines are cached outside this repository.
Quoted terms: "This data is available for public use of any kind. Crediting Wilderness Connect is requested."
Page: https://wilderness.net/visit-wilderness/gis-gps.php (read 2026-11-20). Federal work, public domain. The credit the page requests is given here: Wilderness Connect, University of Montana (wilderness.net).
## Canadian Protected and Conserved Areas Database (Open Government Licence, Canada)
Used for: the outlines of Canadian national parks and of British Columbia and Alberta provincial parks, measured by `tools/place_trails.py` and cached outside this repository.
Quoted terms: "Copy, modify, publish, translate, adapt, distribute or otherwise use the Information in any medium, mode or format for any lawful purpose."
Page: https://open.canada.ca/data/dataset/6c343726-1e92-451a-876a-76e17d398a1c and the licence at https://open.canada.ca/en/open-government-licence-canada (read 2026-11-20). Credit: Environment and Climate Change Canada, CPCAD. Contains information licensed under the Open Government Licence – Canada.
## GMBA Mountain Inventory v2 (CC BY 4.0)
Used for: the outlines behind the mountain range pages, the allow-listed ranges only (`tools/place_allowlist.toml`), measured by `tools/place_trails.py` and cached outside this repository.
Quoted terms: the inventory's licence reads "CC BY 4.0".
Page: https://www.earthenv.org/mountains and https://doi.org/10.48601/earthenv-t9k2-1407 (read 2026-11-20). Full text: LICENSES/CC-BY-4.0.txt. Credit required: GMBA Mountain Inventory v2 (Snethlage et al. 2022), via EarthEnv.
## Every record's source
+17 -4
View File
@@ -31,7 +31,7 @@ import os
import shutil
from .markup import esc
from . import authors, browse, cards, datafiles, docs, facets, feed, home, layout, leftout, pagekit, placefacets, placepages, reference, regions, saved, seo, site as site_settings, sketch, standing, thumbs, trail, views
from . import authors, browse, cards, datafiles, docs, facets, feed, home, layout, leftout, pagekit, placefacets, placepages, places, reference, regions, saved, searchtext, seo, site as site_settings, sketch, standing, thumbs, trail, views
WEB_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
ASSETS_DIR = os.path.join(WEB_DIR, "assets")
@@ -99,13 +99,24 @@ def render_site(records, out_dir, repo_root, site=None):
everything = seo.newest(records)
author_links = authors.link_map(records, repo_root)
home.use_authors(author_links)
# The parks, ranges and wilderness areas (olt/places.py): which have a page, for
# the links on trail and state pages and the hub, and every trail's place names
# for search, a page or not.
registry = places.load(repo_root)
place_infos = places.collect(records, registry)
search_names = {}
for key, recs in places.membership(records, registry).items():
for r in recs:
search_names.setdefault(r["id"], []).append(registry[key].get("name", ""))
searchtext.use_place_names(search_names)
for rec in records:
# Read by common.name() wherever a page shows the record's name as text.
rec["derived"]["name_lang"] = site.name_lang.get(rec["id"], "")
for rec in records:
copy_record_files(rec, out_dir, repo_root)
thumbs.prepare(rec, out_dir, repo_root)
title, description, body, needs_map = trail.render(rec, site, records, author_links=author_links)
title, description, body, needs_map = trail.render(
rec, site, records, author_links=author_links, place_infos=place_infos)
path = f"/trails/{rec['id']}/"
card, card_alt = cards.prepare(rec, out_dir)
layout.write_page(out_dir, path, layout.layout(
@@ -140,13 +151,15 @@ def render_site(records, out_dir, repo_root, site=None):
shown = browse.shown(records)
facet_plan = placefacets.plan(records)
facets_of_place = placefacets.pages_by_place(facet_plan)
t, d, b = regions.regions_index_page(records, site)
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
by_slug, _ = regions.collect_regions(records)
region_paths = []
for slug in sorted(by_slug):
here = [(p["lst"].title, p["path"], len(p["recs"])) for p in facets_of_place.get(slug, [])]
t, d, b, needs_map = regions.region_page(slug, records, site, facet_pages=here)
t, d, b, needs_map = regions.region_page(
slug, records, site, facet_pages=here,
place_links=regions.place_links_for(by_slug[slug]["key"], place_infos))
path = f"/regions/{slug}/"
region_paths.append(path)
add(path, t, d, b, maps=needs_map, recs=by_slug[slug]["records"])
+1 -6
View File
@@ -16,12 +16,7 @@ Built = namedtuple("Built", ("path", "title", "description", "body", "needs_map"
def _in_name(info):
"""The name as it reads after "in": a range or a wilderness area takes "the"
("in the Wind River Range"), a park does not ("in Yosemite National Park")."""
name = info["name"]
if info["kind"] in ("range", "wilderness") and not name.lower().startswith("the "):
return f"the {name}"
return name
return places.in_name(info)
def _title_place(info):
+9
View File
@@ -99,6 +99,15 @@ def state_names(info):
return [words.region_name(_state_key(c).split("-", 1)[-1]) for c in info.get("where") or []]
def in_name(info):
"""The name as it reads after "in": a range or a wilderness area takes "the"
("in the Wind River Range"), a park does not ("in Yosemite National Park")."""
name = info["name"]
if info.get("kind") in ("range", "wilderness") and not name.lower().startswith("the "):
return f"the {name}"
return name
def title_name(info):
"""The place as a page title names it: a park by its name alone; a range or a
wilderness area in one state or province with that state spelled out
+34 -4
View File
@@ -7,7 +7,7 @@ The section is called Places; its pages keep their /regions/ URLs.
import collections
from dataclasses import dataclass
from . import bounds, browse, common, facets, home, leftout, summary, words
from . import bounds, browse, common, facets, home, leftout, places, summary, words
from .markup import Markup, esc
@@ -147,9 +147,25 @@ def lists_here(recs, records):
return parts
def regions_index_page(records, site):
"""(title, description, body) for /regions/: the Places hub."""
def place_links_for(state_key, infos):
"""The nav a state page carries to the parks, ranges and wilderness areas in it
that have a page, each with its exact count; empty when there are none. infos:
olt/places.py collect. state_key as in olt/facets.py ("US-CO")."""
here = places.in_state(infos, state_key)
if not here:
return Markup("")
name = facets.place_name(state_key)
links = " · ".join(f'<a href="{esc(i["path"])}">{esc(i["name"])}</a> ({len(i["records"])})'
for i in here)
return Markup(f'<nav class="region-nav" aria-label="Parks, ranges and wilderness in {esc(name)}">'
f'Parks, ranges and wilderness in {esc(name)}, and how many trails in each: {links}</nav>')
def regions_index_page(records, site, infos=()):
"""(title, description, body) for /regions/: the Places hub. infos: the places with
a page (olt/places.py collect); each kind that has any gets a section of its own."""
by_slug, across = collect_regions(records)
place_infos = list(infos.values()) if isinstance(infos, dict) else list(infos or ())
blocks = ""
jump = []
for g, name, keys in facets.PLACE_GROUPS:
@@ -176,6 +192,20 @@ def regions_index_page(records, site):
<p class="places__sum">{_plural(len(across))} that {"crosses" if len(across) == 1 else "cross"} the whole country rather than one province: {links}.
{"It is" if len(across) == 1 else "They are"} counted in every Canadian group, and on no single province&rsquo;s page.</p>
</section>"""
for kind in places.KINDS.values():
mine = sorted((i for i in place_infos if i["kind"] == kind.key), key=lambda i: i["name"])
if not mine:
continue
rows = "".join(
f'<li><a href="{esc(i["path"])}">{esc(i["name"])}</a>'
f'<span class="places__n">{_plural(len(i["records"]))}</span></li>'
for i in mine)
blocks += f"""<section class="places__group" aria-labelledby="{esc(kind.segment)}">
<h2 id="{esc(kind.segment)}">{esc(kind.hub_title)}</h2>
<ul class="places__list">{rows}</ul>
</section>"""
lede_more = (" Parks, mountain ranges and wilderness areas with three or more trails have pages too."
if place_infos else "")
none = empty_places(records)
foot = ""
if none:
@@ -186,7 +216,7 @@ def regions_index_page(records, site):
body = f"""<div class="page-head"><div class="container"><header class="titleblock">
<div class="titleblock__text"><h1>Places</h1>
<p class="page-head__lede">The {len(records)} trails by state and province, grouped into parts of the
United States ({n_us}) and Canada ({n_ca}). A trail that crosses several states is on each one&rsquo;s page.</p>
United States ({n_us}) and Canada ({n_ca}). A trail that crosses several states is on each one&rsquo;s page.{lede_more}</p>
</div></header>
<nav class="lists-row" aria-label="Jump to a part of the country"><ul>{"".join(jump)}</ul></nav></div></div>
<div class="container section places">{blocks}</div>{foot}"""
+49 -9
View File
@@ -5,7 +5,8 @@ A row's words come in four tiers, strongest first, so that the list can put the
0 name the name, its common name, its abbreviation and its id
1 author who made a route
2 places the full names of the states and provinces it lies in, the countries, the place it
starts and the place it ends, and the land unit or managing body its record names
starts and the place it ends, the land unit or managing body its record names, and
the parks, mountain ranges and wilderness areas it is in (place_names)
3 summary the trail's summary
Each tier is folded (fold) and written once per word (the summary's words of fewer than three letters are
@@ -37,9 +38,47 @@ def fold(text):
return _NOT_WORD.sub(" ", _APOSTROPHES.sub("", text)).strip()
def place_names(rec):
# {record id: [place name]} for every park, range and wilderness area a trail is in
# (olt/places.py membership, parents included), set by pages.render_site through
# use_place_names: typing "wind river" then finds the trails of the range, whether
# or not the place has a page. Like home's author links, it is build state.
_PLACE_NAMES = {}
def use_place_names(mapping):
_PLACE_NAMES.clear()
_PLACE_NAMES.update({k: list(v) for k, v in (mapping or {}).items()})
def _names_from_infos(rec, infos):
"""The names of a record's places out of infos: the infos of places.collect (a dict
keyed (kind, slug), or a list of them; their records already include the parents),
or a registry in the same keying, whose names the record's [[place]] tables pick
out, with every `within` parent. [] when infos is neither."""
if isinstance(infos, dict) and infos and all(isinstance(k, tuple) for k in infos):
if any(isinstance(v, dict) and "records" in v for v in infos.values()):
return [v["name"] for v in infos.values()
if any(r["id"] == rec["id"] for r in v.get("records") or [])]
out, stack = [], [(p.get("kind"), p.get("slug")) for p in rec.get("place") or []
if isinstance(p, dict)]
seen = set()
while stack:
key = stack.pop(0)
if key in seen or key not in infos:
continue
seen.add(key)
out.append(infos[key].get("name", ""))
stack += [("range", s) for s in infos[key].get("within") or []]
return out
return [i["name"] for i in infos or ()
if isinstance(i, dict) and any(r["id"] == rec["id"] for r in i.get("records") or [])]
def place_names(rec, infos=()):
"""The names of the places a record carries: states, provinces and countries in full, where it
starts and ends, and the land unit or body of its designation."""
starts and ends, the land unit or body of its designation, and the parks, mountain
ranges and wilderness areas it is in (from infos where given, else the names the
build set with use_place_names)."""
names = [facets.place_name(k) for k in facets.place_keys(rec)]
names += [words.COUNTRIES.get(c, c) for c in common.countries(rec)]
h = hike.table(rec)
@@ -47,24 +86,25 @@ def place_names(rec):
designation = rec.get("designation", "")
if designation and not _NO_BODY.match(designation):
names.append(designation)
names += _names_from_infos(rec, infos) if infos else _PLACE_NAMES.get(rec["id"], [])
return [n for n in names if isinstance(n, str) and n.strip()]
def tier_texts(rec):
def tier_texts(rec, infos=()):
"""The four texts of a record, unfolded."""
return [
" ".join([rec["name"], rec.get("common_name", ""), rec.get("short_name", ""), rec["id"]]),
facets.author(rec),
" ".join(place_names(rec)),
" ".join(place_names(rec, infos)),
hike.table(rec).get("summary", ""),
]
def tiers(rec):
def tiers(rec, infos=()):
"""The four tiers as lists of words, each word in the strongest tier that has it."""
seen = set()
out = []
for i, text in enumerate(tier_texts(rec)):
for i, text in enumerate(tier_texts(rec, infos)):
mine = []
for word in fold(text).split():
if i == SUMMARY and len(word) < SUMMARY_MIN:
@@ -76,6 +116,6 @@ def tiers(rec):
return out
def attribute(rec):
def attribute(rec, infos=()):
"""The value of a row's data-search: the tiers' words, tiers joined with "|"."""
return "|".join(" ".join(t) for t in tiers(rec))
return "|".join(" ".join(t) for t in tiers(rec, infos))
+38 -11
View File
@@ -9,7 +9,7 @@ import os
import re
import urllib.parse
from . import browse, common, elevation, facets, hike, regions, related, seo, sketch, words
from . import browse, common, elevation, facets, hike, places, regions, related, seo, sketch, words
from .layout import OUTDOOR_STYLE
from .markup import Markup, esc
@@ -83,6 +83,15 @@ def region_names(rec):
return Markup((", " if len(keys) <= 3 else " ").join(parts))
def place_links(rec, infos):
"""One link per park, range or wilderness area of this trail that has a page
(olt/places.py collect), for the glance beside its states; "" when none has."""
mine = places.of_record(rec, infos)
if not mine:
return Markup("")
return Markup(", ".join(f'<a href="{esc(i["path"])}">{esc(i["name"])}</a>' for i in mine))
_ORG_CUT = re.compile(r", who |, with | publishes |; (?=[a-z])| \((?=[a-z])| \((?=[^)]*geometry)")
@@ -611,11 +620,12 @@ def time_note(rec, records):
PERMITS = "Permits"
def glance(rec, records=None):
def glance(rec, records=None, place_infos=()):
"""The hiker's facts at a glance, under the attribute names every page uses.
records: every trail, so that terrain, shape, time and length link to the
lists they put the trail in (left out when None)."""
lists they put the trail in (left out when None). place_infos: the places with
a page (olt/places.py collect); the trail's own are linked in the Where row."""
h = hike.table(rec)
# The length leads, set large. A built or a whole-system figure under it is a line across the
# whole panel, so the row is as wide as the panel.
@@ -671,7 +681,11 @@ def glance(rec, records=None):
if h.get("permit"):
rows.append(glance_row(PERMITS, common.sentence(h["permit"]), wide=True))
country = " and ".join(words.COUNTRIES.get(c, c) for c in common.countries(rec))
rows.append(glance_row(facets.WHERE, Markup(f'{region_names(rec)}, {esc(country)}'), wide=True))
where_value = Markup(f'{region_names(rec)}, {esc(country)}')
links = place_links(rec, place_infos)
if links:
where_value = Markup(f"{where_value}<br>{links}")
rows.append(glance_row(facets.WHERE, where_value, wide=True))
status = facets.gpx(rec)
if facets.gpx_here(rec):
text = facets.gpx_status_text(rec)
@@ -1789,11 +1803,12 @@ def nearest_length(rec, other):
RELATED_WHY = {"name": "same name", "named": "named here", "names": "mentions this"}
def onward(rec, records):
def onward(rec, records, place_infos=()):
"""Ways onward at the foot of the page, all worked out from the records (olt/related.py):
trails tied to this one by name or by what the descriptions say; other trails in the
same state or province (up to three of them), the closest in length first; trails like this one in length, terrain
and shape; and for a route, other routes by the same author."""
same state or province (up to three of them), the closest in length first; other trails
in the same park, range or wilderness area that has a page (place_infos); trails like
this one in length, terrain and shape; and for a route, other routes by the same author."""
if not records:
return ""
others = [r for r in records if r["id"] != rec["id"]]
@@ -1813,6 +1828,16 @@ def onward(rec, records):
more = (facets.place_path(key), f"All {len(here) + 1} trails in {name}") if len(here) > ONWARD_MAX else \
(facets.place_path(key), f"{name} on the map")
parts.append(_onward_list(f"More in {name}", here, more[0], more[1], f"onward-{key.lower()}"))
for info in places.of_record(rec, place_infos)[:3]:
here = sorted((r for r in info["records"] if r["id"] != rec["id"]),
key=lambda r: nearest_length(rec, r))
if not here:
continue
where = places.in_name(info)
more = (info["path"], f"All {len(info['records'])} trails in {where}") if len(here) > ONWARD_MAX else \
(info["path"], f"{info['name']} on the map")
parts.append(_onward_list(f"More in {where}", here, more[0], more[1],
f"onward-{info['kind']}-{info['slug']}"))
like = related.similar_to(rec, records)
if like:
def alike(r):
@@ -1830,9 +1855,11 @@ def onward(rec, records):
f'<div class="onward__grid">{"".join(parts)}</div></nav>')
def render(rec, site, records=None, author_links=None):
def render(rec, site, records=None, author_links=None, place_infos=()):
"""Return (title, description, body HTML, needs_map) for one trail.
records: every trail, for the ways onward at the foot (left out when None)."""
records: every trail, for the ways onward at the foot (left out when None).
place_infos: the places with a page (olt/places.py collect), linked in the
glance and the ways onward."""
has_track = common.has_line(rec)
sketch_points = hike.sketch_points(rec) if not has_track else []
has_map = has_track or bool(sketch_points)
@@ -1840,7 +1867,7 @@ def render(rec, site, records=None, author_links=None):
aside_html = (f'<aside class="detail__aside" aria-label="{"Downloads" if has_track else "Where to get the route"}">'
f'{aside}</aside>') if aside else ""
profile = elevation_figure(rec)
side = f'<div class="detail__side">{glance(rec, records)}{aside_html}{map_credit(rec)}</div>'
side = f'<div class="detail__side">{glance(rec, records, place_infos)}{aside_html}{map_credit(rec)}</div>'
body = f"""{page_head(rec, author_links)}
<div class="container detail{"" if aside else " detail--no-aside"}{"" if has_map else " detail--no-map"}{" detail--with-profile" if profile else ""}">
{strip(rec)}
@@ -1850,7 +1877,7 @@ def render(rec, site, records=None, author_links=None):
{profile}
</div>
<div class="container trail-more">
{onward(rec, records)}
{onward(rec, records, place_infos)}
{page_foot(rec, site)}
{about_data(rec, site, author_links)}
{history_section(rec)}
+170
View File
@@ -0,0 +1,170 @@
"""Links to the park, range and wilderness pages: the Places hub sections, the block
on a state page, the links on a trail page, and place names in search
(regions.regions_index_page, regions.place_links_for, trail.place_links,
searchtext.place_names). Fixtures only."""
import hashlib
import json
import os
import re
import sys
import unittest
WEB = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
ROOT = os.path.dirname(WEB)
sys.path.insert(0, WEB)
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from olt import home, placefacets, places, regions, searchtext, site, trail # noqa: E402
from test_place_page import REGISTRY, rec, wind_records, yosemite_records # noqa: E402
from test_state_pages_unchanged import GOLDEN, fixtures, normalise # noqa: E402
S = site.Site("Long Hikes", "T", repo_url="https://github.com/o/r")
def registry(entries=REGISTRY):
return {(e["kind"], e["slug"]): e for e in entries}
def infos(records):
return places.collect(records, registry())
class HubTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.records = wind_records(4) + yosemite_records(3)
cls.infos = infos(cls.records)
def test_the_hub_lists_each_kind_with_exact_counts_and_hides_empty_kinds(self):
_, _, body = regions.regions_index_page(self.records, S, infos=self.infos)
body = str(body)
self.assertIn(">Parks</h2>", body)
self.assertIn(">Mountain ranges</h2>", body)
self.assertNotIn(">Wilderness areas</h2>", body)
self.assertIn('<a href="/ranges/wind-river-range/">Wind River Range</a>'
'<span class="places__n">4 trails</span>', body)
self.assertIn('<a href="/parks/yosemite/">Yosemite National Park</a>'
'<span class="places__n">3 trails</span>', body)
self.assertIn("Parks, mountain ranges and wilderness areas with three or more "
"trails have pages too.", re.sub(r"\s+", " ", body))
def test_the_hub_still_lists_every_state_group_as_before(self):
_, _, plain = regions.regions_index_page(self.records, S)
_, _, with_places = regions.regions_index_page(self.records, S, infos=self.infos)
stripped = re.sub(r'<section class="places__group" aria-labelledby="(?:parks|ranges|wilderness)">.*?</section>',
"", str(with_places), flags=re.S)
stripped = stripped.replace(
" Parks, mountain ranges and wilderness areas with three or more trails have pages too.", "")
self.assertEqual(stripped, str(plain))
class StateLinkTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.records = fixtures()
# three Colorado fixtures in one range whose `where` is Colorado
cls.reg = {("range", "front-range"): {
"kind": "range", "slug": "front-range", "name": "Front Range", "where": ["CO"],
"source": "gmba-v2", "source_id": "1", "source_version": "2026-11-20",
"box": [-106.0, 38.0, -105.0, 41.0]}}
co = [r for r in cls.records if "CO" in r.get("regions", [])][:3]
for r in co:
r["place"] = [{"kind": "range", "slug": "front-range", "basis": "track", "km": 42.0}]
cls.infos = places.collect(cls.records, cls.reg)
def test_a_state_page_links_to_the_places_in_the_state_with_exact_counts_and_nothing_else_changes(self):
block = regions.place_links_for("US-CO", self.infos)
self.assertIn('aria-label="Parks, ranges and wilderness in Colorado"', str(block))
self.assertIn('<a href="/ranges/front-range/">Front Range</a> (3)', str(block))
plan = placefacets.plan(self.records)
facet_pages = [(placefacets.label(p["lst"]), p["path"], len(p["recs"]))
for p in placefacets.pages_by_place(plan).get("us-co", [])]
built = regions.region_page("us-co", self.records, S, facet_pages, place_links=block)
page = "\n".join(str(p) for p in built if isinstance(p, str) or hasattr(p, "__html__"))
self.assertIn("/ranges/front-range/", page)
with open(GOLDEN, encoding="utf-8") as f:
want = json.load(f)["/regions/us-co/"]
self.assertEqual(hashlib.sha256(normalise(page).encode()).hexdigest(), want)
def test_a_state_with_no_place_has_no_block(self):
self.assertEqual(str(regions.place_links_for("US-UT", self.infos)), "")
_, _, body, _ = regions.region_page(
"us-ut", self.records, S, place_links=regions.place_links_for("US-UT", self.infos))
self.assertNotIn("Parks, ranges and wilderness in Utah", str(body))
class TrailLinkTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
small = [rec(301, "Small One", [("range", "wind-river-range"), ("park", "small")]),
rec(302, "Small Two", [("park", "small")])]
cls.records = wind_records(3) + small
cls.infos = infos(cls.records)
cls.rec = small[0]
def test_a_trail_page_links_to_each_of_its_places_that_has_a_page_and_not_to_a_place_below_three(self):
links = str(trail.place_links(self.rec, self.infos))
self.assertIn('<a href="/ranges/wind-river-range/">Wind River Range</a>', links)
self.assertNotIn("small", links)
body = str(trail.render(self.rec, S, self.records, place_infos=self.infos)[2])
glance = body[body.index('class="glance'):body.index("All the facts")]
self.assertIn('<a href="/ranges/wind-river-range/">Wind River Range</a>', glance)
self.assertNotIn("/parks/small/", body)
self.assertIn("More in the Wind River Range", body) # the ways onward
def test_a_trail_with_no_place_page_is_unchanged(self):
plain = str(trail.render(self.rec, S, self.records)[2])
self.assertNotIn("/ranges/wind-river-range/", plain)
class LosingATrailTest(unittest.TestCase):
def test_losing_a_trail_removes_the_page_and_every_link(self):
three = wind_records(3)
got = infos(three)
self.assertIn(("range", "wind-river-range"), got)
two = three[:2]
gone = infos(two)
self.assertEqual(gone, {})
_, _, hub = regions.regions_index_page(two, S, infos=gone)
self.assertNotIn("/ranges/wind-river-range/", str(hub))
self.assertEqual(str(regions.place_links_for("US-WY", gone)), "")
self.assertEqual(str(trail.place_links(two[0], gone)), "")
class SearchTextTest(unittest.TestCase):
def tearDown(self):
searchtext.use_place_names({})
def test_search_text_holds_the_place_names(self):
# names with none of the place's words: a word already in the name tier
# is not repeated in the places tier (searchtext.tiers)
records = [rec(401, "Alpha Trail", [("range", "wind-river-range")]),
rec(402, "Bravo Trail", [("range", "wind-river-range")]),
rec(403, "Charlie Trail", [("range", "wind-river-range")])]
got = infos(records)
attr = searchtext.attribute(records[0], got)
self.assertIn("wind river range", attr)
# through a row, once the build has named each trail's places
searchtext.use_place_names({records[0]["id"]: ["Wind River Range"]})
row = home.entry(records[0])
self.assertIn("wind river range", row)
names = searchtext.place_names(records[0], got)
self.assertIn("Wind River Range", names)
def test_search_text_without_places_is_as_before(self):
r = rec(9, "Plain Trail", [])
self.assertNotIn("wind river", searchtext.attribute(r))
class SourcesTest(unittest.TestCase):
def test_sources_names_the_four_outline_publishers(self):
with open(os.path.join(ROOT, "SOURCES.md"), encoding="utf-8") as f:
text = f.read()
for want in ("National Park Service", "Wilderness Connect", "CPCAD",
"GMBA Mountain Inventory", "Open Government Licence", "CC BY 4.0",
"public domain"):
self.assertTrue(want in text, want)
if __name__ == "__main__":
unittest.main()
+10
View File
@@ -224,6 +224,16 @@ class BuiltPlacePagesTest(unittest.TestCase):
self.assertEqual([i["name"] for i in crumbs["itemListElement"]],
["Trails", "Places", "Wind River Range"])
def test_the_hub_state_and_trail_pages_of_the_same_build_link_here(self):
hub = self.read("regions", "index.html")
self.assertIn('<a href="/ranges/wind-river-range/">Wind River Range</a>', hub)
wyoming = self.read("regions", "us-wy", "index.html")
self.assertIn('aria-label="Parks, ranges and wilderness in Wyoming"', wyoming)
trail_page = self.read("trails", "t101", "index.html")
self.assertIn('<a href="/ranges/wind-river-range/">Wind River Range</a>', trail_page)
home_page = self.read("index.html")
self.assertIn("river range", home_page) # the rows' search words
def test_the_state_pages_of_the_same_build_are_unchanged_in_shape(self):
# the golden test pins the exact bytes; here the same render still has them
doc = self.read("regions", "us-wy", "index.html")
+27 -1
View File
@@ -16,7 +16,7 @@ HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, WEB)
sys.path.insert(0, HERE)
from olt import bounds, facets, placefacets, regions, site # noqa: E402
from olt import bounds, facets, home, placefacets, regions, searchtext, site # noqa: E402
from test_hike import fake # noqa: E402
GOLDEN = os.path.join(HERE, "golden", "state-pages.json")
@@ -95,6 +95,32 @@ def build_map():
return out
class AllowedDifferencesTest(unittest.TestCase):
def test_state_pages_differ_only_in_data_search_and_the_new_block(self):
# data-search gains the place names, and nothing else about a row changes
rec = fixtures()[0]
plain = home.entry(rec)
searchtext.use_place_names({rec["id"]: ["Wind River Range"]})
try:
with_place = home.entry(rec)
finally:
searchtext.use_place_names({})
self.assertIn("wind river range", with_place)
self.assertNotEqual(plain, with_place)
self.assertEqual(normalise(plain), normalise(with_place))
# the place-links nav is the other allowed addition to a state page
records = fixtures()
s = site.Site("Long Hikes", "T", repo_url="https://github.com/o/r")
block = ('<nav class="region-nav" aria-label="Parks, ranges and wilderness in Colorado">'
'Parks, ranges and wilderness in Colorado: <a href="/ranges/front-range/">Front Range</a> (3)</nav>')
plain_page = regions.region_page("us-co", records, s)
linked_page = regions.region_page("us-co", records, s, place_links=block)
self.assertNotEqual(str(plain_page[2]), str(linked_page[2]))
self.assertEqual(normalise(str(plain_page[2])), normalise(str(linked_page[2])))
self.assertEqual(plain_page[0], linked_page[0])
self.assertEqual(plain_page[1], linked_page[1])
class StatePagesUnchangedTest(unittest.TestCase):
def test_every_state_group_and_state_list_page_is_byte_identical_after_normalising(self):
with open(GOLDEN, encoding="utf-8") as f: