Make a trail's length one end-to-end walk, and put the map and the trails in the first screen
Lengths and what belongs: - A trail's length is now the end-to-end length of its canonical path: one branch at a split, no side trails, no system totals. A holder's larger figure and the built length of an unfinished trail are separate fields (`system_km`, `system_note`, `built_km`), shown under the length. - Corrected: Florida Trail 1,500 to 1,130 mi, American Discovery Trail 6,800 to 5,008 mi, Ozark Trail to 230 mi, General Crook Trail to 138 mi, Sheltowee Trace to 343 mi, Allegheny Trail to 316 mi, Great Eastern Trail to 1,800 mi. - The Florida Trail's and the Ice Age Trail's main tracks are re-cut as one walk; the other branches are alternates. - A trail must be walkable from end to end today. Nine trails that are not, are a network, or fall under the floor move to the "Considered and left out" list. The Bayou State Trail is added. 196 trails. Pages: - The trail page puts the map and At a glance directly under the title; the home page drops its oversized hero and shows the trails and the map at once. Place and list pages put the list beside the map. - Every map starts by itself once the page is ready, over a drawing of the tracks that is in the page from the first paint. - Lists is in the header. The home page shows ten lists chosen in `collections.toml`. Tables have equal columns and stack on a phone. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
1 parent
f2d3b71810
commit
8637181a2b
145 files changed
+2178
-1455
No files matched your search
@@ -185,9 +185,9 @@ class ExtraPagesTest(unittest.TestCase):
|
||||
# no dataset filters
|
||||
for name in ("tier", "policy", "designated", "line", "country", "region"):
|
||||
self.assertNotIn(f'name="{name}"', form, name)
|
||||
# the map is in the tool, beside the list it filters
|
||||
main = doc[doc.index('<div class="finder__main">'):]
|
||||
self.assertLess(main.index('data-map="overview"'), main.index('<ol class="entries" id="entries"'))
|
||||
# the map is in the tool, beside the list it filters (after it in the page, beside it on a wide screen)
|
||||
main = doc[doc.index('<div class="home__results">'):]
|
||||
self.assertLess(main.index('<ol class="entries" id="entries"'), main.index('data-map="overview"'))
|
||||
longest_km = max(r["length_km"] for r in self.records)
|
||||
maxsel = form[form.index('id="max"'):form.index("</select>", form.index('id="max"'))]
|
||||
minsel = form[form.index('id="min"'):form.index("</select>", form.index('id="min"'))]
|
||||
|
||||
@@ -242,7 +242,7 @@ def site_words(doc):
|
||||
if '<details class="about-data"' in doc:
|
||||
doc = doc[:doc.index('<details class="about-data"')]
|
||||
doc = doc[doc.index('<main id="main">'):]
|
||||
for cls in ("entry__desc", "entry__name", "trail-lede", "titleblock__sub", "entry__partial",
|
||||
for cls in ("entry__desc", "entry__name", "trail-lede", "trail-summary", "titleblock__sub", "entry__partial",
|
||||
"note", "record-text", "map__reason", "glance__warn", "shelf__items", "onward__list"):
|
||||
doc = re.sub(rf'<(\w+) class="{cls}"[^>]*>.*?</\1>', " ", doc, flags=re.S)
|
||||
doc = re.sub(r"<dd>.*?</dd>", " ", doc, flags=re.S) # glance values are the trail's facts
|
||||
@@ -285,10 +285,10 @@ class BuiltVocabularyTest(unittest.TestCase):
|
||||
self.maxDiff = None
|
||||
self.assertEqual(bad[:40], [])
|
||||
|
||||
def test_navigation_has_three_sections_and_saved(self):
|
||||
def test_navigation_has_four_sections_and_saved(self):
|
||||
doc = self.read("index.html")
|
||||
nav = re.search(r'<nav class="site-nav" aria-label="Main"><ul class="nav">(.*?)</ul></nav>', doc).group(1)
|
||||
self.assertEqual(re.findall(r'<li><a href="[^"]*"[^>]*>([^<]+)</a>', nav), ["Trails", "Places", "About"])
|
||||
self.assertEqual(re.findall(r'<li><a href="[^"]*"[^>]*>([^<]+)</a>', nav), ["Trails", "Places", "Lists", "About"])
|
||||
self.assertIn('<li class="nav__saved js-only"><a href="/saved/">', nav)
|
||||
|
||||
def test_one_count_noun(self):
|
||||
|
||||
@@ -0,0 +1,292 @@
|
||||
"""The first screen: what the top of the trail page and the home page hold, the home page's lists
|
||||
(read from data), the header's Lists item, the tables that stack on a phone, and the maps' static
|
||||
drawings (olt/sketch.py) with the script's handover from them.
|
||||
|
||||
Pages are rendered one at a time; the site is not built. The sketch reads the track files of a
|
||||
site directory, so those are written to a temporary one here. The behaviour of the script in a
|
||||
browser was checked by driving the pages (see the changelog); these pin what its source promises.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import tempfile
|
||||
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.join(ROOT, "tools"))
|
||||
|
||||
from olt import browse, common, datafiles, home, layout, pagekit, records, site, sketch, trail # noqa: E402
|
||||
|
||||
SITE = site.load()
|
||||
|
||||
|
||||
def read(*parts):
|
||||
with open(os.path.join(*parts), encoding="utf-8") as f:
|
||||
return f.read()
|
||||
|
||||
|
||||
def load(tid):
|
||||
return records.load_record(ROOT, tid)
|
||||
|
||||
|
||||
class HomePageTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.recs = records.load_records(ROOT)
|
||||
cls.body = home.render(cls.recs, SITE, ROOT)
|
||||
|
||||
def test_the_hero_no_longer_repeats_the_site_mark_or_the_strip_of_words(self):
|
||||
hero = self.body[:self.body.index('class="container home"')]
|
||||
self.assertNotIn("lockup", hero)
|
||||
self.assertNotIn("hero__tags", hero)
|
||||
self.assertNotIn("<img", hero)
|
||||
self.assertIn("<h1", hero)
|
||||
self.assertIn(SITE.tagline.rstrip("."), hero)
|
||||
|
||||
def test_the_header_shows_the_name_on_the_home_page(self):
|
||||
css = read(WEB, "assets", "style.css")
|
||||
self.assertNotIn(".hero--home) .site-header .wordmark", css)
|
||||
|
||||
def test_the_lists_row_is_read_from_the_data_file_in_its_order(self):
|
||||
entries = datafiles.lists(ROOT)
|
||||
keys = home.home_picks(entries)
|
||||
self.assertEqual(keys, ["national-scenic-trails", "routes", "high-routes", "loops", "under-100-miles",
|
||||
"a-week-or-less", "one-to-two-weeks", "a-month-or-more", "with-gpx", "canada"])
|
||||
row = home.lists_row(self.recs, keys)
|
||||
titles = re.findall(r'<li><a href="[^"]+">(.*?) <span class="chips__n">', row)
|
||||
self.assertEqual(titles, [browse.by_key(k).title for k in keys])
|
||||
self.assertTrue(row.rstrip().endswith("</nav>"))
|
||||
self.assertIn('<a href="/lists/">All lists</a>', row)
|
||||
self.assertNotIn("Hiking in", row)
|
||||
# a different file gives a different row: the set is not a constant of the generator
|
||||
other = home.home_picks([{"key": "loops", "home": 2}, {"key": "routes", "home": 1}, {"key": "canada"}])
|
||||
self.assertEqual(other, ["routes", "loops"])
|
||||
self.assertEqual(re.findall(r'<li><a href="[^"]+">(.*?) <span', home.lists_row(self.recs, other)), ["Routes", "Loops"])
|
||||
|
||||
def test_search_and_filters_are_one_bar_with_a_clear_control_that_starts_hidden(self):
|
||||
bar = self.body[self.body.index('class="filters__bar"'):self.body.index('id="filters-panels"')]
|
||||
self.assertIn('id="q"', bar)
|
||||
self.assertIn('aria-controls="filters-panels"', bar)
|
||||
self.assertRegex(bar, r'class="button button--quiet filters__clear" type="reset" hidden')
|
||||
self.assertIn('id="filters-panels"', self.body)
|
||||
self.assertIn('class="filters__panel"', self.body)
|
||||
self.assertIn('class="filters__more"', self.body)
|
||||
|
||||
def test_the_results_precede_the_map_in_the_page_and_the_map_has_its_own_address(self):
|
||||
self.assertLess(self.body.index('class="home__results"'), self.body.index('class="home__map"'))
|
||||
self.assertIn('id="map"', self.body)
|
||||
|
||||
def test_the_stylesheet_puts_the_map_beside_the_list_on_a_wide_screen(self):
|
||||
css = read(WEB, "assets", "style.css")
|
||||
self.assertRegex(css, r"\.home \{[^}]*grid-template-areas: \"lists\" \"bar\" \"results\" \"map\" \"notes\"")
|
||||
self.assertIn('grid-template-areas: "lists lists" "bar map" "results map" "notes ."', css)
|
||||
self.assertRegex(css, r"\.lists-row \.chips \{[^}]*flex-wrap: nowrap; overflow-x: auto")
|
||||
|
||||
|
||||
class ListEntriesCheckTest(unittest.TestCase):
|
||||
def check(self, entries, keys=("a", "b", "c")):
|
||||
import check_datafiles
|
||||
errors = []
|
||||
check_datafiles.check_list_entries(entries, set(keys), errors)
|
||||
return errors
|
||||
|
||||
def test_the_real_entries_pass(self):
|
||||
import check_datafiles
|
||||
errors = []
|
||||
import tomllib
|
||||
with open(os.path.join(ROOT, "collections.toml"), "rb") as f:
|
||||
doc = tomllib.load(f)
|
||||
check_datafiles.check_list_entries(doc["list"], check_datafiles.built_in_list_keys(), errors)
|
||||
self.assertEqual(errors, [])
|
||||
|
||||
def test_unknown_keys_repeats_and_bad_positions_are_reported(self):
|
||||
self.assertEqual(self.check([{"key": "a", "home": 1}, {"key": "b", "home": 2}]), [])
|
||||
self.assertTrue(any("not the key of a list" in e for e in self.check([{"key": "zzz", "home": 1}])))
|
||||
self.assertTrue(any("appears twice" in e for e in self.check([{"key": "a", "home": 1}, {"key": "a", "home": 2}])))
|
||||
self.assertTrue(any("also the place of" in e for e in self.check([{"key": "a", "home": 1}, {"key": "b", "home": 1}])))
|
||||
self.assertTrue(any("whole number" in e for e in self.check([{"key": "a", "home": 0}])))
|
||||
self.assertTrue(any("whole number" in e for e in self.check([{"key": "a", "home": "1"}])))
|
||||
self.assertTrue(any("unknown field" in e for e in self.check([{"key": "a", "shown": 1}])))
|
||||
|
||||
|
||||
class HeaderTest(unittest.TestCase):
|
||||
def nav(self, path):
|
||||
html = str(layout.header(path, SITE))
|
||||
return {m.group(2): m.group(1) for m in re.finditer(r'<a href="(/[^"]*)"(?: aria-current="[a-z]+")?>', html)}, html
|
||||
|
||||
def current(self, path):
|
||||
html = str(layout.header(path, SITE))
|
||||
return re.findall(r'<a href="([^"]+)" aria-current="(?:page|true)"', html)
|
||||
|
||||
def test_the_items_are_trails_places_lists_about_saved(self):
|
||||
html = str(layout.header("/", SITE))
|
||||
names = re.findall(r"<li[^>]*><a [^>]*>(?:<svg.*?</svg>)?([A-Za-z]+)", html)
|
||||
self.assertEqual(names[:5], ["Trails", "Places", "Lists", "About", "Saved"])
|
||||
self.assertIn('<a href="/lists/">Lists</a>', html)
|
||||
|
||||
def test_lists_is_current_on_the_index_lists_tables_and_views(self):
|
||||
for path in ("/lists/", "/lists/loops/", "/routes/", "/numbers/", "/numbers/highest-points/", "/authors/",
|
||||
"/authors/andrew-skurka/", "/recent/", "/connected/"):
|
||||
self.assertEqual(self.current(path), ["/lists/"], path)
|
||||
layout.UNDER_LISTS.add("/triple-crown/")
|
||||
try:
|
||||
self.assertEqual(self.current("/triple-crown/"), ["/lists/"])
|
||||
finally:
|
||||
layout.UNDER_LISTS.discard("/triple-crown/")
|
||||
|
||||
def test_the_other_items_keep_their_pages(self):
|
||||
self.assertEqual(self.current("/"), ["/"])
|
||||
self.assertEqual(self.current("/trails/tonto-trail/"), ["/"])
|
||||
self.assertEqual(self.current("/regions/us-co/"), ["/regions/"])
|
||||
self.assertEqual(self.current("/regions/us-co/loops/"), ["/regions/"])
|
||||
self.assertEqual(self.current("/about/"), ["/about/"])
|
||||
self.assertEqual(self.current("/sources/"), ["/about/"])
|
||||
self.assertEqual(self.current("/glossary/"), ["/about/"])
|
||||
|
||||
def test_the_triple_crown_page_is_listed_under_lists_by_the_page_builder(self):
|
||||
self.assertIn("layout.UNDER_LISTS.add(path)", read(WEB, "olt", "pages.py"))
|
||||
|
||||
|
||||
class TablesTest(unittest.TestCase):
|
||||
def test_every_cell_carries_its_label_and_a_wide_table_is_set_by_row(self):
|
||||
t = str(pagekit.table(["Trail", "Length", "States", "Time"], [["A", "1", "X", "2"]], caption="c"))
|
||||
self.assertIn('<table data-stack="rows">', t)
|
||||
self.assertEqual(re.findall(r'data-label="([^"]+)"', t), ["Trail", "Length", "States", "Time"])
|
||||
small = str(pagekit.table(["A", "B", "C"], [["1", "2", "3"]]))
|
||||
self.assertNotIn("data-stack", small)
|
||||
|
||||
def test_a_compare_table_labels_each_cell_with_its_row_and_stacks_by_column(self):
|
||||
t = str(pagekit.table(["Figure", "AT", "PCT"], [["Length", "2,198", "2,650"], ["States", "14", "3"]],
|
||||
row_heads=True, compare=True))
|
||||
self.assertIn('<table data-stack="columns">', t)
|
||||
self.assertEqual(re.findall(r'<td data-label="([^"]+)"', t), ["Length", "Length", "States", "States"])
|
||||
|
||||
def test_the_triple_crown_table_is_a_compare_table_with_equal_columns(self):
|
||||
from olt import standing
|
||||
recs = records.load_records(ROOT)
|
||||
c = datafiles.collections(ROOT)[0]
|
||||
title, desc, body, _ = standing.collection_page(c, recs, SITE)
|
||||
self.assertIn('data-stack="columns"', str(body))
|
||||
css = read(WEB, "assets", "style.css")
|
||||
self.assertIn('table[data-stack="columns"] { table-layout: fixed;', css)
|
||||
self.assertIn('th:first-child { inline-size: 9rem; }', css)
|
||||
self.assertIn("order: 3", css) # one block per trail on a phone, from the same cells
|
||||
self.assertNotIn("min-inline-size: 34rem !important", css)
|
||||
|
||||
def test_the_left_out_tables_stack_on_a_phone_too(self):
|
||||
src = read(WEB, "olt", "leftout.py")
|
||||
self.assertIn('<table data-stack="rows">', src)
|
||||
self.assertEqual(src.count("data-label="), 6)
|
||||
|
||||
|
||||
class SketchTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.dir = tempfile.TemporaryDirectory()
|
||||
os.makedirs(os.path.join(self.dir.name, "trails", "x"))
|
||||
coords = [[-112.0 + i * 0.001, 36.0 + (i % 7) * 0.0004 + i * 0.0005] for i in range(400)]
|
||||
fc = {"type": "FeatureCollection", "features": [
|
||||
{"type": "Feature", "properties": {"role": "main"}, "geometry": {"type": "MultiLineString", "coordinates": [coords]}}]}
|
||||
with open(os.path.join(self.dir.name, "trails", "x", "map.json"), "w") as f:
|
||||
json.dump(fc, f)
|
||||
sketch.use(self.dir.name)
|
||||
self.box = [-112.0, 36.0, -111.6, 36.2]
|
||||
|
||||
def tearDown(self):
|
||||
sketch.use("")
|
||||
self.dir.cleanup()
|
||||
|
||||
def test_the_drawing_is_light_and_in_the_site_s_track_classes(self):
|
||||
fr = sketch.frame(self.box)
|
||||
svg = str(sketch.svg(sketch.trail_features("x"), fr))
|
||||
self.assertLess(len(svg), 4000)
|
||||
self.assertIn('class="map__sketch"', svg)
|
||||
self.assertIn('class="fallback__casing"', svg)
|
||||
self.assertIn('class="fallback__line"', svg)
|
||||
self.assertIn('preserveAspectRatio="xMidYMid meet"', svg)
|
||||
self.assertNotRegex(svg, r"\d\.\d{3,}") # whole numbers, relative steps
|
||||
self.assertRegex(svg, r'd="M\d+ \d+l')
|
||||
|
||||
def test_the_frame_is_the_extent_widened_on_every_side(self):
|
||||
w, s, e, n = sketch.frame(self.box)
|
||||
self.assertLess(w, self.box[0])
|
||||
self.assertLess(s, self.box[1])
|
||||
self.assertGreater(e, self.box[2])
|
||||
self.assertGreater(n, self.box[3])
|
||||
|
||||
def test_the_viewbox_has_the_frames_proportions_so_both_fit_a_container_the_same_way(self):
|
||||
import math
|
||||
fr = sketch.frame(self.box)
|
||||
svg = str(sketch.svg(sketch.trail_features("x"), fr))
|
||||
vw, vh = map(float, re.search(r'viewBox="0 0 ([\d.]+) ([\d.]+)"', svg).groups())
|
||||
merc = lambda lat: math.log(math.tan(math.pi / 4 + math.radians(lat) / 2))
|
||||
want = (math.radians(fr[2] - fr[0])) / (merc(fr[3]) - merc(fr[1]))
|
||||
self.assertAlmostEqual(vw / vh, want, places=3)
|
||||
|
||||
def test_a_trail_page_carries_the_frame_and_the_drawing(self):
|
||||
rec = load("tonto-trail")
|
||||
rec["id"] = "x"
|
||||
rec["derived"]["bbox"] = self.box
|
||||
rec["derived"]["files"] = {"line": "x.gpx"}
|
||||
fig = trail.map_figure(rec)
|
||||
self.assertRegex(fig, r'data-frame="-?[\d.]+,-?[\d.]+,-?[\d.]+,-?[\d.]+"')
|
||||
self.assertIn('<div class="map__fallback"><svg class="map__sketch"', fig)
|
||||
self.assertIn('class="map__status"', fig) # the no-script text stays
|
||||
|
||||
def test_no_data_no_drawing_and_no_empty_placeholder_text_for_scripts(self):
|
||||
sketch.use("")
|
||||
rec = load("tonto-trail")
|
||||
rec["derived"]["bbox"] = self.box
|
||||
self.assertIn('<div class="map__fallback"></div>', trail.map_figure(rec))
|
||||
|
||||
|
||||
class HandoverTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.js = read(WEB, "assets", "app.js")
|
||||
cls.css = read(WEB, "assets", "style.css")
|
||||
|
||||
def test_the_live_map_opens_on_the_drawings_ground_with_no_padding(self):
|
||||
self.assertIn("var frame = (fig.dataset.frame || '').split(',').map(Number);", self.js)
|
||||
self.assertIn("options.bounds = [[frame[0], frame[1]], [frame[2], frame[3]]];", self.js)
|
||||
self.assertIn("options.fitBoundsOptions = { padding: 0 };", self.js)
|
||||
|
||||
def test_nothing_is_drawn_over_the_page_s_own_drawing_and_no_placeholder_text_is_written(self):
|
||||
self.assertIn("if (hasSketch()) { sketchCorners(); return; }", self.js)
|
||||
self.assertNotIn("The map loads when you scroll to it.", self.js)
|
||||
self.assertNotIn("Loading the track", self.js)
|
||||
self.assertNotIn("Loading the base map", self.js)
|
||||
self.assertIn("html.js .map__status:not([data-say]) { display: none; }", self.css)
|
||||
|
||||
def test_the_drawing_gives_way_after_the_first_frame_with_the_tracks_and_a_fade(self):
|
||||
self.assertIn("map.once('render', reveal);", self.js)
|
||||
self.assertIn("map.isSourceLoaded('olt')", self.js)
|
||||
self.assertIn(".map[data-state=\"ready\"] .map__fallback { visibility: hidden; transition: visibility 0s 0.4s; }", self.css)
|
||||
self.assertIn(".map__canvas { opacity: 0; transition: opacity 0.4s ease; }", self.css)
|
||||
|
||||
def test_every_frame_starts_when_the_page_is_idle_whatever_its_place(self):
|
||||
self.assertIn("requestIdleCallback(begin, { timeout: 500 })", self.js)
|
||||
self.assertNotIn("IntersectionObserver", self.js)
|
||||
self.assertNotIn("MAP_AHEAD", self.js)
|
||||
|
||||
def test_the_first_view_of_an_overview_needs_no_move(self):
|
||||
self.assertIn("if (entry.frame && same) { target = entry.frame; padding = 0; }", self.js)
|
||||
|
||||
|
||||
class PageTopsTest(unittest.TestCase):
|
||||
def test_a_place_or_list_page_puts_its_list_before_the_text_and_the_map_in_the_narrow_order(self):
|
||||
grid = home.place_grid("TEXT", "LIST", "MAP")
|
||||
self.assertLess(grid.index("TEXT"), grid.index("LIST")) # the text is first in the page
|
||||
css = read(WEB, "assets", "style.css")
|
||||
self.assertIn('grid-template-areas: "list" "map" "text";', css)
|
||||
self.assertIn('grid-template-areas: "list text" "list map";', css)
|
||||
|
||||
def test_every_page_head_is_compact(self):
|
||||
css = read(WEB, "assets", "style.css")
|
||||
self.assertRegex(css, r"\.page-head \.titleblock h1 \{ font-size: var\(--step-3\)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -114,7 +114,7 @@ class HistorySectionTest(unittest.TestCase):
|
||||
|
||||
def test_real_records_all_show_their_history(self):
|
||||
recs = records.load_records()
|
||||
self.assertEqual(len(recs), 204)
|
||||
self.assertEqual(len(recs), 196)
|
||||
for rec in recs:
|
||||
part = trail.history_section(rec)
|
||||
self.assertIn("History of this record", part, rec["id"])
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
"""Tests for the length facts on a trail page: the canonical length, the holder's larger figure
|
||||
and the built length of an unfinished trail (docs/schema.md, "What length_km counts").
|
||||
|
||||
These render fixtures; they do not need the built site.
|
||||
"""
|
||||
import copy
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
WEB = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
sys.path.insert(0, WEB)
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
from olt import browse, common, facets, seo, site, trail, words # noqa: E402
|
||||
from test_hike import FULL_HIKE, GH, fake, render, top_part # noqa: E402
|
||||
from test_hike import text as _text # noqa: E402
|
||||
|
||||
def text(fragment):
|
||||
"""The words of a fragment, with the space the tags add before a comma taken out."""
|
||||
return _text(fragment).replace(" ,", ",")
|
||||
|
||||
|
||||
NOTE = "all designated trail, official side trail and connecting roadwalks"
|
||||
|
||||
|
||||
def with_lengths(i, km, **more):
|
||||
rec = fake(i, km=km, hike=copy.deepcopy(FULL_HIKE))
|
||||
rec["derived"]["length_mi"] = round(km / words.KM_PER_MI)
|
||||
rec.update(more)
|
||||
return rec
|
||||
|
||||
|
||||
def florida():
|
||||
rec = with_lengths(1, 1818, system_km=2549, system_note=NOTE)
|
||||
del rec["hike"]["unfinished"]
|
||||
return rec
|
||||
|
||||
|
||||
def unfinished():
|
||||
return with_lengths(2, 523, built_km=467)
|
||||
|
||||
|
||||
def glance_length(rec):
|
||||
body = top_part(render(rec))
|
||||
start = body.index('<dt>Length</dt>')
|
||||
return body[start:body.index("</div>", start)]
|
||||
|
||||
|
||||
class GlanceTest(unittest.TestCase):
|
||||
def test_the_length_is_the_canonical_one_and_the_system_figure_sits_beneath_it(self):
|
||||
row = glance_length(florida())
|
||||
self.assertIn('<span class="len__mi">1,130 mi</span><span class="len__km">1,818 km</span>', row)
|
||||
self.assertIn(f"Whole system: 1,584 mi 2,549 km, counting {NOTE}", text(row))
|
||||
self.assertLess(row.index("len--stack"), row.index("Whole system"))
|
||||
self.assertIn("<small>", row)
|
||||
|
||||
def test_the_built_figure_sits_beneath_the_length(self):
|
||||
row = glance_length(unfinished())
|
||||
self.assertIn('<span class="len__mi">325 mi</span><span class="len__km">523 km</span>', row)
|
||||
self.assertIn("290 mi 467 km built", text(row))
|
||||
self.assertNotIn("Whole system", row)
|
||||
|
||||
def test_a_record_with_neither_shows_neither(self):
|
||||
row = glance_length(with_lengths(3, 523))
|
||||
self.assertNotIn("built", row)
|
||||
self.assertNotIn("Whole system", row)
|
||||
|
||||
def test_both_may_show_together_and_the_note_is_escaped(self):
|
||||
rec = with_lengths(4, 523, built_km=467, system_km=700, system_note="side trails <b>too</b>")
|
||||
row = glance_length(rec)
|
||||
self.assertIn("built", row)
|
||||
self.assertIn("counting side trails <b>too</b>", row)
|
||||
|
||||
def test_the_not_finished_panel_still_follows_the_unfinished_sentence(self):
|
||||
body = top_part(render(unfinished()))
|
||||
self.assertIn("<strong>Not finished.</strong>", body)
|
||||
|
||||
|
||||
class BriefAndDescriptionTest(unittest.TestCase):
|
||||
def test_in_brief_uses_the_canonical_length_and_may_add_the_built_figure(self):
|
||||
first = text(trail.brief_sentences(florida())[0])
|
||||
self.assertIn("1,130-mile (1,818 km)", first)
|
||||
self.assertNotIn("1,584", first)
|
||||
self.assertNotIn("built", first)
|
||||
first = text(trail.brief_sentences(unfinished())[0])
|
||||
self.assertIn("325-mile (523 km)", first)
|
||||
self.assertIn("with 290 miles (467 km) built", first)
|
||||
|
||||
def test_the_description_uses_the_canonical_length(self):
|
||||
self.assertIn("1,130 miles (1,818 km)", trail.description(florida()))
|
||||
self.assertNotIn("1,584", trail.description(florida()))
|
||||
self.assertIn("325 miles (523 km), 290 miles built,", trail.description(unfinished()))
|
||||
self.assertLessEqual(len(trail.description(unfinished())), common.DESCRIPTION_LIMIT)
|
||||
|
||||
|
||||
class StructuredDataTest(unittest.TestCase):
|
||||
def props(self, rec):
|
||||
return {(p["name"], p.get("unitCode")): p for p in seo.place_node(rec, GH)["additionalProperty"]}
|
||||
|
||||
def test_the_length_stays_canonical_and_the_system_figure_is_labelled(self):
|
||||
props = self.props(florida())
|
||||
self.assertEqual(props[("Published length", "KMT")]["value"], 1818)
|
||||
self.assertEqual(props[("Published length", "SMI")]["value"], 1130)
|
||||
self.assertEqual(props[("Whole system length", "KMT")]["value"], 2549)
|
||||
self.assertEqual(props[("Whole system length", "SMI")]["value"], 1584)
|
||||
self.assertEqual(props[("Whole system length", "SMI")]["description"], f"Counting {NOTE}")
|
||||
self.assertNotIn(("Built length", "KMT"), props)
|
||||
|
||||
def test_the_built_length_is_labelled_and_a_plain_record_has_neither(self):
|
||||
props = self.props(unfinished())
|
||||
self.assertEqual(props[("Built length", "KMT")]["value"], 467)
|
||||
self.assertEqual(props[("Built length", "SMI")]["value"], 290)
|
||||
self.assertNotIn(("Whole system length", "KMT"), props)
|
||||
props = self.props(with_lengths(5, 523))
|
||||
self.assertFalse([k for k in props if k[0] in ("Built length", "Whole system length")])
|
||||
|
||||
|
||||
class OnlyTheCanonicalLengthCountsTest(unittest.TestCase):
|
||||
def test_bands_time_estimates_and_lists_ignore_the_larger_figure(self):
|
||||
plain, big = with_lengths(6, 1818), florida()
|
||||
for rec in (plain, big):
|
||||
del rec["hike"]["days"]
|
||||
self.assertEqual(facets.time_days(plain), facets.time_days(big))
|
||||
self.assertEqual(facets.time_band(plain), facets.time_band(big))
|
||||
for key in ("under-100-miles", "longest"):
|
||||
self.assertEqual(browse.by_key(key).test(plain), browse.by_key(key).test(big), key)
|
||||
# the band follows length_km: raising only the system figure moves nothing
|
||||
longer = copy.deepcopy(big)
|
||||
longer["system_km"] = 9000
|
||||
self.assertEqual(facets.time_days(big), facets.time_days(longer))
|
||||
|
||||
def test_the_record_panel_names_both_figures_apart(self):
|
||||
body = render(florida())
|
||||
panel = text(body[body.index('id="record-title"'):])
|
||||
self.assertIn("Length 1,130 mi 1,818 km", panel)
|
||||
self.assertIn("Whole system 1,584 mi 2,549 km, counting", panel)
|
||||
panel = text(render(unfinished())[render(unfinished()).index('id="record-title"'):])
|
||||
self.assertIn("Built length 290 mi 467 km built", panel)
|
||||
|
||||
|
||||
class WordsTest(unittest.TestCase):
|
||||
def test_the_glossary_and_the_method_page_say_what_length_means(self):
|
||||
import tomllib
|
||||
with open(os.path.join(os.path.dirname(WEB), "glossary.toml"), "rb") as f:
|
||||
terms = {t["id"]: t for t in tomllib.load(f)["term"]}
|
||||
definition = terms["published-length"]["definition"]
|
||||
self.assertIn("end-to-end length", definition)
|
||||
self.assertIn("canonical path", definition)
|
||||
self.assertIn("no system total", definition)
|
||||
|
||||
def test_the_schema_defines_length_and_names_the_new_fields(self):
|
||||
with open(os.path.join(os.path.dirname(WEB), "docs", "schema.md"), encoding="utf-8") as f:
|
||||
schema = f.read()
|
||||
for needle in ("What `length_km` counts", "`system_km`", "`system_note`", "`built_km`",
|
||||
"canonical path", "Florida"):
|
||||
self.assertIn(needle, schema)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
+34
-12
@@ -1,6 +1,7 @@
|
||||
"""The maps start late: nothing for a map (MapLibre, its style, the contour add-on, the track
|
||||
data) loads with the page. These pin the script's promises (the script has no unit tests; the
|
||||
behaviour was checked by driving the pages in a browser)."""
|
||||
"""The maps start a moment after the page has loaded, every one of them, by itself. Nothing for a
|
||||
map (MapLibre, its style, the contour add-on, the track data) loads with the page, and nothing
|
||||
waits for a scroll, a tap, a key or focus. These pin the script's promises (the script has no unit
|
||||
tests; the behaviour was checked by driving the pages in a browser)."""
|
||||
import os
|
||||
import re
|
||||
import unittest
|
||||
@@ -19,23 +20,41 @@ class MapStartTest(unittest.TestCase):
|
||||
cls.js = read("assets", "app.js")
|
||||
|
||||
def test_one_function_starts_a_map_and_it_is_the_only_caller_of_the_fetch_and_the_loader(self):
|
||||
self.assertEqual(self.js.count("fetchData()"), 2) # its definition and the one call
|
||||
self.assertEqual(self.js.count("fetchData()"), 3) # its definition, begin(), and a frame with no drawing
|
||||
self.assertEqual(self.js.count("loadLibraries()"), 2)
|
||||
begin = re.search(r"function begin\(\) \{(.*?)\n \}\n", self.js, re.S)
|
||||
self.assertIsNotNone(begin)
|
||||
self.assertIn("dataReady = fetchData();", begin.group(1))
|
||||
self.assertIn("dataReady = dataReady || fetchData();", begin.group(1))
|
||||
self.assertIn("loadLibraries().then(startMapLibre);", begin.group(1))
|
||||
self.assertIn("if (outdoorUrl) fetchOutdoor(outdoorUrl);", begin.group(1))
|
||||
self.assertEqual(self.js.count("fetchOutdoor(outdoorUrl)"), 2) # begin() and startMapLibre(), once started
|
||||
|
||||
def test_a_map_starts_when_near_the_screen_or_touched_never_at_once(self):
|
||||
self.assertIn("new IntersectionObserver(", self.js)
|
||||
self.assertIn("afterLoad(begin);", self.js) # near the screen, and the page has loaded
|
||||
for event in ("pointerdown", "focusin", "keydown"):
|
||||
self.assertIn(f"'{event}'", self.js)
|
||||
def start_code(self):
|
||||
code = re.search(r"function begin\(\) \{.*?\n function entryFor", self.js, re.S).group(0)
|
||||
return re.sub(r"/\*.*?\*/", "", code, flags=re.S) # the code, not the comments
|
||||
|
||||
def test_every_map_starts_by_itself_after_the_load_event_and_nothing_else_starts_it(self):
|
||||
code = self.start_code()
|
||||
self.assertIn("window.addEventListener('load', fn, { once: true })", code)
|
||||
self.assertIn("requestIdleCallback(begin, { timeout: 500 })", code)
|
||||
self.assertIn("setTimeout(begin, 100)", code)
|
||||
self.assertEqual(len(re.findall(r"\bbegin\b", code)), 3) # its definition and those two calls, no other trigger
|
||||
|
||||
def test_no_map_waits_for_visibility_or_for_the_visitor(self):
|
||||
# the whole script: no observer of any kind, and no scroll listener
|
||||
for word in ("IntersectionObserver", "ResizeObserver", "MAP_AHEAD", "isIntersecting", "'scroll'", "'touchstart'"):
|
||||
self.assertNotIn(word, self.js)
|
||||
code = self.start_code()
|
||||
for event in ("pointerdown", "pointerup", "focusin", "focus", "keydown", "keyup", "click", "mouseover", "touch", "wheel"):
|
||||
self.assertNotIn(event, code)
|
||||
self.assertNotIn("addEventListener('" , code.replace("window.addEventListener('load'", ""))
|
||||
self.assertNotIn("startMaps", self.js)
|
||||
self.assertNotRegex(self.js, r"initMap\(fig\)[^}]*\n\s*(fetch|loadLibraries)")
|
||||
|
||||
def test_a_frame_with_no_drawing_of_its_own_is_drawn_from_the_data_at_once(self):
|
||||
# the saved trails are known only to the browser: no drawing is made when the site is built
|
||||
self.assertIn("if (!hasSketch()) dataReady = fetchData();", self.js)
|
||||
|
||||
def test_the_libraries_come_from_the_addresses_on_the_scripts_own_tag(self):
|
||||
self.assertIn("var SCRIPT = document.currentScript;", self.js)
|
||||
for attr in ("maplibreCss", "maplibreJs", "contourJs"):
|
||||
@@ -48,8 +67,11 @@ class MapStartTest(unittest.TestCase):
|
||||
# the page runs the scripts in order: the add-on needs MapLibre first
|
||||
self.assertIn("script.async = false;", self.js)
|
||||
|
||||
def test_until_it_starts_the_frame_says_what_happens_and_the_page_text_stays_for_no_script(self):
|
||||
self.assertIn("'The map loads when you scroll to it.'", self.js)
|
||||
def test_until_it_starts_the_frame_holds_its_drawing_and_says_nothing_with_a_script(self):
|
||||
# the page's own drawing fills the frame (test_first_screen.py); the no-script text is shown
|
||||
# only without JavaScript, or when a failure sets data-say
|
||||
self.assertNotIn("The map loads when you scroll to it.", self.js)
|
||||
self.assertIn("function say(text) {", self.js)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -394,7 +394,7 @@ class RealDocumentsTest(unittest.TestCase):
|
||||
counter = TableCounter()
|
||||
counter.feed(md.render(read_doc("README.md")))
|
||||
counter.close()
|
||||
self.assertEqual(counter.counts, [147, 57])
|
||||
self.assertEqual(counter.counts, [139, 57])
|
||||
|
||||
def test_readme_num_class_present(self):
|
||||
self.assertIn('class="num"', md.render(read_doc("README.md")))
|
||||
|
||||
@@ -90,7 +90,7 @@ class BuiltSiteTest(unittest.TestCase):
|
||||
def test_one_detail_page_per_record(self):
|
||||
found = [d for d in os.listdir(os.path.join(OUT, "trails"))
|
||||
if os.path.isfile(os.path.join(OUT, "trails", d, "index.html"))]
|
||||
self.assertEqual(len(self.records), 204)
|
||||
self.assertEqual(len(self.records), 196)
|
||||
self.assertEqual(sorted(found), sorted(r["id"] for r in self.records))
|
||||
self.assertTrue(os.path.isfile(os.path.join(OUT, "index.html")))
|
||||
|
||||
@@ -175,8 +175,8 @@ class BuiltSiteTest(unittest.TestCase):
|
||||
v = raw.get("verification", {})
|
||||
if raw["source"].get("line_file") and v.get("verified") and abs(v.get("difference_percent", 0)) > 15:
|
||||
expected.add(rec["id"])
|
||||
self.assertEqual(len(expected), 25)
|
||||
self.assertIn("voyageur", expected)
|
||||
self.assertEqual(len(expected), 17)
|
||||
self.assertIn("knobstone", expected)
|
||||
for rec in self.records:
|
||||
page = self.pages[rec["id"]]
|
||||
has_notice = 'class="notice notice--partial"' in page
|
||||
@@ -305,8 +305,7 @@ class BuiltSiteTest(unittest.TestCase):
|
||||
|
||||
def test_names_marked_with_their_language(self):
|
||||
langs = site.load().name_lang
|
||||
self.assertEqual(langs, {"traversee-charlevoix": "fr", "sentier-national": "fr",
|
||||
"sentier-international-appalaches": "fr"})
|
||||
self.assertEqual(langs, {"traversee-charlevoix": "fr", "sentier-international-appalaches": "fr"})
|
||||
with open(os.path.join(OUT, "index.html"), encoding="utf-8") as f:
|
||||
home = f.read()
|
||||
by_id = {r["id"]: r for r in self.records}
|
||||
@@ -331,7 +330,7 @@ class BuiltSiteTest(unittest.TestCase):
|
||||
self.assertIn('scope="col"', th, path)
|
||||
|
||||
def test_maplibre_is_not_loaded_with_the_page(self):
|
||||
# app.js loads MapLibre when the map scrolls into view or is touched, from the
|
||||
# app.js loads MapLibre a moment after the page has loaded, from the
|
||||
# addresses on its own tag (layout.py); the page itself names no MapLibre file.
|
||||
with open(os.path.join(OUT, "index.html"), encoding="utf-8") as f:
|
||||
doc = f.read()
|
||||
@@ -446,7 +445,7 @@ class RenderUnitTest(unittest.TestCase):
|
||||
rec = sample_record("L Trail")
|
||||
rec["hike"] = {"official_url": "https://official.example/"}
|
||||
rec["link"] = [{"title": "T", "publisher": "Wiki", "url": "https://wiki.example/t"}]
|
||||
buttons = re.search(r'<p class="cluster trail-actions">.*?</p>', trail.page_head(rec), re.S).group(0)
|
||||
buttons = re.search(r'<p class="cluster trail-actions">.*?</p>', trail.action_buttons(rec), re.S).group(0)
|
||||
self.assertIn("Official site", buttons)
|
||||
self.assertNotIn("wiki.example", buttons)
|
||||
|
||||
@@ -454,7 +453,7 @@ class RenderUnitTest(unittest.TestCase):
|
||||
rec = sample_record("L Trail")
|
||||
rec["link"] = [{"title": "T", "publisher": "Wiki Pub", "url": "https://wiki.example/t"},
|
||||
{"title": "U", "publisher": "Other", "url": "https://other.example/u"}]
|
||||
buttons = re.search(r'<p class="cluster trail-actions">.*?</p>', trail.page_head(rec), re.S).group(0)
|
||||
buttons = re.search(r'<p class="cluster trail-actions">.*?</p>', trail.action_buttons(rec), re.S).group(0)
|
||||
self.assertIn('href="https://wiki.example/t"', buttons)
|
||||
self.assertIn("Wiki Pub", buttons)
|
||||
self.assertNotIn("other.example", buttons)
|
||||
|
||||
@@ -13,10 +13,10 @@ class RecordsTest(unittest.TestCase):
|
||||
cls.recs = records.load_records()
|
||||
|
||||
def test_counts(self):
|
||||
self.assertEqual(len(self.recs), 204)
|
||||
self.assertEqual(len(self.recs), 196)
|
||||
self.assertEqual(sum(r["derived"]["kind"] == "route" for r in self.recs), 57)
|
||||
self.assertEqual(sum(r["derived"]["kind"] == "designated" for r in self.recs), 147)
|
||||
self.assertEqual(sum(r["derived"]["has_line"] for r in self.recs), 126)
|
||||
self.assertEqual(sum(r["derived"]["kind"] == "designated" for r in self.recs), 139)
|
||||
self.assertEqual(sum(r["derived"]["has_line"] for r in self.recs), 118)
|
||||
|
||||
def test_sorted_by_id(self):
|
||||
ids = [r["id"] for r in self.recs]
|
||||
|
||||
+23
-8
@@ -190,14 +190,14 @@ class InBrief(unittest.TestCase):
|
||||
self.assertIn("trail network", net[0])
|
||||
self.assertTrue(any(x.startswith("Most walks start at ") for x in net))
|
||||
part = self.sentences(load("allegheny-trail"))
|
||||
self.assertTrue(any("computed from the part of the track on file, about 5% of the published length" in x for x in part))
|
||||
self.assertTrue(any("computed from the part of the track on file, about 6% of the published length" in x for x in part))
|
||||
self.assertTrue(any(x == "This page has a GPX of part of the track to download." for x in part))
|
||||
|
||||
def test_trail_without_a_track_and_french_name(self):
|
||||
free = self.sentences(load("circle-of-solitude"))
|
||||
self.assertTrue(free[-1].startswith("This site has no GPX for it"))
|
||||
fr = load("sentier-national")
|
||||
self.assertTrue(self.sentences(fr)[0].startswith("Sentier National (Quebec) is a "))
|
||||
fr = load("traversee-charlevoix")
|
||||
self.assertTrue(self.sentences(fr)[0].startswith("Traversée de Charlevoix is a "))
|
||||
self.assertIn('<span lang="fr">', str(trail.brief_sentences(fr)[0]))
|
||||
|
||||
def test_a_place_name_that_starts_with_near_reads_mid_sentence(self):
|
||||
@@ -239,13 +239,28 @@ class InBrief(unittest.TestCase):
|
||||
self.assertEqual("highest point" in paragraph,
|
||||
bool(h.get("high_point") or h.get("high_point_m") or rec["derived"].get("elevation")), rec["id"])
|
||||
|
||||
def test_the_paragraph_is_in_the_page_head_before_the_buttons(self):
|
||||
def test_the_map_area_comes_first_and_the_paragraph_is_under_it(self):
|
||||
rec = load("appalachian")
|
||||
body = str(trail.render(rec, SITE, [rec])[2])
|
||||
self.assertLess(body.index('class="trail-lede"'), body.index('class="trail-brief"'))
|
||||
self.assertLess(body.index('class="trail-brief"'), body.index('class="note trail-checked"'))
|
||||
self.assertLess(body.index('class="note trail-checked"'), body.index('class="cluster trail-actions"'))
|
||||
self.assertIn("<strong>In brief.</strong>", body)
|
||||
order = ['class="titleblock', 'class="cluster trail-actions"', 'id="glance-title"', 'class="mapfig ',
|
||||
'id="brief-title"', 'class="trail-brief"', 'class="note trail-checked"']
|
||||
at = [body.index(x) for x in order]
|
||||
self.assertEqual(at, sorted(at), order)
|
||||
self.assertIn("<h2 id=\"brief-title\">In brief</h2>", body)
|
||||
self.assertIn('class="trail-summary"', body) # the summary in full stays in the page, as text
|
||||
self.assertLess(body.index('id="brief-title"'), body.index('id="morelinks-title"') if 'id="morelinks-title"' in body else len(body))
|
||||
|
||||
def test_the_lead_above_the_map_is_the_first_sentence_and_only_when_short(self):
|
||||
rec = load("appalachian")
|
||||
lead = text_of(trail.lead_text(rec))
|
||||
self.assertTrue(hike.summary(rec).startswith(lead))
|
||||
self.assertLessEqual(len(lead), trail.LEAD_MAX)
|
||||
long_rec = copy.deepcopy(rec)
|
||||
long_rec["hike"]["summary"] = "A " + "very " * 60 + "long first sentence. A second one."
|
||||
self.assertEqual(str(trail.lead_text(long_rec)), "")
|
||||
body = str(trail.render(long_rec, SITE, [long_rec])[2])
|
||||
self.assertNotIn('class="trail-lede"', body)
|
||||
self.assertIn("very very", body) # but the whole summary is under the map
|
||||
|
||||
|
||||
def words_km(rec):
|
||||
|
||||
Reference in new issue
Block a user