Merge branch 'main' into fast-tests-2

This commit is contained in:
swaits committed 2026-11-20 16:28:12 -07:00
commit 69871fc764
128 files changed
+7921 -300

No files matched your search

+11 -11
View File
@@ -1,14 +1,14 @@
{
"/regions/": "e70a9608ef0ee6a97d0591ad582abff1b165371dee5111e3277df06a53a554e1",
"/regions/atlantic-canada/": "6af5c4a79cac82eb0a4342297fd4f6755890e98597a98f219087c56432f06243",
"/regions/ca-on/": "12b5726d800090233f082a572cf1472f152552cef8fa5019f49b83e32e337eef",
"/regions/central-canada/": "fa6f8bbe466b5978f1edda22371b6aab8546efa567eee0d0405c717e278b8a3e",
"/regions/mountain-west/": "c079eb93a55c2279f24083983230057940eb032cb034057c822c52230ce22e05",
"/regions/north/": "fdfd201ae1e42b8fd17dd055815d4b06392a8ddb6ac3e72a06f15ec2b333fb56",
"/regions/us-co/": "45cb1b92fd22ffc35f82a26fe2c71b66836b0624bf0e195f9c4926dfab6a8900",
"/regions/us-co/loops/": "8883c9aac63f100196f9e853d6738a42b8199f1250c10ec34d1d0cfe8c998e7d",
"/regions/us-co/with-gpx/": "abc3f7e44cbcbf8d6cce3b5d5065e6e7c085ec5a4033842af8909077f87e1e18",
"/regions/": "7430cb0e32ffb89d0bc0bd89c476bccf9fc76e2d84175ebacd7370dc3bb20d1e",
"/regions/atlantic-canada/": "5146b4b9d1940a268cfd2345f1eee2263fd6c7e2dfd28adfdffc3fff0e698c93",
"/regions/ca-on/": "d4e543c6f163ba188a34444b42c494a3dbbd26c02f2b141339bbc230cd91f84e",
"/regions/central-canada/": "d7478ad682d715705770d35cc902c80c40d27719e7f9f5a1d99ec702d3f7a43e",
"/regions/mountain-west/": "6151f5a28d366fb48aab7027f08cea6da425201d0e7327780a01dd77cedc7bc7",
"/regions/north/": "85ba3ea850c2df690e311cf09257f2548ed888c07c319a01fd30d5e19cdf1fd4",
"/regions/us-co/": "97daaf3511578896b222570cba630da2d8ca0571504ce43b3685dbe532e40f56",
"/regions/us-co/loops/": "03896834b5369655f7b5f26634b6d23c834b17f1a25b0ec328d44934e20e2dfa",
"/regions/us-co/with-gpx/": "d82eace3d70eb9b1ef1346f5a3470199bd6a00e6e104fe661bfeb80199af96b8",
"/regions/us-hi/": "1e5681ffbd50e382db7d69528fde602069006bf0cddad494d817369224bd96ad",
"/regions/us-ut/": "065bcc01e14eb588dc1b118c466f44474fca0172c30037fb193d83a044624100",
"/regions/western-canada/": "91b40d35dd3d1a093d38d01bbfcf1ef536221a69631fc58e46732da81d0582c3"
"/regions/us-ut/": "906db4153def35fa5418d0b86dba908fd27396bbc2098978ee169516e1b39785",
"/regions/western-canada/": "1b102ed9d47283869fdf8c8d54229d245f2113fd53c7e8ec2ecc118fd4da3b64"
}
+107 -6
View File
@@ -174,6 +174,79 @@ class PlaceTest(unittest.TestCase):
self.assertIn('<a href="/regions/us-co/">Colorado</a>', crumbs)
def est_hike(**kw):
h = {"season": "June to September", "months": [6, 7, 8, 9], "season_basis": "estimate",
"season_method": "Judged from the climate at the trail's elevation and from similar trails. "
"Snow keeps the high passes closed until June. Confidence: medium."}
h.update(kw)
return h
class SeasonTextTest(unittest.TestCase):
def test_an_estimated_season_reads_about_and_has_a_note(self):
rec = fake(1, hike=est_hike())
self.assertTrue(facets.season_estimated(rec))
self.assertEqual(facets.season_text(rec), "About June to September")
note = facets.season_note(rec)
for want in ("No page states a season", "estimated from the climate at the trail's elevation and from "
"similar trails", "Snow keeps the high passes closed until June.", "Confidence: medium.",
"This is the usual window, not a closure."):
self.assertIn(want, note)
self.assertNotIn("walk it outside", note)
self.assertNotIn("Judged from", note) # the standard lead is said once, in the note's own words
def test_a_page_that_contradicts_itself_is_said_once_not_twice(self):
rec = fake(1, hike=est_hike(season_method=(
"A page was found but it contradicts itself, so no page is relied on. The season was estimated "
"from the climate and similar trails: snow lies until June. Confidence: medium.")))
note = facets.season_note(rec)
self.assertTrue(note.startswith("No page states a season. A page was found but it contradicts itself"), note)
self.assertEqual(note.count("estimated from the climate"), 1)
self.assertTrue(note.endswith("This is the usual window, not a closure."))
def test_a_season_judged_from_pages_is_not_called_estimated_from_climate(self):
judged = fake(1, hike=est_hike(season_basis="sources", season_method="The pages differ. Confidence: low."))
est = fake(2, hike=est_hike())
self.assertEqual(facets.season_unstated_clause([est, est, judged]),
"2 are estimated from the climate and similar trails and 1 is set by judgement from "
"pages that differ")
self.assertEqual(facets.season_unstated_clause([judged]), "1 is set by judgement from pages that differ")
self.assertEqual(facets.season_unstated_clause([est]), "1 is estimated from the climate and similar trails")
self.assertEqual(facets.season_unstated_clause([]), "")
def test_a_stated_season_is_unchanged_and_has_no_note(self):
rec = fake(1, hike={"season": "June to September", "months": [6, 7, 8, 9], "season_basis": "primary"})
self.assertFalse(facets.season_estimated(rec))
self.assertEqual(facets.season_text(rec), "June to September")
self.assertEqual(facets.season_note(rec), "")
def test_an_estimated_all_year_season_reads_about_all_year(self):
rec = fake(1, hike=est_hike(season="All year", months=list(range(1, 13))))
self.assertEqual(facets.season_text(rec), "About all year")
def test_it_is_not_estimated_without_a_basis_or_a_method(self):
self.assertFalse(facets.season_estimated(fake(1, hike={"season": "May", "months": [5]})))
self.assertFalse(facets.season_estimated(fake(1)))
self.assertEqual(facets.season_kind(fake(1)), "")
def test_a_season_judged_from_pages_that_differ_says_so(self):
rec = fake(1, hike=est_hike(season_basis="sources", season_method=(
"The pages differ: one gives May to October and one gives June to November. It was set by "
"judgement from both and from the climate. Confidence: medium.")))
self.assertTrue(facets.season_estimated(rec))
self.assertEqual(facets.season_kind(rec), "judged")
self.assertEqual(facets.season_text(rec), "About June to September")
note = facets.season_note(rec)
self.assertIn("No one page states this season.", note)
self.assertIn("The pages differ", note)
self.assertNotIn("estimated from the climate at the trail's elevation", note)
self.assertIn("It is a judgement", facets.season_basis_line(rec))
def test_the_basis_line_gives_the_method_for_an_estimate(self):
line = facets.season_basis_line(fake(1, hike=est_hike()))
self.assertTrue(line.endswith("Confidence: medium. No page states a season."), line)
class MissingValuesTest(unittest.TestCase):
def recs(self, n_with, n_without):
return ([fake(i, hike={"months": [7, 8], "season": "July and August", "terrain": ["alpine"]})
@@ -190,22 +263,24 @@ class MissingValuesTest(unittest.TestCase):
self.assertIn('name="terrain"', form)
def test_missing_count_is_said(self):
# the generic mechanism, shown with terrain: no real trail lacks a season any more
form = home.finder_form(self.recs(10, 12))
self.assertIn('data-missing="season" hidden>12 trails have no season on file.', form)
self.assertIn('data-missing="terrain" hidden>12 trails have no terrain on file.', form)
self.assertEqual(facets.missing_text(1, "season"), "1 trail has no season on file.")
self.assertEqual(facets.missing_text(0, "season"), "")
self.assertEqual(facets.missing_text(1, "terrain"), "1 trail has no terrain on file.")
self.assertEqual(facets.missing_text(0, "terrain"), "")
# full coverage: no note
self.assertNotIn('data-missing="season"', home.finder_form(self.recs(5, 0)))
self.assertNotIn('data-missing="terrain"', home.finder_form(self.recs(5, 0)))
def test_rows_without_a_value_carry_none(self):
# the script leaves out a row whose data-months is empty while a month is chosen
row = home.entry(fake(1))
self.assertIn('data-months=""', row)
self.assertIn('data-terrain=""', row)
row = home.entry(fake(1, hike={"months": [7, 8, 9]}))
self.assertIn('data-months="7 8 9"', row)
def test_every_real_trail_has_months(self):
for rec in records.load_records(ROOT):
self.assertTrue(facets.months(rec), rec["id"])
def test_script_leaves_out_missing_values(self):
with open(os.path.join(WEB, "assets", "app.js"), encoding="utf-8") as f:
js = f.read()
@@ -288,6 +363,32 @@ class BuiltVocabularyTest(unittest.TestCase):
self.maxDiff = None
self.assertEqual(bad[:40], [])
def test_no_page_says_only_some_trails_have_a_season(self):
found = []
for dirpath, _dirs, files in os.walk(OUT):
for name in files:
if name.endswith(".html") and "changelog" not in dirpath: # its old entries say what was
path = os.path.join(dirpath, name)
with open(path, encoding="utf-8") as f:
doc = f.read()
for phrase in ("Only some trails have a season", "season on file", "Not on file</td>",
"data-unseasoned", "Show them"):
if phrase in doc:
found.append((os.path.relpath(path, OUT), phrase))
self.assertEqual(found[:10], [])
def test_an_estimated_season_reads_about_on_its_page_and_a_stated_one_does_not(self):
est = [r for r in records.load_records(ROOT) if facets.season_estimated(r)]
stated = [r for r in records.load_records(ROOT) if not facets.season_estimated(r)]
self.assertEqual(len(est) + len(stated), 223)
for rec in est[:10]:
doc = self.read(f"trails/{rec['id']}/index.html")
self.assertIn(facets.season_text(rec), html.unescape(doc), rec["id"])
self.assertIn("This is the usual window, not a closure.", html.unescape(doc), rec["id"])
self.assertNotIn("outside these months", html.unescape(doc), rec["id"])
for rec in stated[:10]:
self.assertNotIn("This is the usual window", html.unescape(self.read(f"trails/{rec['id']}/index.html")))
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)
+96 -44
View File
@@ -1,7 +1,7 @@
"""The filter bar on every page that shows a set of trails, and the numbers beside its choices.
The bar (olt/home.py listing(), finder_form()) is the home page's, on each list, place and the Routes
page whose set has at least home.FILTER_MIN trails, built from that page's own trails. app.js counts
page, whatever the number of trails, built from that page's own trails. app.js counts
the choices again from the rows on the page every time anything changes (FacetCount, between the
facet-counts markers); this file runs that counting under node, on the rows the home page writes,
and checks it against counts made here straight from the records. Pages are rendered one at a time;
@@ -68,22 +68,36 @@ class WhichPagesHaveTheBarTest(unittest.TestCase):
lst = browse.by_key(key)
return regions.list_page(lst, self.shown[key], len(self.records), SITE, records=self.records)[2]
def test_a_list_page_a_place_page_a_part_of_the_country_and_routes_have_it(self):
self.assertGreaterEqual(len(self.shown["loops"]), home.FILTER_MIN)
self.assertTrue(form_of(self.list_body("loops")))
def test_a_list_page_a_place_page_a_part_of_the_country_and_routes_have_it(self):
self.assertTrue(form_of(self.list_body("loops")))
by_slug, _ = regions.collect_regions(self.records)
self.assertGreaterEqual(len(by_slug["ca-on"]["records"]), home.FILTER_MIN)
self.assertTrue(form_of(regions.region_page("ca-on", self.records, SITE)[2]))
self.assertTrue(form_of(regions.group_page("central-canada", self.records, SITE)[2]))
self.assertTrue(form_of(regions.routes_page(self.records, SITE)[2]))
def test_a_set_under_the_threshold_has_the_plain_rows(self):
small = [k for k, recs in self.shown.items() if len(recs) < home.FILTER_MIN and k != "routes"]
self.assertTrue(small)
def test_every_state_province_and_list_page_has_the_bar_however_few_trails(self):
by_slug, _ = regions.collect_regions(self.records)
small = [k for k, v in by_slug.items() if len(v["records"]) < 10]
self.assertGreater(len(small), 40)
for key in small:
body = self.list_body(key)
self.assertFalse(form_of(body), key)
self.assertNotIn("data-finder", str(body), key)
body = regions.region_page(key, self.records, SITE)[2]
self.assertIn('id="finder-form"', str(body), key)
self.assertIn("data-finder", str(body), key)
small_lists = [k for k, recs in self.shown.items() if len(recs) < 10 and k != "routes"]
self.assertTrue(small_lists)
for key in small_lists:
self.assertTrue(form_of(self.list_body(key)), key)
def test_a_two_trail_page_offers_only_filters_that_narrow_it(self):
by_slug, _ = regions.collect_regions(self.records)
two = [k for k, v in by_slug.items() if len(v["records"]) == 2]
self.assertTrue(two)
for key in two:
form = form_of(regions.region_page(key, self.records, SITE)[2])
self.assertIn('name="q"', form, key)
for sel in re.findall(r"<select[^>]*>(.*?)</select>", form, re.S):
self.assertNotIn("<select></select>", sel)
self.assertGreater(len(re.findall(r"<option", sel)), 1, key)
def test_the_tables_rankings_newest_authors_and_left_out_pages_do_not(self):
bodies = {}
@@ -102,14 +116,22 @@ class WhichPagesHaveTheBarTest(unittest.TestCase):
from olt import authors
groups = authors.author_pages(self.records, ROOT)
bodies["authors"] = authors.index_page(self.records, SITE, ROOT)[2]
big = max(groups, key=lambda g: len(g["routes"]))
bodies["author"] = authors.author_page(big, self.records, SITE, groups)[2]
bodies["left-out"] = leftout.left_out_page(leftout.load_entries(ROOT), SITE, ROOT)[2]
self.assertGreater(len(bodies), 4)
for name, body in bodies.items():
self.assertNotIn('id="finder-form"', str(body), name)
self.assertNotIn("data-finder", str(body), name)
def test_an_authors_own_page_has_the_bar_however_few_routes(self):
from olt import authors
groups = authors.author_pages(self.records, ROOT)
for g in (min(groups, key=lambda g: len(g["routes"])), max(groups, key=lambda g: len(g["routes"]))):
body = authors.author_page(g, self.records, SITE, groups)[2]
self.assertIn('id="finder-form"', str(body), g["name"])
def test_a_set_with_no_trails_still_builds(self):
self.assertIn("<form", str(home.finder_form([])))
def test_the_saved_page_has_no_bar(self):
from olt import saved
self.assertNotIn('id="finder-form"', str(saved.saved_page(self.records, SITE)[2]))
@@ -235,13 +257,13 @@ def rows_of(body):
d = {k: html.unescape(v) for k, v in re.findall(r' data-([a-z]+)="([^"]*)"', attrs)}
split = lambda v: [x for x in v.split(" ") if x] # noqa: E731
out.append({"id": d["id"], "search": [" " + t + " " for t in d["search"].split("|")], "where": split(d["where"]), "km": float(d["km"]),
"time": d["time"], "months": split(d["months"]), "terrain": split(d["terrain"]),
"time": d["time"], "months": split(d["months"]), "estimate": d.get("estimate") == "yes", "terrain": split(d["terrain"]),
"kind": d["kind"], "walking": d["walking"], "shape": d["shape"], "gpx": d["gpx"]})
return out
def state(**kw):
s = {"words": [], "where": "", "min": 0, "max": None, "month": "", "kind": "",
s = {"words": [], "where": "", "min": 0, "max": None, "month": "", "stated": False, "kind": "",
"time": [], "terrain": [], "walking": [], "shape": [], "gpx": []}
s.update(kw)
return s
@@ -366,45 +388,75 @@ class PanelInTheFlowTest(unittest.TestCase):
self.assertIn("if (window.location.hash === '#filters') showPanels(true);", js)
class UnseasonedNoteTest(unittest.TestCase):
"""A month filter says how many trails it leaves out for having no season on file."""
class LeaveOutEstimatesTest(unittest.TestCase):
"""The month filter can leave estimated seasons out, and says nothing about trails with no season."""
def test_a_finder_list_has_the_note_and_it_starts_hidden(self):
def test_the_month_field_has_the_checkbox_and_it_starts_disabled(self):
recs = recordsmod.load_records(ROOT)
body = str(home.results(recs, finder=True))
self.assertIn('<p class="results-note" data-unseasoned hidden>', body)
self.assertIn('data-unseasoned-show>Show them</button>', body)
self.assertNotIn("data-unseasoned", str(home.results(recs)))
form = home.finder_form(recs)
field = form[form.index('data-facet="month"'):]
field = field[:field.index("</div>")]
self.assertIn('<input type="checkbox" name="stated" value="1" disabled>', field)
self.assertIn("Leave out estimated seasons", field)
def test_the_script_counts_it_over_the_rows_of_the_list_and_show_them_clears_the_month(self):
def test_there_is_no_checkbox_where_no_trail_has_an_estimated_season(self):
recs = [r for r in recordsmod.load_records(ROOT) if not facets.season_estimated(r)]
self.assertNotIn('name="stated"', home.finder_form(recs))
def test_the_results_have_no_unseasoned_note(self):
recs = recordsmod.load_records(ROOT)
for body in (str(home.results(recs, finder=True)), str(home.results(recs))):
self.assertNotIn("data-unseasoned", body)
self.assertNotIn("Show them", body)
self.assertNotIn("no season on file", body)
js = read(WEB, "assets", "app.js")
self.assertIn("if (!d.months.length && FacetCount.passes(d, s, 'month')) noSeason++;", js)
self.assertIn("' trails with no season on file are not shown.'", js)
self.assertIn("el.month.value = '';", js)
self.assertNotIn("unseasoned", js.lower())
self.assertNotIn("no season on file", js)
def test_a_row_carries_whether_its_season_is_an_estimate(self):
est = next(r for r in recordsmod.load_records(ROOT) if facets.season_estimated(r))
stated = next(r for r in recordsmod.load_records(ROOT) if not facets.season_estimated(r))
self.assertIn('data-estimate="yes"', str(home.entry(est)))
self.assertNotIn("data-estimate", str(home.entry(stated)))
def test_the_script_reads_the_checkbox_and_writes_it_in_the_address(self):
js = read(WEB, "assets", "app.js")
self.assertIn("if (s.month && s.stated && d.estimate) return false;", js)
self.assertIn("if (s.month && s.stated) p.set('stated', '1');", js)
self.assertIn("estimate: d.estimate === 'yes'", js)
@unittest.skipUnless(NODE, "node is not installed")
def test_the_number_is_the_trails_that_pass_everything_else_and_have_no_season(self):
recs = recordsmod.load_records(ROOT)
rows = rows_of(home.render(recs, SITE, ROOT))
def test_with_stated_on_estimated_rows_leave_the_month_and_the_counts_follow(self):
def row(i, months, estimate):
return {"id": f"t{i}", "search": [" ", " ", " ", " "], "where": [], "km": 100.0, "time": "week",
"months": [str(m) for m in months], "estimate": estimate, "terrain": [], "kind": "trail", "walking": "",
"shape": "", "gpx": "none"}
rows = [row(1, [7], True), row(2, [7], False), row(3, [7, 8], False), row(4, [8], True)]
off = run_counts(rows, state(month="7"))
on = run_counts(rows, state(month="7", stated=True))
self.assertEqual((off["total"], off["month"]["7"], off["month"]["8"]), (3, 3, 2))
self.assertEqual((on["total"], on["month"]["7"], on["month"]["8"]), (2, 2, 1))
# with no month chosen it does nothing
self.assertEqual(run_counts(rows, state(stated=True))["total"], 4)
# and the shown number is the rows that pass
prog = facet_count_source() + """
var input = JSON.parse(require('fs').readFileSync(0, 'utf8'));
input.s.max = Infinity;
var n = 0, shown = 0;
input.rows.forEach(function (d) {
if (FacetCount.passes(d, input.s, '')) shown++;
else if (!d.months.length && FacetCount.passes(d, input.s, 'month')) n++;
});
process.stdout.write(JSON.stringify([shown, n]));
process.stdout.write(JSON.stringify(input.rows.filter(function (d) { return FacetCount.passes(d, input.s, ''); }).length));
"""
for s in (state(month="8"), state(month="8", kind="route"), state(month="8", where="US-CA")):
out = subprocess.run([NODE, "-e", prog], input=json.dumps({"rows": rows, "s": s}),
capture_output=True, text=True, check=True)
shown, n = json.loads(out.stdout)
def base(r):
return ((not s["kind"] or facets.kind(r) == s["kind"])
and (not s["where"] or s["where"] in facets.where_tokens(r)))
self.assertEqual(shown, sum(1 for r in recs if base(r) and 8 in facets.months(r)))
self.assertEqual(n, sum(1 for r in recs if base(r) and not facets.months(r)))
out = subprocess.run([NODE, "-e", prog], input=json.dumps({"rows": rows, "s": state(month="7", stated=True)}),
capture_output=True, text=True, check=True)
self.assertEqual(json.loads(out.stdout), on["total"])
@unittest.skipUnless(NODE, "node is not installed")
def test_on_the_real_trails_the_counts_leave_out_exactly_the_estimates(self):
recs = recordsmod.load_records(ROOT)
rows = rows_of(home.render(recs, SITE, ROOT))
for month in (1, 7):
c = run_counts(rows, state(month=str(month), stated=True))
want = sum(1 for r in recs if month in facets.months(r) and not facets.season_estimated(r))
self.assertEqual(c["total"], want)
self.assertEqual(c["month"][str(month)], want)
if __name__ == "__main__":
+32 -2
View File
@@ -137,6 +137,36 @@ class TrailPageTest(unittest.TestCase):
self.assertNotIn("The season comes from", trail.hike_sources_block(rec))
self.assertEqual(facets.season_basis(rec), "")
def test_an_estimated_season_row_carries_the_note(self):
rec = sample_record("X Trail")
rec["hike"] = dict(FULL_HIKE, season="April to October", months=[4, 5, 6, 7, 8, 9, 10],
season_basis="estimate",
season_method="Judged from the climate at the trail's elevation and from similar "
"trails. Snow and mud last into March. Confidence: high.")
t = text(top_part(render(rec)))
self.assertIn("Season About April to October", t)
self.assertIn("No page states a season.", t)
self.assertIn("Confidence: high.", t)
self.assertIn("This is the usual window, not a closure.", t)
self.assertNotIn("People do walk", t)
self.assertIn("No source gives a season; the climate suggests about April to October.", t)
self.assertNotIn("The usual season is", t)
block = html.unescape(trail.hike_sources_block(rec))
self.assertIn("Snow and mud last into March. Confidence: high. No page states a season.", block)
def test_a_source_naming_season_and_months_says_season_once(self):
rec = sample_record("X Trail")
rec["hike"] = dict(FULL_HIKE, season_basis="primary")
block = html.unescape(trail.hike_sources_block(rec))
self.assertNotIn("season and season", block)
def test_a_stated_season_row_has_no_note(self):
rec = sample_record("X Trail")
rec["hike"] = dict(FULL_HIKE, season_basis="primary")
t = text(top_part(render(rec)))
self.assertIn("Season March to October", t)
self.assertNotIn("No page states a season", t)
def test_partial_hike_table(self):
rec = sample_record("X Trail")
rec["hike"] = {"shape": "loop", "start": "Lake Camp", "days": [4, 6], "checked": "2026-11-13"}
@@ -144,7 +174,7 @@ class TrailPageTest(unittest.TestCase):
t = text(top)
self.assertIn("Shape Loop. Starts and ends at Lake Camp", t)
self.assertIn("Time 4 to 6 days", t)
self.assertIn("Season, terrain, walking and permits are not on file for this trail yet.", t)
self.assertIn("Terrain, walking and permits are not on file for this trail yet.", t)
for absent in ("Season March", "High point", "Terrain Alpine", "Permits", "Not finished", "Official site"):
self.assertNotIn(absent, t, absent)
# no summary: the lede is built from the record
@@ -175,7 +205,7 @@ class TrailPageTest(unittest.TestCase):
self.assertIn("Where Arizona , United States", t)
# every trail has a time: here estimated from its 100 km, and labelled so
self.assertIn("Time About 4 to 5 days Estimated from the length, at 12 to 19 mi 20 to 30 km a day.", t)
self.assertIn("Season, terrain, walking and permits are not on file for this trail yet.", t)
self.assertIn("Terrain, walking and permits are not on file for this trail yet.", t)
self.assertNotIn("Where the hiking facts come from", body)
# no track: the page says so plainly and points at the source
self.assertIn("No GPX here", t)
+42 -11
View File
@@ -29,6 +29,31 @@ def infos(records):
return places.collect(records, registry())
class HomeWayInTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.records = wind_records(4) + yosemite_records(3)
def test_below_the_rows_a_line_links_each_kind_that_has_pages(self):
body = str(home.render(self.records, S, ROOT, place_kinds=["park", "range", "wilderness"]))
line = re.search(r'<p class="finder__foot finder__places">(.*?)</p>', body, re.S).group(1)
self.assertEqual(
re.sub(r"<[^>]+>", "", line),
"Browse by park, by mountain range or by wilderness area.")
for frag in ('href="/regions/#parks">park', 'href="/regions/#ranges">mountain range',
'href="/regions/#wilderness">wilderness area'):
self.assertIn(frag, line)
# after the rows and the map, in the notes at the foot, never in the intro
self.assertGreater(body.index("finder__places"), body.rindex('<li class="entry"'))
self.assertGreater(body.index("finder__places"), body.index('id="browse-list"'))
self.assertLess(body.index("</section>"), body.index("finder__places"))
def test_only_the_kinds_with_pages_and_none_when_there_are_none(self):
line = re.search(r'finder__places">(.*?)</p>', str(home.render(self.records, S, ROOT, place_kinds=["range"])), re.S).group(1)
self.assertEqual(re.sub(r"<[^>]+>", "", line), "Browse by mountain range.")
self.assertNotIn("finder__places", str(home.render(self.records, S, ROOT)))
class HubTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
@@ -48,18 +73,24 @@ class HubTest(unittest.TestCase):
self.assertIn("Parks, mountain ranges and wilderness areas with three or more "
"trails have pages too.", re.sub(r"\s+", " ", body))
def test_the_shortcut_strip_links_each_kind_that_has_pages(self):
def test_a_jump_row_tops_the_hub_with_exact_counts_of_pages(self):
_, _, body = regions.regions_index_page(self.records, S, infos=self.infos)
strip = str(body)[str(body).index('<nav class="lists-row"'):]
strip = strip[:strip.index("</nav>")]
self.assertIn('<a href="#parks">Parks<span class="lists-row__n">1</span></a>', strip)
self.assertIn('<a href="#ranges">Mountain ranges<span class="lists-row__n">1</span></a>', strip)
self.assertNotIn("#wilderness", strip) # no wilderness page here: no shortcut
# the regional groups are still there, before the kinds
self.assertLess(strip.index('href="#west-coast"') if 'href="#west-coast"' in strip
else strip.index("<li>"), strip.index('href="#parks"'))
body = str(body)
by_slug, _ = regions.collect_regions(self.records)
row = body[body.index('<nav class="places-jump"'):]
row = row[:row.index("</nav>")]
self.assertLess(body.index('<nav class="places-jump"'), body.index("<h1>"))
self.assertIn(f'<a href="#states-and-provinces">States and provinces <span class="places-jump__n">{len(by_slug)}</span></a>', row)
self.assertIn('<a href="#parks">Parks <span class="places-jump__n">1</span></a>', row)
self.assertIn('<a href="#ranges">Mountain ranges <span class="places-jump__n">1</span></a>', row)
self.assertNotIn("#wilderness", row) # no wilderness page here: no link
self.assertLess(row.index("#states-and-provinces"), row.index("#parks"))
self.assertIn('id="states-and-provinces"', body)
# the kinds are in the one row, not also in the strip of regional groups
strip = body[body.index('<nav class="lists-row"'):]
self.assertNotIn("#parks", strip[:strip.index("</nav>")])
_, _, plain = regions.regions_index_page(self.records, S)
self.assertNotIn('href="#parks"', str(plain))
self.assertNotIn('class="places-jump"', str(plain))
def test_the_hub_still_lists_every_state_group_as_before(self):
_, _, plain = regions.regions_index_page(self.records, S)
@@ -67,7 +98,7 @@ class HubTest(unittest.TestCase):
stripped = re.sub(r'<section class="places__group" aria-labelledby="(?:parks|ranges|wilderness)">.*?</section>',
"", str(with_places), flags=re.S)
stripped = stripped.replace(" or a kind of place", "")
stripped = re.sub(r'<li><a href="#(?:parks|ranges|wilderness)">.*?</li>', "", stripped)
stripped = re.sub(r'<nav class="places-jump".*?</nav>\s*', "", stripped, 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))
+14 -1
View File
@@ -203,6 +203,17 @@ class JsonLdTest(unittest.TestCase):
count += 1
self.assertEqual(count, len(self.records))
def test_no_estimated_season_appears_in_structured_data(self):
seen = 0
for rec in self.records:
h = rec.get("hike", {})
if not (h.get("season_basis") == "estimate" or h.get("season_method")):
continue
seen += 1
page = self.pages[f"trails/{rec['id']}/index.html"]
self.assertNotIn("Usual season", page, rec["id"])
self.assertGreater(seen, 0)
def test_a_trail_states_only_what_its_record_holds(self):
built_derived = {r["id"]: r["derived"] for r in json.loads(read("data/trails.json"))}
for rec in self.records:
@@ -213,7 +224,9 @@ class JsonLdTest(unittest.TestCase):
self.assertEqual(props[("Published length", "KMT")]["value"], rec["length_km"], rec["id"])
h = rec.get("hike", {})
self.assertEqual(("Start", None) in props, bool(h.get("start")), rec["id"])
self.assertEqual(("Usual season", None) in props, bool(h.get("season")), rec["id"])
self.assertEqual(("Usual season", None) in props,
bool(h.get("season") and h.get("season_basis") != "estimate" and not h.get("season_method")),
rec["id"])
self.assertEqual(any(k[0] == "Highest point" for k in props),
bool(h.get("high_point_m") or h.get("high_point")), rec["id"])
if h.get("official_url"):
+25 -4
View File
@@ -16,7 +16,7 @@ WEB = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
ROOT = os.path.dirname(WEB)
sys.path.insert(0, WEB)
from olt import common, docs, hike, records, seo, site, trail # noqa: E402
from olt import common, docs, facets, hike, records, seo, site, trail # noqa: E402
SITE = site.load()
@@ -160,6 +160,21 @@ class InBrief(unittest.TestCase):
("range", "The usual season is spring and fall"))
self.assertIsNone(season("Best travelled " + "in the later part of the summer " * 5))
def test_an_estimated_season_sentence_says_no_source_gives_one(self):
rec = sparse_record()
rec["hike"] = {"season": "June to September", "months": [6, 7, 8, 9], "season_basis": "estimate",
"season_method": "Judged from the climate. Snow. Confidence: low."}
self.assertEqual(trail.season_sentence(rec),
("estimate", "No source gives a season; the climate suggests about June to September"))
rec["hike"]["season_basis"] = "sources"
self.assertEqual(trail.season_sentence(rec),
("estimate", "The pages differ on the season; it is judged to be about June to September"))
rec["hike"].update(season="All year", months=list(range(1, 13)), season_basis="estimate")
self.assertEqual(trail.season_sentence(rec)[1], "No source gives a season; the climate suggests about all year")
# the sentence stands alone: it is never joined to the GPX clause with "and"
paragraph = " ".join(trail.brief_sentences(rec))
self.assertIn("No source gives a season; the climate suggests about all year.", paragraph)
def test_a_permit_is_said_only_when_it_is_short(self):
short = sparse_record()
short["hike"] = {"permit": "No permit is needed to hike it."}
@@ -217,7 +232,8 @@ class InBrief(unittest.TestCase):
s = self.sentences(rec)
paragraph = " ".join(s)
self.assertGreaterEqual(len(s), 2, rec["id"])
self.assertLessEqual(len(s), 4, rec["id"])
# four sentences, and a fifth where the season is an estimate, which is always said
self.assertLessEqual(len(s), 4 + facets.season_estimated(rec), rec["id"])
self.assertIn("GPX", paragraph, rec["id"])
self.assertNotRegex(paragraph, r"\b(Season|Permits are noted)\b", rec["id"])
for bad in ("None", "{", "}", " ", " ,", " .", "unknown", "not known", "n/a"):
@@ -232,8 +248,13 @@ class InBrief(unittest.TestCase):
self.assertIn("usually takes", paragraph, rec["id"])
else:
self.assertNotIn("usually takes", paragraph, rec["id"])
if not (h.get("season") or h.get("months")):
self.assertNotRegex(paragraph, r"usual season|walked all year|Northbound|season", rec["id"])
self.assertTrue(h.get("season"), rec["id"])
if facets.season_estimated(rec):
self.assertIn("No source gives a season" if not facets.season_pages_differ(rec)
else "The pages differ on the season", paragraph, rec["id"])
self.assertNotIn("The usual season is", paragraph, rec["id"])
else:
self.assertNotIn("No source gives a season", paragraph, rec["id"])
if "No permit" in paragraph or "permit" in paragraph.lower():
self.assertIn(common.sentence(h.get("permit", "")), paragraph, rec["id"])
self.assertEqual("highest point" in paragraph,
+89 -2
View File
@@ -8,6 +8,7 @@ These do not need the built site.
"""
import os
import re
from html import unescape as html_unescape
import shutil
import tempfile
import sys
@@ -117,7 +118,7 @@ class MonthListTest(unittest.TestCase):
self.assertEqual(keys(recs, "hike-in-july"), ["t1"])
self.assertEqual(keys(recs, "hike-in-august"), ["t2"])
def test_a_month_needs_eight_trails_and_says_how_many_have_a_season(self):
def test_a_month_needs_eight_trails(self):
july = browse.by_key("hike-in-july")
self.assertEqual(july.min_size, 8)
self.assertFalse(browse.is_shown(7, 100, july.min_size))
@@ -126,8 +127,48 @@ class MonthListTest(unittest.TestCase):
shown = {lst.key for lst, _ in browse.shown(recs)}
self.assertIn("hike-in-july", shown)
self.assertNotIn("hike-in-august", shown)
def est(self, i, months=(7,)):
return fake(i, hike={"months": list(months), "season": "July", "season_basis": "estimate",
"season_method": "Judged. Confidence: low."})
def test_a_month_note_counts_stated_and_estimated_exactly(self):
july = browse.by_key("hike-in-july")
recs = [fake(i, hike={"months": [7], "season": "July", "season_basis": "primary"}) for i in range(10)] \
+ [self.est(20 + i) for i in range(5)]
note = july.note(browse.members(july, recs), recs)
self.assertIn("Only 10 of the 20 trails have a season on file", note)
self.assertEqual(note, "A source states the season for 10 of these. For the other 5 it is estimated "
"from the climate and similar trails, and marked.")
def test_a_month_note_tells_estimated_from_judged_from_pages_that_differ(self):
july = browse.by_key("hike-in-july")
judged = fake(90, hike={"months": [7], "season": "July", "season_basis": "sources",
"season_method": "The pages differ. Confidence: low."})
stated = fake(91, hike={"months": [7], "season": "July", "season_basis": "primary"})
recs = [stated, judged] + [self.est(20 + i) for i in range(3)]
self.assertEqual(july.note(browse.members(july, recs), recs),
"A source states the season for 1 of these. For the other 4, 3 are estimated from the climate "
"and similar trails and 1 is set by judgement from pages that differ, and marked.")
recs = [judged, judged]
self.assertEqual(july.note(browse.members(july, recs), recs),
"No source states the season for these, so each is set by judgement from pages that differ.")
def test_a_month_list_with_no_estimates_says_so(self):
july = browse.by_key("hike-in-july")
recs = [fake(i, hike={"months": [7], "season": "July", "season_basis": "primary"}) for i in range(10)]
self.assertEqual(july.note(browse.members(july, recs), recs), "A source states the season for all 10.")
recs = [self.est(i) for i in range(3)]
self.assertEqual(july.note(browse.members(july, recs), recs),
"No source states the season for these, so each is estimated from the climate and similar trails.")
def test_the_month_blurb_no_longer_says_only_some_trails(self):
group = {key: blurb for key, _title, blurb in browse.GROUPS}["month"]
self.assertEqual(group, "Trails normally hiked in the month. Estimated seasons are marked.")
self.assertEqual(browse.by_key("hike-in-july").blurb,
"Trails normally hiked in July. Estimated seasons are marked.")
for lst in browse.LISTS:
self.assertNotIn("Only some trails", lst.blurb)
self.assertNotIn("season on file", lst.blurb)
def test_every_list_has_a_group_and_every_group_a_heading(self):
headings = {k for k, _, _ in browse.GROUPS}
@@ -141,6 +182,22 @@ class MonthListTest(unittest.TestCase):
self.assertLessEqual(len(t), common.TITLE_LIMIT, t)
class MonthListsAreASetOfTwelveTest(unittest.TestCase):
def test_a_month_in_nearly_every_trail_is_still_shown(self):
# every trail has a season now, so September holds far more than MAX_SHARE of them
recs = [fake(i, hike={"months": [9]}) for i in range(100)]
shown = {lst.key for lst, _ in browse.shown(recs)}
self.assertIn("hike-in-september", shown)
self.assertFalse(browse.is_shown(100, 100)) # an ordinary list over the cap still is not
self.assertTrue(browse.is_shown(100, 100, browse.by_key("hike-in-september").min_size, capped=False))
def test_all_twelve_month_pages_exist_on_the_real_data(self):
recs = records.load_records(ROOT)
shown = {lst.key for lst, _ in browse.shown(recs)}
for name in facets.MONTHS:
self.assertIn(f"hike-in-{name.lower()}", shown)
class PlaceFacetTest(unittest.TestCase):
def setUp(self):
# Eight trails in Arizona: six under 100 miles, three of them loops; two in Utah.
@@ -628,6 +685,36 @@ class RealDataTest(unittest.TestCase):
n_ver = len(reference.verified(self.records))
self.assertIn(f"{n_ver} of the {len(self.records)} trails have a track", str(body))
def method_text(self):
title, desc, body = reference.method_page(self.records, SITE, ROOT)
return re.sub(r"\s+", " ", html_unescape(re.sub(r"<[^>]+>", " ", str(body))))
def test_the_reference_page_counts_stated_and_estimated_seasons(self):
text = self.method_text()
kinds = {k: sum(1 for r in self.records if facets.season_kind(r) == k) for k in ("stated", "judged", "estimated")}
self.assertEqual(sum(kinds.values()), len(self.records))
self.assertIn(f"A season a page states Records with it {kinds['stated']} Records without {len(self.records) - kinds['stated']}", text)
self.assertIn(f"A season estimated from the climate and similar trails Records with it {kinds['estimated']} Records without {len(self.records) - kinds['estimated']}", text)
self.assertIn(f"A season set from pages that differ Records with it {kinds['judged']} Records without {len(self.records) - kinds['judged']}", text)
self.assertIn(f"All trails Trails {len(self.records)}", text)
def test_the_reference_page_gives_the_blind_test_from_its_file(self):
blind = datafiles.blind_test(ROOT)
text = self.method_text()
self.assertIn(f"the method was run blind on {blind['tested']} trails whose seasons a page does state", text)
self.assertIn(f"{blind['matched']} of {blind['tested']} ({round(blind['share'] * 100)} percent) had their first "
f"and last months within a month of the page\u2019s; {blind['strict_matched']} "
f"({round(blind['strict_share'] * 100)} percent) also had no wrong gap in the middle", text)
for name, v in blind["by_confidence"].items():
self.assertIn(f"{name} {v['matched']} of {v['tested']} ({round(v['share'] * 100)} percent) and "
f"{v['strict_matched']} ({round(v['strict_share'] * 100)} percent)", text)
self.assertIn("not a promise for any one trail", text)
def test_the_glossary_no_longer_says_only_some_records_state_a_season(self):
season = next(t for t in reference.terms(ROOT) if t["id"] == "season")
self.assertNotIn("Only some", season["definition"])
self.assertIn("estimated", season["definition"])
def test_every_place_page_has_a_summary_paragraph(self):
by_slug, _ = regions.collect_regions(self.records)
for slug in by_slug: