"""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 shared layout of every page that shows a set of
trails, the rows that take the place of tables, 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, facets, 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("(.*?)', row)
# the file's lists in its order, with the trip-length band it leaves out added where it belongs
keys = keys[:7] + ["two-to-four-weeks"] + keys[7:]
self.assertEqual(titles, [browse.by_key(k).title for k in keys])
self.assertTrue(row.rstrip().endswith(""))
self.assertIn('All lists ', row)
self.assertNotIn("Hiking in", row)
self.assertNotIn("chips", row) # one quiet line of links, not pills
# 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'(.*?)'):]
self.assertLess(grid.index('class="browse__map" id="map"'), grid.index('class="browse__list"'))
self.assertLess(grid.index('class="browse__list"'), grid.index('id="finder-form"'))
self.assertLess(grid.index('id="finder-form"'), grid.index('id="entries"'))
self.assertNotIn("filters__maplink", self.body)
def test_the_open_filters_sit_between_the_bar_and_the_rows_and_can_be_closed(self):
css = read(WEB, "assets", "style.css")
self.assertNotRegex(css, r"\.filters__panels \{[^}]*position: absolute;")
self.assertIn('class="button filters__done"', self.body)
js = read(WEB, "assets", "app.js")
self.assertIn("e.key === 'Escape'", js)
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'', html)}, html
def current(self, path):
html = str(layout.header(path, SITE))
return re.findall(r' ]*> ]*>(?:)?([A-Za-z]+)", html)
self.assertEqual(names[:5], ["Trails", "Places", "Lists", "About", "Saved"])
self.assertIn('Lists ', 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 NoTablesTest(unittest.TestCase):
"""The site sets no tables. A set of trails is the site's trail rows; a set of other things is
rows in the same language (pagekit.rows_list); a table written in Markdown is set the same way."""
def test_a_set_of_things_is_rows_with_a_name_a_sentence_and_a_line_of_facts(self):
t = str(pagekit.table(["File", "What it holds", "Size"],
[["a.json", "Every trail with all its fields, written out for the programs that read it", "3 MB"]],
caption="c"))
self.assertNotIn("', t)
self.assertLess(t.index('class="entry__name">a.json'), t.index('class="entry__desc">Every trail'))
self.assertIn('Size 3 MB
', t)
def test_a_table_written_in_markdown_or_by_hand_is_set_as_rows(self):
html = ('x
Tier Records '
'Measured 12 Stated 3
y
')
out = pagekit.untable(html)
self.assertNotIn("(\w+)<', out), ["Measured", "Stated"])
self.assertTrue(out.startswith("x
") and out.endswith("y
"))
def test_the_triple_crown_is_three_trail_rows_with_their_map_and_the_compared_figures_in_each_row(self):
from olt import standing
recs = records.load_records(ROOT)
c = datafiles.collections(ROOT)[0]
title, desc, body, members = standing.collection_page(c, recs, SITE)
body = str(body)
self.assertNotIn("High point", body)
self.assertIn("Designated ", body)
def test_a_ranking_is_the_trail_rows_in_rank_order_led_by_the_rank_and_the_figure(self):
from olt import standing
recs = records.load_records(ROOT)
title, desc, body, have = standing.ranking_page(standing.RANKINGS[0], recs, SITE)
body = str(body)
self.assertNotIn("No. 1', first)
self.assertIn('', body)
def test_the_left_out_entries_are_rows_in_the_trail_row_language(self):
src = read(WEB, "olt", "leftout.py")
self.assertNotIn("', 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_browsing_page_is_the_map_and_the_rows_then_the_text_about_the_set(self):
grid = str(home.browse_view("LIST", 'MAP ', about="TEXT
", about_title="About X"))
self.assertLess(grid.index("MAP"), grid.index("LIST")) # the map is a band above the rows when narrow
self.assertLess(grid.index("LIST"), grid.index("TEXT")) # the text about the set follows the rows
self.assertIn('About X ', grid)
css = read(WEB, "assets", "style.css")
self.assertIn('grid-template-areas: "list map";', css)
self.assertRegex(css, r"\.browse__map \{ grid-area: map; position: sticky;")
def test_a_set_too_small_to_map_is_the_rows_with_the_note_under_them(self):
grid = str(home.browse_view("LIST", 'NOTE
'))
self.assertIn('class="browse browse--no-map"', grid)
self.assertLess(grid.index("LIST"), grid.index("NOTE"))
def test_a_place_page_has_its_rows_before_its_summary(self):
from olt import regions
recs = records.load_records(ROOT)
_, _, body, _ = regions.region_page("us-co", recs, SITE)
body = str(body)
self.assertLess(body.index('class="browse__list"'), body.index('class="browse-about"'))
self.assertNotIn("percent", body)
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()