diff --git a/tools/tests/test_held_note.py b/tools/tests/test_held_note.py new file mode 100644 index 0000000..46418a2 --- /dev/null +++ b/tools/tests/test_held_note.py @@ -0,0 +1,36 @@ +"""Tests for the held-needs-a-note rule in tools/validate.py. + +Run from the repository root: + python3 -m unittest discover tools/tests +""" +import os +import sys +import unittest + +sys.dont_write_bytecode = True +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +import validate as V # noqa: E402 + + +def check(rec): + errors = [] + V.check_held_note("t", rec, errors) + return errors + + +class HeldNoteTests(unittest.TestCase): + def test_held_without_a_note_fails(self): + self.assertEqual(len(check({"wave": "held"})), 1) + self.assertEqual(len(check({"wave": "held", "wave_note": " "})), 1) + + def test_held_with_a_note_passes(self): + self.assertEqual(check({"wave": "held", "wave_note": "No whole track exists."}), []) + + def test_other_waves_need_no_note(self): + self.assertEqual(check({"wave": 1}), []) + self.assertEqual(check({}), []) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/validate.py b/tools/validate.py index ccc7fa2..1b5c7ca 100644 --- a/tools/validate.py +++ b/tools/validate.py @@ -466,6 +466,12 @@ def _whole_km(value): return isinstance(value, int) and not isinstance(value, bool) and value > 0 +def check_held_note(tid, rec, errors): + """A held record says why in wave_note: the page quotes it, and says nothing when there is none.""" + if str(rec.get("wave", "")) == "held" and not str(rec.get("wave_note", "")).strip(): + errors.append(f"{tid}: wave is held but wave_note does not say why") + + def check_length_facts(tid, rec, errors): """system_km, system_note and built_km (docs/schema.md, "What length_km counts"). @@ -754,6 +760,7 @@ def main(): check_short_name(tid, rec, errors) check_common_name(tid, rec, errors) check_length_facts(tid, rec, errors) + # check_held_note(tid, rec, errors) # to switch on once the five held records have their notes if rec.get("id") != tid: errors.append(f"{tid}: id {rec.get('id')!r} does not match directory name") if rec.get("country") not in ("US", "CA"): diff --git a/web/assets/style.css b/web/assets/style.css index fa98356..30ef86e 100644 --- a/web/assets/style.css +++ b/web/assets/style.css @@ -959,7 +959,7 @@ html.js .termini-list { position: absolute; inline-size: 1px; block-size: 1px; o border-radius: var(--radius); color: var(--ink); } -.maplibregl-ctrl-attrib-button { background-color: transparent; } +.maplibregl-ctrl-attrib-button { background-color: transparent; background-repeat: no-repeat; background-position: center; } .maplibregl-ctrl-attrib.maplibregl-compact-show .maplibregl-ctrl-attrib-button { background-color: transparent; } @media (pointer: coarse) { .maplibregl-ctrl-group button { inline-size: 2.75rem; block-size: 2.75rem; width: 2.75rem; height: 2.75rem; } @@ -2038,9 +2038,11 @@ td .linklist a { font-weight: 400; } .trail-actions__gpx { grid-column: 1 / -1; } } @media (max-width: 39.99rem) { - .trail-actions { flex-wrap: nowrap; } + .trail-actions { flex-wrap: wrap; } .trail-actions .button { flex: 0 1 auto; min-inline-size: 0; padding-inline: var(--space-3); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } - .trail-actions .trail-actions__gpx { flex: 1 1 auto; } + /* The GPX button says where the GPX is ("Not here, see the official site"): it wraps, on a line of its + own when it does not fit, and never cuts its words. */ + .trail-actions .trail-actions__gpx { flex: 1 1 auto; white-space: normal; overflow: visible; text-overflow: clip; text-align: center; line-height: 1.25; } } /* Under the map: the summary in full, the "In brief" paragraph, the date of the last check (small print), and the other pages about the trail. */ diff --git a/web/olt/common.py b/web/olt/common.py index 4a7ac9f..31526e7 100644 --- a/web/olt/common.py +++ b/web/olt/common.py @@ -214,9 +214,36 @@ def rich(text): return Markup("".join(f"{p}" if i % 2 else p for i, p in enumerate(parts))) +# Services the maintainers search with. A search is a note for maintainers (the record's own notes), not +# something a visitor is told on the page. +INTERNAL_SERVICE = re.compile(r"\b(Overpass|Nominatim|Geofabrik)\b") + + +def visitor_text(text): + """text without the sentences that name a maintainers' search service.""" + parts = re.split(r"(?<=[.!?])\s+", text.strip()) + return " ".join(p for p in parts if not INTERNAL_SERVICE.search(p)) + + +def not_added_yet(rec): + """True when the record says only that no track has been added yet: a public track exists, or may, + and the page must not give a reason of the kind "no track may be passed on".""" + src = rec.get("source", {}) + return src.get("status") == "osm-only" or src.get("line_absent_reason", "").startswith("No track has been added") + + +def sells_gpx(rec): + """True when a guide the author sells names a GPX or GPS track in what it holds (its format or + title); a route sold only as a book or map set has no GPX to sell.""" + return any(g.get("access") == "purchase" and re.search(r"GPX|GPS", f'{g.get("format", "")} {g.get("title", "")}', re.I) + for g in rec.get("guide", [])) + + def absent_reason_short(rec): """line_absent_reason without the opening "No line is included." or "No track is included." (the status already says so).""" - reason = rec.get("source", {}).get("line_absent_reason", "") + reason = visitor_text(rec.get("source", {}).get("line_absent_reason", "")) + if not_added_yet(rec): + return visitor_text(reason.split(". ")[0].rstrip(".") + ".") if reason else reason return re.sub(r"^No (?:line|track) is included\.\s*", "", reason) or reason diff --git a/web/olt/facets.py b/web/olt/facets.py index bb641ac..54c4d3b 100644 --- a/web/olt/facets.py +++ b/web/olt/facets.py @@ -286,6 +286,15 @@ def gpx(rec): return "elsewhere" +def gpx_status_text(rec): + """GPX_STATUS for the trail's page. A route sold only as a book or map set has no GPX to sell, so + it is not "Sold by its author" as a GPX is.""" + status = gpx(rec) + if status == "sold" and not common.sells_gpx(rec): + return "Not here, sold as a guide" + return GPX_STATUS[status] + + def gpx_here(rec): return gpx(rec) in ("here", "partial") diff --git a/web/olt/pages.py b/web/olt/pages.py index a0818d0..6522509 100644 --- a/web/olt/pages.py +++ b/web/olt/pages.py @@ -166,8 +166,9 @@ def render_site(records, out_dir, repo_root, site=None): pending = [] # (path, title, description, body, add() options): written once every view is known - def view(path, group, link_label, blurb, built): - """Hold a view page built as (title, description, body, recs...) and note it for /lists/.""" + def view(path, group, link_label, blurb, built, count=None): + """Hold a view page built as (title, description, body, recs...) and note it for /lists/. + count: what the page's tile counts, when that is not the trails it lists (the authors page lists routes).""" t, d, b = built[:3] recs = built[3] if len(built) > 3 and isinstance(built[3], list) else None pending.append((path, t, d, b, {"recs": recs, "maps": 'data-map="overview"' in str(b)})) @@ -175,7 +176,7 @@ def render_site(records, out_dir, repo_root, site=None): layout.UNDER_LISTS.add(path) # its header item is Lists labels[path] = link_label if group: - extras.append((group, link_label, blurb, path, len(recs) if recs else 0)) + extras.append((group, link_label, blurb, path, count if count is not None else len(recs) if recs else 0)) for c in datafiles.collections(repo_root): built = standing.collection_page(c, records, site) @@ -198,7 +199,7 @@ def render_site(records, out_dir, repo_root, site=None): if authors_built: t, d, b, routes = authors.index_page(records, site, repo_root) view(authors.INDEX, "standing", "Route authors", f"The {len(routes)} routes by who published them, and where.", - (t, d, b, routes)) + (t, d, b, routes), count=len(author_groups)) for g in author_groups: t, d, b, needs_map, routes, person = authors.author_page(g, records, site, author_groups) path = authors.path(g) diff --git a/web/olt/placefacets.py b/web/olt/placefacets.py index 2ad1c66..f5a5ab9 100644 --- a/web/olt/placefacets.py +++ b/web/olt/placefacets.py @@ -106,12 +106,12 @@ def page(p, records, site, all_pages):
{home.browse_view(home.listing(recs, default_sort=lst.sort, top=2, where=""), home.overview_map(recs, f"Map of the trails in {name}: {lst.title}", place=bounds.place_box(info["key"])), - about=summary.facts(recs, records), about_title=f"About these trails in {name}")} + about=summary.facts(recs, records, place=(name, [info["key"]])), about_title=f"About these trails in {name}")} {nav}
""" by_length = sorted(recs, key=lambda r: (r["length_km"], r["id"])) - first = (f"{count} in {name}, from {common.plain_name(by_length[0])}, {regions._miles(by_length[0])} miles, " - f"to {common.plain_name(by_length[-1])}, {regions._miles(by_length[-1])} miles.") + first = (f"{count} in {name}, from {common.plain_name(by_length[0])}, {regions.trail_miles(by_length[0], [info["key"]])}, " + f"to {common.plain_name(by_length[-1])}, {regions.trail_miles(by_length[-1], [info["key"]])}.") desc = regions._fit([f"{lst.blurb} {first}", f"{lst.noun} in {name}: {first}"]) return title, desc, Markup(body), home.has_overview_map(recs) diff --git a/web/olt/regions.py b/web/olt/regions.py index 74a93b0..2b7c7d4 100644 --- a/web/olt/regions.py +++ b/web/olt/regions.py @@ -63,6 +63,12 @@ def _miles(rec): return words.fmt_int(rec["derived"]["length_mi"]) +def trail_miles(rec, keys): + """"5,008 miles in all" for a trail that also lies outside keys (a place's state keys), "50 miles" + for one wholly inside: a place's description never gives a whole trail's length as the place's.""" + return f"{_miles(rec)} miles" + ("" if summary.wholly_in(rec, keys) else " in all") + + def _fit(options, limit=common.DESCRIPTION_LIMIT): """The first of options (fullest first) that fits; else the last, cut at a word.""" return common.cut_at_word(next((o for o in options if len(o) <= limit), options[-1]), limit) @@ -161,14 +167,14 @@ def group_page(g, records, site):
{home.browse_view(home.listing(recs, top=2, where="g:" + g), home.overview_map(recs, f"Map of the trails in {name}", place=group_box(g, by_slug)), - about=f"{summary.facts(recs, records)}{summary.details(recs)}", about_title=f"About the trails in {name}")} + about=f"{summary.facts(recs, records, place=(name, keys))}{summary.details(recs)}", about_title=f"About the trails in {name}")} {nav}
""" title = common.fit_title([f"Long Trails in {name}: {_plural(len(recs), 'Trail')}", f"Long Trails in {name}"], site) by_length = sorted(recs, key=lambda r: (r["length_km"], r["id"])) first = (f"{_plural(len(recs))} in {name} ({words.join_names(i['name'] for i in places)}), from " - f"{common.plain_name(by_length[0])}, {_miles(by_length[0])} miles, to {common.plain_name(by_length[-1])}, " - f"{_miles(by_length[-1])} miles.") + f"{common.plain_name(by_length[0])}, {trail_miles(by_length[0], keys)}, to {common.plain_name(by_length[-1])}, " + f"{trail_miles(by_length[-1], keys)}.") gpx = f" {_with_gpx(n_gpx, len(recs))[:1].upper()}{_with_gpx(n_gpx, len(recs))[1:]}." if n_gpx else "" desc = _fit([first + gpx, first, f"{_plural(len(recs))} in {name}.{gpx}"]) return title, desc, Markup(body), home.has_overview_map(recs), recs @@ -214,7 +220,7 @@ def region_page(slug, records, site, facet_pages=()):
{home.browse_view(home.listing(recs, top=2, where=""), home.overview_map(recs, f"Map of the trails in {info['name']}", place=bounds.place_box(key)), - about=f"{summary.facts(recs, records)}{summary.details(recs)}", + about=f"{summary.facts(recs, records, place=(info['name'], [key]))}{summary.details(recs)}", about_title=f"About the trails in {info['name']}")} {nav}
""" @@ -236,10 +242,10 @@ def region_page(slug, records, site, facet_pages=()): what = _plural(len(recs), "route") gpx = f" {_with_gpx(n_gpx, len(recs))[:1].upper()}{_with_gpx(n_gpx, len(recs))[1:]}." if n_gpx else "" if len(recs) == 1: - first = f"{common.plain_name(longest)}, {_miles(longest)} miles, is the one long trail listed in {name}, {country}." + first = f"{common.plain_name(longest)}, {trail_miles(longest, [key])}, is the one long trail listed in {name}, {country}." else: - first = (f"{what[:1].upper() + what[1:]} in {name}, {country}, from {common.plain_name(shortest)}, {_miles(shortest)} miles, " - f"to {common.plain_name(longest)}, {_miles(longest)} miles.") + first = (f"{what[:1].upper() + what[1:]} in {name}, {country}, from {common.plain_name(shortest)}, {trail_miles(shortest, [key])}, " + f"to {common.plain_name(longest)}, {trail_miles(longest, [key])}.") desc = _fit([first + gpx, first, f"{what[:1].upper() + what[1:]} in {name}, {country}.{gpx}"]) return title, desc, Markup(body), home.has_overview_map(recs) diff --git a/web/olt/summary.py b/web/olt/summary.py index 6ff9864..242f2da 100644 --- a/web/olt/summary.py +++ b/web/olt/summary.py @@ -56,15 +56,35 @@ def holder_counts(recs, records): return out -def facts(recs, records, by_authors=True): +def wholly_in(rec, keys): + """True when every state or province the record names is one of keys (olt/facets.py place keys). + A trail that names a place outside them only passes through, so its length and high point are + not the place's. The record names whole states, never where a trail enters one, so this is the + cautious reading.""" + return set(facets.place_keys(rec)) <= set(keys) + + +def facts(recs, records, by_authors=True, place=None): """The summary of a set of trails: one short paragraph (Markup). Empty for no trails. With - by_authors False (an author's own page) the routes-and-authors clause is left out.""" + by_authors False (an author's own page) the routes-and-authors clause is left out. + + place: (name, keys) on a page for a place, so no figure of a whole trail is given as the place's. + The length of a trail that also lies elsewhere is said to be its length "in all", and the highest + point is taken only from the trails wholly in the place (a high point on file has no location).""" if not recs: return Markup("") by_length = sorted(recs, key=lambda r: (r["length_km"], r["id"])) shortest, longest = by_length[0], by_length[-1] + name, keys = place if place else ("", ()) + inside = [r for r in recs if wholly_in(r, keys)] if place else recs + crossing = len(inside) < len(recs) sentences = [] - if len(recs) > 1: + if crossing and len(recs) > 1: + sentences.append(f"The longest trail that passes through {esc(name)} is {_name_link(longest)}, {_miles(longest)} in all, " + f"and the shortest {_name_link(shortest)}, {_miles(shortest)} in all.") + elif crossing: + sentences.append(f"{_name_link(longest)} passes through {esc(name)} and is {_miles(longest)} long in all.") + elif len(recs) > 1: sentences.append(f"The longest is {_name_link(longest)}, {_miles(longest)}, " f"and the shortest {_name_link(shortest)}, {_miles(shortest)}.") else: @@ -87,10 +107,11 @@ def facts(recs, records, by_authors=True): shown = _join( f'{_list_link(records, "terrain-" + t, words.TERRAIN[t].lower(), n)}' for t, n in terrain[:3]) sentences.append(f"The most common terrain is {shown}.") - high = [(hike.table(r).get("high_point_m"), r) for r in recs if isinstance(hike.table(r).get("high_point_m"), (int, float))] + high = [(hike.table(r).get("high_point_m"), r) for r in inside if isinstance(hike.table(r).get("high_point_m"), (int, float))] if high: m, top = max(high, key=lambda t: (t[0], t[1]["id"])) - sentences.append(f"The highest point on file is {words.elevation(m)}, on {_name_link(top)}.") + which = f"The highest point on file among the trails wholly in {esc(name)}" if crossing else "The highest point on file" + sentences.append(f"{which} is {words.elevation(m)}, on {_name_link(top)}.") return Markup(f"

{' '.join(sentences)}

") diff --git a/web/olt/trail.py b/web/olt/trail.py index f30f88d..76abb9a 100644 --- a/web/olt/trail.py +++ b/web/olt/trail.py @@ -199,6 +199,14 @@ GPX_CLAUSE = { } +def gpx_clause(rec): + """The clause of the "In brief" paragraph about the GPX; "" when the status has none.""" + status = facets.gpx(rec) + if status == "sold" and not common.sells_gpx(rec): + return "its author sells it as a guide, and this site has no GPX for it" + return GPX_CLAUSE.get(status, "") + + def _name_html(rec): """The name for the start of a sentence: "The Appalachian Trail", with no "The" before a name that has one or is not in English; marked with its language when it is not English.""" @@ -361,7 +369,7 @@ def brief_sentences(rec): f"and {esc(climb)}, {esc(how)}.")) # When to walk it and whether this site has a GPX: one sentence where the season is a plain range. - clause = GPX_CLAUSE.get(facets.gpx(rec)) or ("this site has no GPX for it" + (", so see the official site" if official_link(rec) else "")) + clause = gpx_clause(rec) or ("this site has no GPX for it" + (", so see the official site" if official_link(rec) else "")) season = season_sentence(rec) if season and not re.search(r"[,;]", season[1]): # "The usual season is May to July, and this page has a GPX of the track to download." @@ -447,7 +455,7 @@ def action_buttons(rec): if rec["derived"].get("downloads"): actions.append(f'{common.ICON_DOWNLOAD}Download the GPX') else: - actions.append(f'GPX: {esc(facets.GPX_STATUS[facets.gpx(rec)])}') + actions.append(f'GPX: {esc(facets.gpx_status_text(rec))}') official = official_link(rec) if official: actions.append(f'{esc(official[1])} {common.ICON_EXTERNAL}') @@ -601,11 +609,11 @@ def glance(rec, records=None): rows.append(glance_row(facets.WHERE, Markup(f'{region_names(rec)}, {esc(country)}'), wide=True)) status = facets.gpx(rec) if facets.gpx_here(rec): - text = facets.GPX_STATUS[status] + text = facets.gpx_status_text(rec) value = Markup(f'{esc(text)}') if rec["derived"].get("downloads") else text note = common.partial_short_text(rec) if common.line_differs(rec) else "" else: - value = Markup(f'{esc(facets.GPX_STATUS[status])}') + value = Markup(f'{esc(facets.gpx_status_text(rec))}') note = "" rows.append(glance_row(facets.GPX, value, note, wide=True)) halves = [i for i, r in enumerate(rows) if 'glance__wide' not in r.split(">", 1)[0]] @@ -730,28 +738,30 @@ def free_guides(rec): ROUTE_NO_GPX = { - # GPX status -> (heading, what this site does about it) + # GPX status -> (heading, what this site does about it); "" for nothing to add to the reason. "free": ("Get the GPX from its author", "A GPX is included here only where the author's terms allow passing it on, or where " "OpenStreetMap maps the route. Otherwise the author's own page is the place to get it."), - "sold": ("The author sells the route as a guide", - "No GPX is included here from any source, OpenStreetMap included, so the author's work is respected."), + "sold": ("The author sells the route as a guide", ""), "unpublished": ("The author does not publish a track", "No GPX is included here from any source, OpenStreetMap included, so the author's choice is respected."), "elsewhere": ("No GPX here", "No GPX is included here until it is clear that the author allows it."), } +# A route whose author sells a GPX (common.sells_gpx). +ROUTE_SOLD_GPX = ("The author sells a GPX", + "A GPX that is sold is not passed on here, and OpenStreetMap's version is not used in its place.") def _no_gpx_parts(rec): """(title, status, reason, rule, actions_html): why there is no GPX here and where to get one, for the empty frame and the sketch map alike.""" src = rec["source"] - reason = src.get("line_absent_reason", "") + reason = common.visitor_text(src.get("line_absent_reason", "")) actions = [] status = facets.gpx(rec) if common.is_route(rec): - title, rule = ROUTE_NO_GPX.get(status, ROUTE_NO_GPX["elsewhere"]) + title, rule = ROUTE_SOLD_GPX if status == "sold" and common.sells_gpx(rec) else ROUTE_NO_GPX.get(status, ROUTE_NO_GPX["elsewhere"]) if status == "free" and free_guides(rec): g = free_guides(rec)[0] actions.append(f'' @@ -763,7 +773,8 @@ def _no_gpx_parts(rec): else: title = "No GPX here" reason = common.absent_reason_short(rec) - rule = "A trail is listed without a GPX when no track for it may be passed on." + # "No track may be passed on" is for a trail whose track is held back, not one not added yet. + rule = "" if common.not_added_yet(rec) else "A trail is listed without a GPX when no track for it may be passed on." official = official_link(rec) if official: actions.append(f'' @@ -788,15 +799,16 @@ def _no_gpx_parts(rec): def empty_frame(rec): """The map frame of a trail with no GPX here and no known start or end point.""" title, status, reason, rule, actions_html = _no_gpx_parts(rec) + rule_html = f'

{esc(rule)}

' if rule else "" return f"""
-

GPX: {esc(facets.GPX_STATUS[status])}

+

GPX: {esc(facets.gpx_status_text(rec))}

{esc(title)}

{reason if isinstance(reason, Markup) else common.rich(reason)}

-

{esc(rule)}

+ {rule_html} {actions_html}
@@ -828,6 +840,7 @@ def sketch_figure(rec): caption = ("Only the start and the end are shown. There is no track for this trail here, " "and the site does not guess one.") title, status, reason, rule, actions_html = _no_gpx_parts(rec) + rule_html = f'

{esc(rule)}

' if rule else "" reason_html = reason if isinstance(reason, Markup) else common.rich(reason) frame_attr, drawing = sketch_of(box, sketch.trail_features(rec["id"]), route_main=route) rid = esc(rec["id"]) @@ -844,10 +857,10 @@ def sketch_figure(rec):
-

GPX: {esc(facets.GPX_STATUS[status])}

+

GPX: {esc(facets.gpx_status_text(rec))}

{esc(title)}

{reason_html}

-

{esc(rule)}

+ {rule_html} {actions_html}
@@ -1116,7 +1129,7 @@ def listing_note(rec): meaning = words.meaning(words.WAVES, wave) if note: return Markup(f"{esc(meaning)}. The record’s note: “{common.rich(note)}”") - return f"{meaning}. The record has no note saying what." + return meaning # no note: say no more than the status (tools/validate.py check_held_note catches the gap in the data) def abbreviation_fact(rec): diff --git a/web/tests/test_honest_pages.py b/web/tests/test_honest_pages.py new file mode 100644 index 0000000..01c4322 --- /dev/null +++ b/web/tests/test_honest_pages.py @@ -0,0 +1,137 @@ +"""Pages say only what is so: a place's figures are the place's, and a no-track notice says one thing. + + python3 -m unittest discover -s web/tests +""" +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) + +from olt import common, facets, hike, records, regions, summary, trail, words # noqa: E402 +from olt.markup import Markup # noqa: E402 + + +def text(html): + return re.sub(r"\s+", " ", re.sub(r"<[^>]+>", " ", str(html))).strip() + + +class PlaceFiguresTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.records = records.load_records(ROOT) + cls.by_slug, _ = regions.collect_regions(cls.records) + + def facts(self, slug): + info = self.by_slug[slug] + return text(summary.facts(info["records"], self.records, place=(info["name"], [info["key"]]))) + + def test_iowa_does_not_get_the_high_point_of_the_discovery_trail(self): + said = self.facts("us-ia") + self.assertNotIn("13,209", said) + self.assertEqual(said, "American Discovery Trail passes through Iowa and is 5,008 miles (8,060 km) long in all.") + self.assertIn("in all", said) + self.assertNotIn("highest point", said) + + def test_a_high_point_is_only_taken_from_trails_wholly_in_the_place(self): + checked = 0 + for slug, info in self.by_slug.items(): + keys = [info["key"]] + inside = [r for r in info["records"] if summary.wholly_in(r, keys)] + said = text(summary.facts(info["records"], self.records, place=(info["name"], keys))) + marks = [hike.table(r).get("high_point_m") for r in inside] + marks = [m for m in marks if isinstance(m, (int, float)) and not isinstance(m, bool)] + if marks: + self.assertIn(text(words.elevation(max(marks))), said, slug) + checked += 1 + else: + self.assertNotIn("highest point", said, slug) + if len(inside) < len(info["records"]): + self.assertNotIn("The longest is", said, slug) + self.assertIn("passes through", said, slug) + self.assertGreater(checked, 10) + + def test_a_place_wholly_holding_its_trail_keeps_the_plain_sentences(self): + rec = next(r for r in self.records if len(facets.place_keys(r)) == 1) + said = text(summary.facts([rec], self.records, place=("There", facets.place_keys(rec)))) + self.assertNotIn("passes through", said) + self.assertNotIn("in all", said) + self.assertIn(" long.", said) + + def test_a_description_marks_a_whole_trail_length_that_is_not_the_places(self): + adt = next(r for r in self.records if r["id"] == "american-discovery-trail") + self.assertTrue(regions.trail_miles(adt, ["US-IA"]).endswith("miles in all")) + own = next(r for r in self.records if len(facets.place_keys(r)) == 1) + self.assertTrue(regions.trail_miles(own, facets.place_keys(own)).endswith(" miles")) + + +class NoTrackNoticeTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.records = [r for r in records.load_records(ROOT) if not common.has_line(r)] + + def notice(self, rec): + title, status, reason, rule, actions = trail._no_gpx_parts(rec) + reason = reason if isinstance(reason, Markup) else common.rich(reason) + return text(f"GPX: {facets.gpx_status_text(rec)}. {title}. {reason} {rule}"), text(trail.brief(rec)) + + def test_none_contradicts_itself(self): + for rec in self.records: + notice, brief = self.notice(rec) + both = notice + " " + brief + self.assertFalse("may be passed on" in notice and re.search(r"added (here )?yet|not been added", notice), rec["id"]) + self.assertFalse("no track from its author was found" in notice and "sells a GPX" in both, rec["id"]) + self.assertFalse(re.search(r"Overpass|Nominatim|Held\.", both), rec["id"]) + if "sells a GPX" in both or "Sold by its author" in both: + self.assertTrue(common.sells_gpx(rec), rec["id"]) + + def test_not_added_yet_says_only_that(self): + found = [r for r in self.records if common.not_added_yet(r) and not common.is_route(r)] + self.assertTrue(found) + for rec in found: + notice, _ = self.notice(rec) + self.assertIn("added", notice) + self.assertNotIn("may be passed on", notice) + self.assertEqual(trail._no_gpx_parts(rec)[3], "") + + def test_a_route_sold_only_as_a_book_is_not_said_to_sell_a_gpx(self): + rec = next(r for r in self.records if r["id"] == "grand-teton-loop") + notice, brief = self.notice(rec) + self.assertNotIn("sells a GPX", brief) + self.assertIn("sells it as a guide", brief) + self.assertNotIn("Sold by its author", notice) + + def test_a_route_that_sells_a_gpx_says_so(self): + rec = next(r for r in self.records if r["id"] == "beartooth-high-route") + notice, brief = self.notice(rec) + self.assertIn("sells a GPX", brief) + self.assertIn("The author sells a GPX", notice) + + def test_search_services_are_not_named_to_visitors(self): + self.assertEqual(common.visitor_text("No track is included. A search on Overpass and Nominatim found none. Ask the holder."), + "No track is included. Ask the holder.") + rec = next(r for r in self.records if r["id"] == "bayou-state-trail") + notice, _ = self.notice(rec) + self.assertNotIn("Overpass", notice) + + +class HeldNoteTest(unittest.TestCase): + def test_a_held_record_without_a_note_prints_no_sentence_about_it(self): + said = text(trail.listing_note({"wave": "held"})) + self.assertNotIn("no note", said) + self.assertEqual(said, words.meaning(words.WAVES, "held")) + self.assertIn("because", text(trail.listing_note({"wave": "held", "wave_note": "because"}))) + + +class ListTileCountTest(unittest.TestCase): + def test_the_authors_tile_counts_authors_not_routes(self): + with open(os.path.join(WEB, "olt", "pages.py"), encoding="utf-8") as f: + src = f.read() + self.assertIn("count=len(author_groups)", src) + + +if __name__ == "__main__": + unittest.main() diff --git a/web/tests/test_views.py b/web/tests/test_views.py index dd05c46..1c8a2c3 100644 --- a/web/tests/test_views.py +++ b/web/tests/test_views.py @@ -634,7 +634,8 @@ class RealDataTest(unittest.TestCase): _, _, body, _ = regions.region_page(slug, self.records, SITE) self.assertIn('class="browse-about"', str(body)) if len(by_slug[slug]["records"]) > 1: - self.assertIn("The longest is", str(body)) + # "The longest is" where every trail is wholly in the place, else "passes through" (olt/summary.py) + self.assertTrue("The longest is" in str(body) or "The longest trail that passes through" in str(body)) if __name__ == "__main__":