Merge branch 'main' into fast-tests-2
This commit is contained in:
commit
69871fc764
128 files changed
+7921
-300
No files matched your search
+24
-23
@@ -1940,9 +1940,10 @@
|
||||
var OLD_POLICY = { open: 'free', sold: 'sold', withheld: 'unpublished', unclear: 'elsewhere' };
|
||||
|
||||
/* facet-counts:begin — pure, with no page: web/tests/test_filter_counts.py runs this under node.
|
||||
A row: {search: [name, author, places, summary], where: [], km, time, months: [], terrain: [], kind, walking, shape, gpx}.
|
||||
A state: {words: [], where, min, max (km; max may be Infinity), month, kind, and a list for
|
||||
each of time, terrain, walking, shape, gpx}. */
|
||||
A row: {search: [name, author, places, summary], where: [], km, time, months: [], estimate, terrain: [], kind, walking, shape, gpx}.
|
||||
A state: {words: [], where, min, max (km; max may be Infinity), month, stated, kind, and a list for
|
||||
each of time, terrain, walking, shape, gpx}. stated: with a month chosen, leave out the rows whose
|
||||
season is an estimate. */
|
||||
var FacetCount = (function () {
|
||||
var FACETS = ['where', 'length', 'time', 'month', 'terrain', 'kind', 'walking', 'shape', 'gpx'];
|
||||
function has(list, v) { return list.indexOf(v) !== -1; }
|
||||
@@ -1991,6 +1992,9 @@
|
||||
if (skip !== 'length' && (d.km < s.min || d.km > s.max)) return false;
|
||||
if (skip !== 'time' && s.time.length && !has(s.time, d.time)) return false;
|
||||
if (skip !== 'month' && s.month && !has(d.months, s.month)) return false;
|
||||
/* Leaving estimates out belongs to the month: it holds in counting each month too, so the
|
||||
number beside a month is what choosing it, with estimates left out, shows. */
|
||||
if (s.month && s.stated && d.estimate) return false;
|
||||
if (skip !== 'terrain' && s.terrain.length && !d.terrain.some(function (t) { return has(s.terrain, t); })) return false;
|
||||
if (skip !== 'kind' && s.kind && d.kind !== s.kind) return false;
|
||||
if (skip !== 'walking' && s.walking.length && !has(s.walking, d.walking)) return false;
|
||||
@@ -2052,15 +2056,14 @@
|
||||
var rows = Array.prototype.map.call(resultsRoot.querySelectorAll('.entry[data-id]'), function (li) {
|
||||
var d = li.dataset;
|
||||
return { li: li, id: d.id, search: FacetCount.textsOf(d.search), where: split(d.where), km: Number(d.km), time: d.time || '',
|
||||
months: split(d.months), terrain: split(d.terrain), kind: d.kind || '', walking: d.walking || '',
|
||||
months: split(d.months), estimate: d.estimate === 'yes', terrain: split(d.terrain), kind: d.kind || '', walking: d.walking || '',
|
||||
shape: d.shape || '', gpx: d.gpx || '' };
|
||||
});
|
||||
var lists = Array.prototype.slice.call(resultsRoot.querySelectorAll('ol.entries'));
|
||||
var count = resultsRoot.querySelector('.results-count');
|
||||
var noun = (count && count.dataset.noun) || 'trails';
|
||||
var empty = resultsRoot.querySelector('.empty-state');
|
||||
var unseasoned = resultsRoot.querySelector('[data-unseasoned]');
|
||||
var unseasonedText = resultsRoot.querySelector('[data-unseasoned-text]');
|
||||
var seasonAlways = resultsRoot.hasAttribute('data-season-shown');
|
||||
var active = form.querySelector('.filters__active');
|
||||
var lenHint = document.getElementById('len-hint');
|
||||
var listHead = resultsRoot.querySelector('.list-head');
|
||||
@@ -2160,6 +2163,7 @@
|
||||
maxRaw: maxRaw,
|
||||
swapped: swapped,
|
||||
month: value(el.month),
|
||||
stated: !!(el.stated && el.stated.checked && value(el.month)),
|
||||
kind: radio('kind')
|
||||
};
|
||||
MULTI.forEach(function (name) { s[name] = checked(name); });
|
||||
@@ -2287,6 +2291,7 @@
|
||||
if (s.min) p.set('min', s.minRaw);
|
||||
if (s.max !== Infinity) p.set('max', s.maxRaw);
|
||||
if (s.month) p.set('month', s.month);
|
||||
if (s.month && s.stated) p.set('stated', '1');
|
||||
if (s.kind) p.set('kind', s.kind);
|
||||
MULTI.forEach(function (name) { if (s[name].length) p.set(name, s[name].join(',')); });
|
||||
if (sort && sort.value !== defaultSort && sort.value !== 'nearest') p.set('sort', sort.value);
|
||||
@@ -2332,6 +2337,7 @@
|
||||
if (el.month) {
|
||||
var month = p.get('month') || '';
|
||||
el.month.value = hasOption(el.month, month) ? month : '';
|
||||
if (el.stated) el.stated.checked = !!el.month.value && p.get('stated') === '1';
|
||||
}
|
||||
var kind = p.get('kind') || '';
|
||||
if (kind === 'designated') kind = 'trail';
|
||||
@@ -2460,16 +2466,19 @@
|
||||
count.appendChild(document.createTextNode(' ' + words));
|
||||
}
|
||||
if (empty) empty.hidden = shown.length > 0;
|
||||
/* With a month chosen, say how many trails that pass everything else are left out for having no
|
||||
season on file, counted over the same rows as the list. */
|
||||
if (unseasoned && el.month) {
|
||||
var noSeason = 0;
|
||||
if (s.month) rows.forEach(function (d) { if (!d.months.length && FacetCount.passes(d, s, 'month')) noSeason++; });
|
||||
unseasoned.hidden = noSeason === 0;
|
||||
if (noSeason) {
|
||||
unseasonedText.textContent = noSeason + (noSeason === 1 ? ' trail with no season on file is not shown.'
|
||||
: ' trails with no season on file are not shown.');
|
||||
/* A month's rows show their season, and the way to leave estimated seasons out is offered once a
|
||||
month is chosen and some of the trails that pass everything else have an estimated season. */
|
||||
if (!seasonAlways) resultsRoot.toggleAttribute('data-season-shown', !!s.month);
|
||||
if (el.stated) {
|
||||
var open = false;
|
||||
if (s.month) {
|
||||
var withEstimates = Object.assign({}, s, { stated: false });
|
||||
open = rows.some(function (d) { return d.estimate && FacetCount.passes(d, withEstimates, ''); });
|
||||
}
|
||||
el.stated.disabled = !s.month;
|
||||
if (!s.month) el.stated.checked = false;
|
||||
var box = el.stated.closest('label');
|
||||
if (box) box.hidden = !open && !el.stated.checked;
|
||||
}
|
||||
if (listHead) listHead.hidden = shown.length === 0;
|
||||
relabel(s, c);
|
||||
@@ -2499,14 +2508,6 @@
|
||||
form.addEventListener('change', function () { apply(true); });
|
||||
form.addEventListener('submit', function (e) { e.preventDefault(); });
|
||||
form.addEventListener('reset', function () { setTimeout(function () { apply(true); }, 0); });
|
||||
resultsRoot.querySelectorAll('[data-unseasoned-show]').forEach(function (b) {
|
||||
/* Showing them is clearing the month; the rest of the filters stay. */
|
||||
b.addEventListener('click', function () {
|
||||
if (!el.month) return;
|
||||
el.month.value = '';
|
||||
el.month.dispatchEvent(new Event('change', { bubbles: true }));
|
||||
});
|
||||
});
|
||||
resultsRoot.querySelectorAll('[data-reset]').forEach(function (b) {
|
||||
b.addEventListener('click', function () { form.reset(); el.q.focus(); });
|
||||
});
|
||||
|
||||
@@ -1247,6 +1247,11 @@ html.js .filters__panels:not([data-open]) { display: none; }
|
||||
.results-note { margin-block: calc(-1 * var(--space-1)) var(--space-3); color: var(--ink-2); font: 400 var(--step--1)/1.4 var(--font-sans); }
|
||||
.results-note[hidden] { display: none; }
|
||||
.results-note__show { padding: 0; border: 0; background: none; color: var(--link); font: inherit; text-decoration: underline; cursor: pointer; }
|
||||
/* A row's season: shown on a month's list, and while a month is chosen (app.js). */
|
||||
.entry__season { display: none; }
|
||||
[data-season-shown] .entry__season { display: block; }
|
||||
.field__check { display: block; margin-block-start: var(--space-1); color: var(--ink-2); font: 400 var(--step--1)/1.4 var(--font-sans); }
|
||||
.field__check[hidden] { display: none; }
|
||||
.key {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
@@ -2293,6 +2298,12 @@ td .linklist a { font-weight: 400; }
|
||||
.lists-row li { flex: none; }
|
||||
.lists-row a { min-block-size: 2.75rem; }
|
||||
}
|
||||
/* The Places hub's jump row: one compact line at the very top, States and provinces and each kind of
|
||||
place with its number of pages; it wraps on a phone rather than scrolling. */
|
||||
.places-jump { margin-block-end: var(--space-1); }
|
||||
.places-jump ul { display: flex; flex-wrap: wrap; gap: 0 var(--space-4); padding: 0; list-style: none; font: 600 0.85rem/1.3 var(--font-sans); }
|
||||
.places-jump a { display: inline-flex; align-items: center; min-block-size: 2.25rem; color: var(--link); }
|
||||
.places-jump__n { margin-inline-start: 0.35em; color: var(--ink-2); font-weight: 400; font-variant-numeric: tabular-nums; }
|
||||
.section--finder { padding-block-start: var(--space-4); }
|
||||
.pills { display: flex; flex-wrap: wrap; gap: var(--space-2); }
|
||||
.pills .check { grid-template-columns: auto auto; padding: 0.15rem var(--space-2); border: 1px solid var(--rule-strong); border-radius: 999px; }
|
||||
|
||||
+1
-1
@@ -312,7 +312,7 @@ def author_page(g, records, site, all_pages):
|
||||
+ " · ".join(f'<a href="{esc(path(x))}">{esc(x["name"])}</a> ({len(x["routes"])})' for x in nav_items) + "</nav>") if nav_items else ""
|
||||
more = str(summary.facts(routes, records, by_authors=False)) if n >= 3 else ""
|
||||
briefs = "".join(f'<h3><a href="{esc(common.trail_path(r))}">{esc(common.plain_name(r))}</a></h3>\n{trail.brief(r)}\n' for r in routes)
|
||||
listing = home.results(groups=[(None, routes, regions.route_guides)], routes_list=True, top=2,
|
||||
listing = home.listing(groups=[(None, routes, regions.route_guides)], routes_list=True, top=2,
|
||||
by=lambda r: with_html(g, r, by_name))
|
||||
route_title = "About the route" if n == 1 else "About each route"
|
||||
bio = about_html(g)
|
||||
|
||||
+26
-10
@@ -55,6 +55,9 @@ class List:
|
||||
note: Optional[Callable] = None
|
||||
# A larger least size than MIN_SIZE, where the list is thin by nature (a month's list).
|
||||
min_size: int = 0
|
||||
# False for a list that is one of a fixed set, so none may go missing: a month's list, however
|
||||
# many of the trails are walked in it, is not "nearly everything" but one of twelve.
|
||||
capped: bool = True
|
||||
|
||||
def search_title(self, n):
|
||||
return (self.page_title or f"{self.title}: {{n}} Trails").format(n=n)
|
||||
@@ -79,7 +82,7 @@ GROUPS = (
|
||||
("walking", "By kind of walking", "Loops, high routes, walking with no trail, and trails not yet finished."),
|
||||
("terrain", "By terrain", "The main kinds of country a trail crosses."),
|
||||
("holder", "By who looks after it", "Trails whose designation names the holder."),
|
||||
("month", "By month", "Trails whose season on file includes the month. Only some trails have a season."),
|
||||
("month", "By month", "Trails normally hiked in the month. Estimated seasons are marked."),
|
||||
("where", "By country and GPX", "Where a trail is, and whether its page has a track to download."),
|
||||
)
|
||||
|
||||
@@ -116,17 +119,29 @@ def time_note(recs, records):
|
||||
def _month_list(m):
|
||||
name = facets.MONTHS[m - 1]
|
||||
return List(f"hike-in-{name.lower()}", f"Hiking in {name}",
|
||||
f"Trails whose season on file includes {name}.",
|
||||
f"Trails normally hiked in {name}. Estimated seasons are marked.",
|
||||
lambda r, m=m: m in facets.months(r),
|
||||
page_title=f"Long Trails to Hike in {name}: {{n}} Trails", group="month", note=month_note(name),
|
||||
min_size=MONTH_MIN)
|
||||
min_size=MONTH_MIN, capped=False)
|
||||
|
||||
|
||||
def month_note(name):
|
||||
def note(recs, records):
|
||||
have = sum(1 for r in records if facets.months(r))
|
||||
return (f"Only {have} of the {len(records)} trails have a season on file, so this page covers those "
|
||||
f"{have}. It is not every trail that can be walked in {name}.")
|
||||
unstated = [r for r in recs if facets.season_estimated(r)]
|
||||
est = len(unstated)
|
||||
stated = len(recs) - est
|
||||
if not est:
|
||||
return f"A source states the season for all {stated}."
|
||||
kinds = {facets.season_kind(r) for r in unstated}
|
||||
one = ("estimated from the climate and similar trails" if kinds == {"estimated"}
|
||||
else "set by judgement from pages that differ" if kinds == {"judged"} else "")
|
||||
if not stated:
|
||||
return (f"No source states the season for these, so each is {one}." if one
|
||||
else f"No source states the season for these: {facets.season_unstated_clause(unstated)}.")
|
||||
if one:
|
||||
return f"A source states the season for {stated} of these. For the other {est} it is {one}, and marked."
|
||||
return (f"A source states the season for {stated} of these. For the other {est}, "
|
||||
f"{facets.season_unstated_clause(unstated)}, and marked.")
|
||||
return note
|
||||
|
||||
|
||||
@@ -266,10 +281,11 @@ def members(lst, records):
|
||||
return facets.sort_records([r for r in records if lst.test(r)], lst.sort)
|
||||
|
||||
|
||||
def is_shown(n, total, least=0):
|
||||
def is_shown(n, total, least=0, capped=True):
|
||||
"""The threshold rule: a list is shown when it holds at least MIN_SIZE
|
||||
trails (or `least`, where the list asks for more) and no more than MAX_SHARE of all of them."""
|
||||
return n >= max(MIN_SIZE, least) and n <= MAX_SHARE * total
|
||||
trails (or `least`, where the list asks for more) and no more than MAX_SHARE of all of them,
|
||||
unless it is not capped (the twelve month lists)."""
|
||||
return n >= max(MIN_SIZE, least) and (not capped or n <= MAX_SHARE * total)
|
||||
|
||||
|
||||
_SHOWN_MEMO = None # while a site is being rendered: {id(records): (records, shown)}
|
||||
@@ -296,7 +312,7 @@ def shown(records):
|
||||
out = []
|
||||
for lst in LISTS:
|
||||
recs = members(lst, records)
|
||||
if is_shown(len(recs), len(records), lst.min_size):
|
||||
if is_shown(len(recs), len(records), lst.min_size, lst.capped):
|
||||
out.append((lst, recs))
|
||||
if _SHOWN_MEMO is not None:
|
||||
_SHOWN_MEMO[id(records)] = (records, out)
|
||||
|
||||
@@ -5,11 +5,13 @@
|
||||
[[list]] which lists the home page shows, and in what order (olt/home.py)
|
||||
authors.toml [[author]] route authors, and the words about the people among them (olt/authors.py)
|
||||
places.toml [[place]] the parks, mountain ranges and wilderness areas records name
|
||||
tools/season_blind_test.json how the judged seasons did against the seasons pages state (olt/reference.py)
|
||||
|
||||
Each is checked by tools/validate.py and described in docs/schema.md. Like left-out.toml, a file
|
||||
is looked for in the repository being built and then in this one, so a test repository without
|
||||
one still builds.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import tomllib
|
||||
|
||||
@@ -46,3 +48,14 @@ def places(repo_root):
|
||||
def lists(repo_root):
|
||||
"""The [[list]] entries of collections.toml: a list's key, and `home`, its place in the home page's row."""
|
||||
return load(repo_root, "collections.toml", "list")
|
||||
|
||||
|
||||
def blind_test(repo_root):
|
||||
"""The blind test of the judged seasons (tools/season_blind_test.json, written by
|
||||
tools/season_judge.py score), or None when there is none."""
|
||||
for base in (repo_root, REAL_ROOT):
|
||||
path = os.path.join(base or REAL_ROOT, "tools", "season_blind_test.json")
|
||||
if os.path.isfile(path):
|
||||
with open(path, encoding="utf-8") as f:
|
||||
return json.load(f)
|
||||
return None
|
||||
+106
-6
@@ -172,8 +172,15 @@ def months(rec):
|
||||
return sorted({x for x in (m or []) if isinstance(x, int) and 1 <= x <= 12})
|
||||
|
||||
|
||||
def season_text(rec):
|
||||
"""The phrase on the trail page: [hike].season, else built from the months."""
|
||||
def season_estimated(rec):
|
||||
"""True when no page states the season: it was estimated (season_basis "estimate"), or set by
|
||||
judgement from pages that differ (it carries a season_method). Such a season reads "About"."""
|
||||
h = hike.table(rec)
|
||||
return bool(h.get("season")) and (h.get("season_basis") == "estimate" or bool((h.get("season_method") or "").strip()))
|
||||
|
||||
|
||||
def season_phrase(rec):
|
||||
"""The phrase on the trail page as the record gives it: [hike].season, else built from the months."""
|
||||
phrase = (hike.table(rec).get("season") or "").strip()
|
||||
if phrase:
|
||||
return phrase[:1].upper() + phrase[1:]
|
||||
@@ -185,6 +192,97 @@ def season_text(rec):
|
||||
return words.join_names(MONTHS[m - 1] for m in ms)
|
||||
|
||||
|
||||
def season_text(rec):
|
||||
"""The season as a page shows it: the phrase, or "About ..." where it is estimated, so an
|
||||
estimate never reads as a stated fact ("About June to September", "About all year")."""
|
||||
phrase = season_phrase(rec)
|
||||
if not phrase or not season_estimated(rec):
|
||||
return phrase
|
||||
if phrase.lower().startswith("about"):
|
||||
return phrase
|
||||
if phrase.lower() == "all year":
|
||||
phrase = phrase.lower()
|
||||
return "About " + phrase
|
||||
|
||||
|
||||
def season_kind(rec):
|
||||
"""How the season is known: "stated" (a page states it), "judged" (set by judgement from pages
|
||||
that differ), "estimated" (no page states one), or "" when the trail has no season."""
|
||||
if not hike.table(rec).get("season"):
|
||||
return ""
|
||||
if not season_estimated(rec):
|
||||
return "stated"
|
||||
return "judged" if season_basis(rec) == "sources" else "estimated"
|
||||
|
||||
|
||||
SEASON_CONFIDENCE = re.compile(r"\s*Confidence: (high|medium|low)\.\s*$")
|
||||
JUDGED_LEAD = "Judged from the climate at the trail's elevation and from similar trails."
|
||||
|
||||
|
||||
def season_confidence(rec):
|
||||
""""high", "medium" or "low" from the end of the season's method; "" when it names none."""
|
||||
found = SEASON_CONFIDENCE.search(hike.table(rec).get("season_method") or "")
|
||||
return found.group(1) if found else ""
|
||||
|
||||
|
||||
def season_reason(rec):
|
||||
"""What the season's method says sets the season, without its standard first sentence and its
|
||||
closing confidence."""
|
||||
text = SEASON_CONFIDENCE.sub("", (hike.table(rec).get("season_method") or "").strip()).strip()
|
||||
if text.startswith(JUDGED_LEAD):
|
||||
text = text[len(JUDGED_LEAD):].strip()
|
||||
return text
|
||||
|
||||
|
||||
def season_pages_differ(rec):
|
||||
"""True for a season set by judgement from pages that state different seasons."""
|
||||
return season_estimated(rec) and season_basis(rec) == "sources"
|
||||
|
||||
|
||||
SEASON_USUAL = "This is the usual window, not a closure."
|
||||
|
||||
|
||||
def _plural(n, one, many):
|
||||
return f"{n} {one if n == 1 else many}"
|
||||
|
||||
|
||||
def season_unstated_clause(recs):
|
||||
"""What is true of the seasons among recs that no page states, kind by kind and counted exactly:
|
||||
"2 are estimated from the climate and similar trails and 1 is set by judgement from pages that
|
||||
differ"; "" when there are none."""
|
||||
kinds = [season_kind(r) for r in recs]
|
||||
est, judged = kinds.count("estimated"), kinds.count("judged")
|
||||
parts = []
|
||||
if est:
|
||||
parts.append(f"{est} {'is' if est == 1 else 'are'} estimated from the climate and similar trails")
|
||||
if judged:
|
||||
parts.append(f"{judged} {'is' if judged == 1 else 'are'} set by judgement from pages that differ")
|
||||
return " and ".join(parts)
|
||||
|
||||
|
||||
def season_note(rec):
|
||||
"""Says an estimated season is not a page's statement, how it was worked out, what sets it
|
||||
there and how far to trust it; "" when a page states the season."""
|
||||
if not season_estimated(rec):
|
||||
return ""
|
||||
reason = season_reason(rec)
|
||||
if season_pages_differ(rec):
|
||||
lead = "No one page states this season."
|
||||
elif "estimated from the climate" in reason:
|
||||
lead = "No page states a season." # the method says how it was estimated; not said twice
|
||||
else:
|
||||
lead = ("No page states a season. This is estimated from the climate at the trail's "
|
||||
"elevation and from similar trails.")
|
||||
parts = [lead]
|
||||
if reason:
|
||||
parts.append(reason)
|
||||
conf = season_confidence(rec)
|
||||
if conf:
|
||||
parts.append(f"Confidence: {conf}.")
|
||||
parts.append(SEASON_USUAL)
|
||||
return " ".join(parts)
|
||||
|
||||
|
||||
SEASON_BASIS_TEXT = {
|
||||
"primary": "The season comes from the page of the body that manages the trail or the trail's own association or, for a route, its author.",
|
||||
"sources": "Two or more pages from different publishers agree on the season.",
|
||||
@@ -203,10 +301,12 @@ def season_basis(rec):
|
||||
def season_basis_line(rec):
|
||||
"""One sentence for "About this data"; "" when the season has no recorded basis."""
|
||||
basis = season_basis(rec)
|
||||
if basis == "estimate":
|
||||
method = (hike.table(rec).get("season_method") or "").strip()
|
||||
return (method + " No page states a season.").strip()
|
||||
return SEASON_BASIS_TEXT.get(basis, "")
|
||||
if not season_estimated(rec):
|
||||
return SEASON_BASIS_TEXT.get(basis, "")
|
||||
method = (hike.table(rec).get("season_method") or "").strip()
|
||||
if season_pages_differ(rec):
|
||||
return (method + " It is a judgement, not any one page's statement.").strip()
|
||||
return (method + " No page states a season.").strip()
|
||||
|
||||
|
||||
# Terrain, Walking, Shape ----------------------------------------------------
|
||||
|
||||
+46
-27
@@ -193,6 +193,9 @@ def entry(rec, *, level=3, extra="", routes_list=False, hidden=False, eager=Fals
|
||||
if search:
|
||||
data["search"] = searchtext.attribute(rec)
|
||||
attrs = "".join(f' data-{k}="{esc(v)}"' for k, v in data.items())
|
||||
estimated = facets.season_estimated(rec)
|
||||
if estimated:
|
||||
attrs += ' data-estimate="yes"'
|
||||
if common.line_differs(rec):
|
||||
attrs += ' data-partial="yes"'
|
||||
h = f"h{level}"
|
||||
@@ -203,6 +206,9 @@ def entry(rec, *, level=3, extra="", routes_list=False, hidden=False, eager=Fals
|
||||
desc = entry_desc(rec)
|
||||
desc_html = f'\n <p class="entry__desc">{esc(desc)}</p>' if desc else ""
|
||||
time_html = esc(facets.time_text(rec)) + (' <small class="entry__est">estimate</small>' if est else "")
|
||||
season_html = (f'\n <div class="entry__season"><dt>{facets.SEASON}</dt><dd>{esc(facets.season_text(rec))}'
|
||||
+ ('<small class="entry__est">estimate</small>' if estimated else "") + "</dd></div>"
|
||||
if facets.months(rec) else "")
|
||||
climb_html = (f'\n <div class="entry__climb"><dt>Climb</dt><dd>{words.elevation(climb_m, "stack")}'
|
||||
f'<small class="entry__est">computed</small></dd></div>') if climb_m is not None else ""
|
||||
if hidden:
|
||||
@@ -227,23 +233,19 @@ def entry(rec, *, level=3, extra="", routes_list=False, hidden=False, eager=Fals
|
||||
<dl class="entry__facts">{lead_html}
|
||||
<div class="entry__length"><dt>Length</dt><dd>{words.length(rec["length_km"], "stack", rec["derived"]["length_mi"])}<span class="loglen" style="--km: {rec["length_km"]}" aria-hidden="true"></span></dd></div>
|
||||
<div class="entry__time"><dt>Time</dt><dd>{time_html}</dd></div>
|
||||
<div class="entry__line"><dt>GPX</dt><dd class="line line--{"yes" if facets.gpx_here(rec) else "no"}">{gpx_cell(rec)}</dd></div>{climb_html}{more_html}
|
||||
<div class="entry__line"><dt>GPX</dt><dd class="line line--{"yes" if facets.gpx_here(rec) else "no"}">{gpx_cell(rec)}</dd></div>{season_html}{climb_html}{more_html}
|
||||
</dl>{extra}
|
||||
</li>"""
|
||||
|
||||
|
||||
# The filters ------------------------------------------------------------------
|
||||
# One bar and one set of panels, on the home page and on every other page that shows a set of at
|
||||
# least FILTER_MIN trails (listing()), and on every park, range and wilderness page whatever its
|
||||
# size (the owner's rule: every set of trails gets the bar). Everything is built from the page's own trails: a facet that
|
||||
# One bar and one set of panels, on the home page and on every other page that shows a set of
|
||||
# trails (listing()), whatever its size (the owner's rule: every set of trails gets the bar). Everything is built from the page's own trails: a facet that
|
||||
# cannot narrow them is left out, and an option none of them has is not written. The numbers written
|
||||
# here are for the whole set; app.js counts again from the rows on the page every time anything
|
||||
# changes, and hides an option that would show nothing (its counting is facetCounts(), which
|
||||
# web/tests/test_filter_counts.py runs under node against counts made here from the records).
|
||||
|
||||
FILTER_MIN = 10
|
||||
|
||||
|
||||
def _length_options(steps, selected_any_last, unit="mi"):
|
||||
opts = [f'<option value="{step_value(n, unit)}">{step_label(n, unit)}</option>' for n in steps]
|
||||
if selected_any_last:
|
||||
@@ -334,7 +336,7 @@ def finder_form(records, c=None, steps=None, where="all", bare_if_empty=False):
|
||||
<label class="field__label" for="where">{facets.WHERE}</label>
|
||||
<select class="select" id="where" name="where">{opts}</select>
|
||||
</div>""")
|
||||
kms = [r["length_km"] for r in records]
|
||||
kms = [r["length_km"] for r in records] or [0]
|
||||
if any(min(kms) < n * words.KM_PER_MI <= max(kms) for n in steps):
|
||||
first.append(f"""<fieldset class="field" data-facet="length">
|
||||
<legend>{facets.LENGTH}</legend>
|
||||
@@ -355,10 +357,14 @@ def finder_form(records, c=None, steps=None, where="all", bare_if_empty=False):
|
||||
</fieldset>""")
|
||||
if facets.offered(records, "season") and _narrows(c, "month", range(1, 13)):
|
||||
month_opts = "".join(_opt(str(i), m, c[f"month:{i}"]) for i, m in enumerate(facets.MONTHS, 1) if c[f"month:{i}"])
|
||||
# A way to leave estimated seasons out, offered only where some of these trails have one.
|
||||
stated_box = ('\n <label class="field__check"><input type="checkbox" name="stated" value="1" disabled> '
|
||||
'Leave out estimated seasons</label>'
|
||||
if any(facets.season_estimated(r) for r in records) else "")
|
||||
first.append(f"""<div class="field" data-facet="month">
|
||||
<label class="field__label" for="month">{facets.SEASON}</label>
|
||||
<select class="select" id="month" name="month"><option value="">Any month</option>{month_opts}</select>
|
||||
<p class="field__hint">Trails usually walked in that month.</p>
|
||||
<p class="field__hint">Trails usually walked in that month. Estimated seasons are marked.</p>{stated_box}
|
||||
{_missing(records, "season")}
|
||||
</div>""")
|
||||
if _narrows(c, "kind", facets.KINDS):
|
||||
@@ -433,15 +439,13 @@ def finder_form(records, c=None, steps=None, where="all", bare_if_empty=False):
|
||||
</form>"""
|
||||
|
||||
|
||||
def listing(recs=None, *, where="all", groups=None, always=False, **kw):
|
||||
"""The rows of a page that shows a set of trails, with the filter bar over them when the set
|
||||
has at least FILTER_MIN trails (else results() alone); with always, whatever its size (the
|
||||
bar then holds only the filters that have something to offer). where: the Where filter's
|
||||
scope (finder_form). The other arguments are results()'s."""
|
||||
def listing(recs=None, *, where="all", groups=None, **kw):
|
||||
"""The rows of a page that shows a set of trails, with the filter bar over them whatever the size
|
||||
of the set (the bar holds only the filters that have something to offer, and the search box
|
||||
alone where nothing can narrow the set). where: the Where filter's scope (finder_form). The
|
||||
other arguments are results()'s."""
|
||||
trails = [r for g in groups for r in g[1]] if groups is not None else list(recs)
|
||||
if len(trails) < FILTER_MIN and not always:
|
||||
return results(recs, groups=groups, **kw)
|
||||
return Markup(f"""<div class="finder__bar">{finder_form(trails, where=where, bare_if_empty=always)}</div>
|
||||
return Markup(f"""<div class="finder__bar">{finder_form(trails, where=where, bare_if_empty=True)}</div>
|
||||
{results(recs, groups=groups, finder=True, **kw)}""")
|
||||
|
||||
|
||||
@@ -549,7 +553,7 @@ def key(official=True):
|
||||
|
||||
|
||||
def results(recs=None, *, finder=False, groups=None, routes_list=False, default_sort="name", saved=False, top=3,
|
||||
ranked="", lead=None, more=None, tools=True, by=None, every=False, wholly=None):
|
||||
ranked="", lead=None, more=None, tools=True, by=None, every=False, wholly=None, season=False):
|
||||
"""The list of trails, as every page shows it: div.results > head, key, list head, ol.entries.
|
||||
|
||||
Every list carries the same "Sort by" control. The rows are written in
|
||||
@@ -558,6 +562,7 @@ def results(recs=None, *, finder=False, groups=None, routes_list=False, default_
|
||||
|
||||
finder: a list driven by the filter bar over it (listing(): live count, empty state).
|
||||
every: the list holds every trail (the home page's).
|
||||
season: show each row's season (a month's list), as app.js does when a month is chosen.
|
||||
groups: [(heading, trails, extra_fn)] to list the trails under headings (level `top`);
|
||||
sorting is within each group and the groups keep their order. A heading may be a pair
|
||||
(heading HTML, intro HTML): the intro is a sentence under the heading (an author's summary).
|
||||
@@ -638,18 +643,14 @@ def results(recs=None, *, finder=False, groups=None, routes_list=False, default_
|
||||
tools = sort_select(default_sort, saved=saved, ranked=ranked, wholly=wholly)
|
||||
dflt = SAVED_ORDER[0] if saved else "rank" if ranked else HERE_ORDER if wholly else default_sort
|
||||
finder_attr = " data-finder" if finder else ""
|
||||
# Under the count, while a month is chosen: how many trails are left out for having no season on
|
||||
# file, and a way to see them (app.js fills it in from the rows, the same ones the list is).
|
||||
unseasoned = ('\n <p class="results-note" data-unseasoned hidden><span data-unseasoned-text></span> '
|
||||
'<button class="results-note__show" type="button" data-unseasoned-show>Show them</button></p>'
|
||||
if finder else "")
|
||||
return Markup(f"""<div class="results"{finder_attr} data-sortable data-default-sort="{esc(dflt)}">
|
||||
season_attr = " data-season-shown" if season else ""
|
||||
return Markup(f"""<div class="results"{finder_attr}{season_attr} data-sortable data-default-sort="{esc(dflt)}">
|
||||
<div class="results-head">
|
||||
{count}
|
||||
<div class="results-tools">
|
||||
{tools}
|
||||
</div>
|
||||
</div>{unseasoned}
|
||||
</div>
|
||||
{key(official=not only_routes)}
|
||||
{list_head(default_sort)}{lists}{empty}
|
||||
</div>""")
|
||||
@@ -866,8 +867,25 @@ def description(records):
|
||||
return common.cut_at_word(text, common.DESCRIPTION_LIMIT)
|
||||
|
||||
|
||||
def render(records, site, repo_root=""):
|
||||
"""The home page body (HTML). repo_root: where collections.toml names the lists the page shows."""
|
||||
# How the home page's line names each kind of place, and where on the Places hub it goes.
|
||||
PLACE_WAYS_IN = {"park": "park", "range": "mountain range", "wilderness": "wilderness area"}
|
||||
|
||||
|
||||
def places_line(place_kinds):
|
||||
"""The line below the rows that leads to the Places hub's sections: "Browse by park, by mountain
|
||||
range or by wilderness area." for the kinds that have pages (place_kinds: kind keys), else ""."""
|
||||
from . import places # imported here: places.py is the registry, and loads datafiles like this module
|
||||
links = [f'by <a href="/regions/#{places.KINDS[k].segment}">{PLACE_WAYS_IN[k]}</a>'
|
||||
for k in places.KINDS if k in place_kinds]
|
||||
if not links:
|
||||
return ""
|
||||
text = links[0] if len(links) == 1 else ", ".join(links[:-1]) + " or " + links[-1]
|
||||
return f'<p class="finder__foot finder__places">Browse {text}.</p>'
|
||||
|
||||
|
||||
def render(records, site, repo_root="", place_kinds=()):
|
||||
"""The home page body (HTML). repo_root: where collections.toml names the lists the page shows.
|
||||
place_kinds: the kinds of place (olt/places.py) that have pages; the page then ends with a line to them."""
|
||||
c = counts(records)
|
||||
recs = sorted(records, key=sort_name)
|
||||
total = c["total"]
|
||||
@@ -893,6 +911,7 @@ def render(records, site, repo_root=""):
|
||||
{browse_view(listing, overview_map(records, "Map of the trails the filters leave", scope="all"))}
|
||||
<div class="finder__notes">
|
||||
<p class="finder__foot">Not for navigation: tracks vary in quality and some trails are unfinished. Check each trail’s own maps before you go.</p>
|
||||
{places_line(place_kinds)}
|
||||
{contribute}
|
||||
</div>
|
||||
</div>"""
|
||||
+1
-1
@@ -130,7 +130,7 @@ def _render_site(records, out_dir, repo_root, site=None):
|
||||
image=card, image_alt=card_alt))
|
||||
dates[path] = seo.modified(rec)
|
||||
pages += 1
|
||||
body = home.render(records, site, repo_root)
|
||||
body = home.render(records, site, repo_root, place_kinds={i["kind"] for i in place_infos.values()})
|
||||
layout.write_page(out_dir, "/", layout.layout("", body, path="/", maps=True, site=site,
|
||||
description=home.description(records),
|
||||
jsonld=seo.home_jsonld(site)))
|
||||
|
||||
@@ -105,7 +105,7 @@ def page(p, records, site, all_pages):
|
||||
</div></header>
|
||||
</div></div>
|
||||
<div class="container section place">
|
||||
{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"])),
|
||||
{home.browse_view(home.listing(recs, default_sort=lst.sort, top=2, where="", season=lst.group == "month"), home.overview_map(recs, f"Map of the trails in {name}: {lst.title}", place=bounds.place_box(info["key"])),
|
||||
about=summary.facts(recs, records, place=(name, [info["key"]])), about_title=f"About these trails in {name}")}
|
||||
<nav class="region-nav" aria-label="Lists"><a href="{esc(browse.path(lst))}">{esc(lst.title)} everywhere</a> · <a href="/lists/">All lists</a></nav>
|
||||
{nav}
|
||||
|
||||
@@ -75,7 +75,7 @@ def _kind():
|
||||
kicker=_kicker, crumbs=_crumbs, lede=_lede, where="all", wholly=False,
|
||||
facts_place=lambda info: (_in_name(info), ()), title_options=_title_options,
|
||||
description=_description, box=lambda info: info.get("box"), nav=_nav,
|
||||
in_name=_in_name, phrase=_phrase, always_filters=True)
|
||||
in_name=_in_name, phrase=_phrase)
|
||||
|
||||
|
||||
PARK = _kind()
|
||||
|
||||
+33
-2
@@ -96,6 +96,33 @@ def verified(records):
|
||||
return out
|
||||
|
||||
|
||||
def _pct(share):
|
||||
return f"{share * 100:.0f} percent"
|
||||
|
||||
|
||||
def season_section(records, blind):
|
||||
"""The paragraphs and table saying where seasons come from, how many trails have each kind, and how
|
||||
the estimates did in the blind test (read from tools/season_blind_test.json, never typed)."""
|
||||
n = len(records)
|
||||
kinds = collections.Counter(facets.season_kind(r) for r in records)
|
||||
basis = collections.Counter(facets.season_basis(r) for r in records if facets.season_kind(r) == "stated")
|
||||
rows = [["The body that manages the trail, its association, or for a route its author", str(basis["primary"])],
|
||||
["Two or more pages from different publishers that agree", str(basis["sources"])],
|
||||
["One page", str(basis["source"])],
|
||||
["Pages that differ, so set by judgement from all of them", str(kinds["judged"])],
|
||||
["No page states one, so estimated from the climate and similar trails", str(kinds["estimated"])],
|
||||
["All trails", str(n)]]
|
||||
out = [f"""<p>Every trail has a season. Where a page states one, the season is that page’s. Where the pages that state one differ and none is the trail’s holder, its association or its route’s author, the season is set by judgement from all of them and the climate, and the page says so. Where no page states one, the season is estimated from the climate at the trail’s elevation and from similar trails: it reads “About” with a note, is marked in lists and is left out of the data search engines read. An estimated season is the usual window, not a closure, and an estimate is replaced when a page that states a season is found.</p>
|
||||
{pagekit.table(["Where a trail's season comes from", "Trails"], rows, caption="Where the seasons come from", numeric=(1,))}"""]
|
||||
if blind:
|
||||
by = blind["by_confidence"]
|
||||
conf = ", ".join(f"{name} {by[name]['matched']} of {by[name]['tested']} ({_pct(by[name]['share'])}) and "
|
||||
f"{by[name]['strict_matched']} ({_pct(by[name]['strict_share'])})"
|
||||
for name in ("high", "medium", "low") if by[name]["tested"])
|
||||
out.append(f"""<p>How the estimates were tested. On {esc(blind["date"])} the method was run blind on {blind["tested"]} trails whose seasons a page does state, with those seasons hidden. Two measures are given together. {blind["matched"]} of {blind["tested"]} ({_pct(blind["share"])}) had their first and last months within a month of the page’s; {blind["strict_matched"]} ({_pct(blind["strict_share"])}) also had no wrong gap in the middle, so the second measure counts a season with a gap that the page does not have, or without one that it has, as a miss. By the confidence it gave each estimate, first and last months and then also no wrong gap: {esc(conf)}. This measures how the method did where the answer is known, not a promise for any one trail.</p>""")
|
||||
return "\n ".join(out)
|
||||
|
||||
|
||||
def method_page(records, site, repo_root):
|
||||
"""(title, description, body) for /method/."""
|
||||
meaning = schema_meanings(repo_root)
|
||||
@@ -120,12 +147,15 @@ def method_page(records, site, repo_root):
|
||||
(a, b), (c, d_) = facets.PACE_KM, facets.PACE_KM_CROSS
|
||||
coverage = []
|
||||
for label, fn in (("A usual time stated by a source", lambda r: not facets.time_days(r)[2]),
|
||||
("A season", lambda r: bool(facets.months(r))), ("A high point", lambda r: bool(hike.table(r).get("high_point_m"))),
|
||||
("A season a page states", lambda r: facets.season_kind(r) == "stated"),
|
||||
("A season set from pages that differ", lambda r: facets.season_kind(r) == "judged"),
|
||||
("A season estimated from the climate and similar trails", lambda r: facets.season_kind(r) == "estimated"), ("A high point", lambda r: bool(hike.table(r).get("high_point_m"))),
|
||||
("Terrain", lambda r: bool(facets.terrain(r))), ("What the walking is", lambda r: bool(facets.walking(r))),
|
||||
("A computed climb that covers the whole trail", lambda r: facets.row_climb_m(r) is not None),
|
||||
("A track included here", common.has_line)):
|
||||
have = sum(1 for r in records if fn(r))
|
||||
coverage.append([label, str(have), str(n - have)])
|
||||
season_html = season_section(records, datafiles.blind_test(repo_root))
|
||||
rows = [[label, str(k), f"{k / len(ver) * 100:.0f}%" if ver else ""] for label, k in bands]
|
||||
body = (pagekit.head("How the figures are measured", (
|
||||
f"What each figure on this site means, and how far to trust it. {len(ver)} of the {n} trails have a track whose "
|
||||
@@ -145,7 +175,8 @@ def method_page(records, site, repo_root):
|
||||
<p>Climb is the total ascent along the track.{(" It uses " + esc(model) + ", sampled every " + words.fmt_int(spacing) + " metres, with " + esc(smoothing[:1].lower() + smoothing[1:]) + ".") if model and spacing else ""} {esc(limits_text)}</p>
|
||||
<p>A climb is ranked or shown in a list only where its track covers the whole trail: a track that covers part of the trail, or more than the trail, would mislead.</p>
|
||||
<h2>Season and high point</h2>
|
||||
<p>{esc(_sentence(meaning.get("season", "")))} {esc(_sentence(meaning.get("high_point_m", "").split(" May be given")[0]))} Not every record has them, so a page built from them says how many records it covers.</p>
|
||||
<p>{esc(_sentence(meaning.get("season", "")))} {esc(_sentence(meaning.get("high_point_m", "").split(" May be given")[0]))} </p>
|
||||
{season_html}
|
||||
<h2>What the records have</h2>
|
||||
{pagekit.table(["Figure", "Records with it", "Records without"], coverage, caption="How many records carry each figure", numeric=(1, 2))}
|
||||
<p>Every fact is read on a page that the record names. See the <a href="/sources/">sources</a>, the <a href="/data/schema/">record schema</a> and <a href="{GLOSSARY}">the glossary</a>.</p>
|
||||
|
||||
+12
-6
@@ -168,6 +168,7 @@ def regions_index_page(records, site, infos=()):
|
||||
place_infos = list(infos.values()) if isinstance(infos, dict) else list(infos or ())
|
||||
blocks = ""
|
||||
jump = []
|
||||
kinds = []
|
||||
for g, name, keys in facets.PLACE_GROUPS:
|
||||
infos = sorted((by_slug[k.lower()] for k in keys if k.lower() in by_slug), key=lambda i: i["name"])
|
||||
if not infos:
|
||||
@@ -200,7 +201,7 @@ def regions_index_page(records, site, infos=()):
|
||||
f'<li><a href="{esc(i["path"])}">{esc(i["name"])}</a>'
|
||||
f'<span class="places__n">{_plural(len(i["records"]))}</span></li>'
|
||||
for i in mine)
|
||||
jump.append(f'<li><a href="#{esc(kind.segment)}">{esc(kind.hub_title)}<span class="lists-row__n">{len(mine)}</span></a></li>')
|
||||
kinds.append(f'<li><a href="#{esc(kind.segment)}">{esc(kind.hub_title)} <span class="places-jump__n">{len(mine)}</span></a></li>')
|
||||
blocks += f"""<section class="places__group" aria-labelledby="{esc(kind.segment)}">
|
||||
<h2 id="{esc(kind.segment)}">{esc(kind.hub_title)}</h2>
|
||||
<ul class="places__list">{rows}</ul>
|
||||
@@ -214,12 +215,18 @@ def regions_index_page(records, site, infos=()):
|
||||
foot = f'\n<div class="container"><p class="places__sum">Places with no listed trail: {links}.</p></div>'
|
||||
n_us = sum(1 for r in records if "US" in common.countries(r))
|
||||
n_ca = sum(1 for r in records if "CA" in common.countries(r))
|
||||
body = f"""<div class="page-head"><div class="container"><header class="titleblock">
|
||||
# One compact row at the very top, whatever the screen: the states and provinces and each kind of
|
||||
# place that has pages, each with its exact number of pages.
|
||||
row = (f'<nav class="places-jump" aria-label="Jump to a kind of place"><ul>'
|
||||
f'<li><a href="#states-and-provinces">States and provinces <span class="places-jump__n">{len(by_slug)}</span></a></li>'
|
||||
f'{"".join(kinds)}</ul></nav>') if kinds else ""
|
||||
body = f"""<div class="page-head"><div class="container">{row}<header class="titleblock">
|
||||
<div class="titleblock__text"><h1>Places</h1>
|
||||
<p class="page-head__lede">The {len(records)} trails by state and province, grouped into parts of the
|
||||
United States ({n_us}) and Canada ({n_ca}). A trail that crosses several states is on each one’s page.{lede_more}</p>
|
||||
</div></header>
|
||||
<nav class="lists-row" aria-label="Jump to a part of the country{" or a kind of place" if place_infos else ""}"><ul>{"".join(jump)}</ul></nav></div></div>
|
||||
<nav class="lists-row" aria-label="Jump to a part of the country"><ul>{"".join(jump)}</ul></nav></div></div>
|
||||
<span id="states-and-provinces"></span>
|
||||
<div class="container section places">{blocks}</div>{foot}"""
|
||||
description = (f"Where the {len(records)} long trails and routes are: {n_us} in the United States and {n_ca} in Canada, "
|
||||
f"by state and province, with the number in each.")
|
||||
@@ -309,7 +316,6 @@ class PageKind:
|
||||
nav: object
|
||||
in_name: object = None
|
||||
phrase: object = None
|
||||
always_filters: bool = False # the filter bar whatever the number of trails
|
||||
|
||||
|
||||
def _state_kicker(info):
|
||||
@@ -433,7 +439,7 @@ def place_page(info, records, site, kind, *, facet_pages=(), place_links=""):
|
||||
</div></header>
|
||||
</div></div>
|
||||
<div class="container section place">
|
||||
{home.browse_view(home.listing(recs, top=2, where=kind.where, wholly=wholly, always=kind.always_filters), home.overview_map(recs, f"Map of the trails {phrase}", place=kind.box(info)),
|
||||
{home.browse_view(home.listing(recs, top=2, where=kind.where, wholly=wholly), home.overview_map(recs, f"Map of the trails {phrase}", place=kind.box(info)),
|
||||
about=f"{summary.facts(recs, records, place=place)}{summary.details(recs)}",
|
||||
about_title=f"About the trails {phrase}")}
|
||||
{nav}{place_links}
|
||||
@@ -526,7 +532,7 @@ def list_page(lst, recs, total, site, *, records=None, before="", after="", lead
|
||||
</div></header>
|
||||
</div></div>
|
||||
<div class="container section place">
|
||||
{home.browse_view(home.listing(recs, default_sort=lst.sort, top=2, lead=lead),
|
||||
{home.browse_view(home.listing(recs, default_sort=lst.sort, top=2, lead=lead, season=lst.group == "month"),
|
||||
home.overview_map(recs, f"Map of the trails in the list {lst.title}"),
|
||||
about=f"{about}{before}{f'<p>{esc(note.strip())}</p>' if note else ''}<p class=\"finder__foot\">{rule}</p>",
|
||||
about_title="About this list")}
|
||||
|
||||
+2
-1
@@ -290,7 +290,8 @@ def _properties(rec):
|
||||
props.append(_pv("Shape", facets.SHAPES[shape]))
|
||||
props.append(_pv("Start", h.get("start", "")) if h.get("start") else None)
|
||||
props.append(_pv("End", h.get("end", "")) if h.get("end") else None)
|
||||
props.append(_pv("Usual season", h["season"]) if h.get("season") else None)
|
||||
# Only a season a page states: an estimate is not a fact about the trail to hand to a search engine.
|
||||
props.append(_pv("Usual season", h["season"]) if h.get("season") and not facets.season_estimated(rec) else None)
|
||||
if common.is_route(rec):
|
||||
route = rec.get("route", {})
|
||||
props.append(_pv("Route author", route["creator"]) if route.get("creator") else None)
|
||||
|
||||
+4
-1
@@ -45,14 +45,17 @@ def time_cell(rec):
|
||||
|
||||
|
||||
def season_cell(rec):
|
||||
return facets.season_text(rec) or "Not on file"
|
||||
return facets.season_text(rec)
|
||||
|
||||
|
||||
def figures_note(recs):
|
||||
"""What the times and climbs of these trails mean, with the caveats the records state."""
|
||||
est = sum(1 for r in recs if facets.time_days(r)[2])
|
||||
unstated = [r for r in recs if facets.season_estimated(r)]
|
||||
parts = [f"Times that start with “About” are estimated from the length ({est} of these). "
|
||||
"Otherwise a source states the time.",
|
||||
(f"Seasons that start with “About” are not stated by a page ({len(unstated)} of these): "
|
||||
f"{facets.season_unstated_clause(unstated)}." if unstated else ""),
|
||||
climb_caveat(recs)]
|
||||
return " ".join(p for p in parts if p)
|
||||
|
||||
|
||||
+3
-1
@@ -148,7 +148,9 @@ def detail(rec):
|
||||
out.append(f"Its high point is {esc(name + ', ') if name else ''}{words.elevation(m)}.")
|
||||
season = facets.season_text(rec)
|
||||
if season:
|
||||
out.append(f"Season: {esc(season)}.")
|
||||
how = (", judged from pages that differ" if facets.season_pages_differ(rec)
|
||||
else ", estimated from the climate and similar trails" if facets.season_estimated(rec) else "")
|
||||
out.append(f"Season: {esc(season)}{how}.")
|
||||
rest = _rest_of_summary(rec)
|
||||
if rest:
|
||||
out.append(f'<span class="record-text">{esc(rest)}</span>')
|
||||
|
||||
+18
-6
@@ -303,6 +303,7 @@ def _name_html(rec):
|
||||
|
||||
|
||||
MAX_BRIEF = 4 # sentences in the "In brief" paragraph
|
||||
PINNED = -1 # the priority of a sentence that is kept besides those (an estimated season)
|
||||
MONTH_WORDS = ("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December")
|
||||
SEASON_WORDS = ("spring", "summer", "fall", "autumn", "winter", "late", "early", "mid", "from", "about")
|
||||
SENTENCE_VERBS = re.compile(r"\b(is|are|can|start|starts|hikes?|hiked|travelled|traveled|bring|brings|closed|best)\b", re.I)
|
||||
@@ -313,6 +314,13 @@ def season_sentence(rec):
|
||||
seasons, ("sentence", "Northbound hikes start late February to early April") for one the record
|
||||
already words as a sentence, or None when the record has none or it is too long to say briefly.
|
||||
The caller adds the full stop. Only the record's own words are used."""
|
||||
if facets.season_estimated(rec):
|
||||
# Never worded as a fact, and never joined to the GPX clause with "and".
|
||||
phrase = facets.season_phrase(rec).rstrip(". ")
|
||||
phrase = phrase.lower() if phrase.lower() == "all year" else phrase
|
||||
if facets.season_pages_differ(rec):
|
||||
return ("estimate", f"The pages differ on the season; it is judged to be about {phrase}")
|
||||
return ("estimate", f"No source gives a season; the climate suggests about {phrase}")
|
||||
text = facets.season_text(rec).strip().rstrip(". ")
|
||||
if not text:
|
||||
return None
|
||||
@@ -452,19 +460,23 @@ def brief_sentences(rec):
|
||||
# When to walk it and whether this site has a GPX: one sentence where the season is a plain range.
|
||||
clause = gpx_clause(rec) or ("this site has no GPX for it" + _see_clause(rec))
|
||||
season = season_sentence(rec)
|
||||
if season and not re.search(r"[,;]", season[1]):
|
||||
if season and season[0] != "estimate" 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."
|
||||
items.append((3, 5, f"{esc(season[1])}, and {esc(clause)}."))
|
||||
else:
|
||||
if season:
|
||||
items.append((3.5, 5, esc(season[1]) + "."))
|
||||
# An estimated season is always said, so it is never left for a reader to take as a fact
|
||||
# by omission: it is the one sentence that may stand beyond MAX_BRIEF.
|
||||
items.append((PINNED if season[0] == "estimate" else 3.5, 5, esc(season[1]) + "."))
|
||||
items.append((3, 6, esc(clause[:1].upper() + clause[1:]) + "."))
|
||||
permit = permit_sentence(rec)
|
||||
if permit:
|
||||
items.append((6, 7, esc(permit)))
|
||||
|
||||
# At most MAX_BRIEF sentences: the lowest priorities are kept, shown in reading order.
|
||||
kept = sorted(sorted(items, key=lambda i: (i[0], i[1]))[:MAX_BRIEF], key=lambda i: i[1])
|
||||
pinned = [i for i in items if i[0] == PINNED]
|
||||
rest = sorted((i for i in items if i[0] != PINNED), key=lambda i: (i[0], i[1]))[:MAX_BRIEF]
|
||||
kept = sorted(rest + pinned, key=lambda i: i[1])
|
||||
return [text for _, _, text in kept]
|
||||
|
||||
|
||||
@@ -646,7 +658,7 @@ def glance(rec, records=None, place_infos=()):
|
||||
rows.append(glance_row(facets.TIME, facets.time_text(rec), time_note(rec, records)))
|
||||
season = facets.season_text(rec)
|
||||
if season:
|
||||
rows.append(glance_row(facets.SEASON, season))
|
||||
rows.append(glance_row(facets.SEASON, season, facets.season_note(rec)))
|
||||
if facets.walking(rec):
|
||||
walking = facets.WALKING_VALUES[facets.walking(rec)]
|
||||
if facets.walking(rec) in facets.CROSS_COUNTRY:
|
||||
@@ -718,7 +730,7 @@ def glance(rec, records=None, place_infos=()):
|
||||
unfinished = ""
|
||||
if h.get("unfinished"):
|
||||
unfinished = f'<p class="glance__warn"><strong>Not finished.</strong> {common.rich(common.sentence(h["unfinished"]))}</p>'
|
||||
missing = [name for name, have in ((facets.SEASON, season), (facets.TERRAIN, terrain),
|
||||
missing = [name for name, have in ((facets.TERRAIN, terrain),
|
||||
(facets.WALKING, facets.walking(rec)),
|
||||
(PERMITS, h.get("permit"))) if not have]
|
||||
pending = ""
|
||||
@@ -1581,7 +1593,7 @@ def hike_sources_block(rec):
|
||||
for src in hike.sources(rec):
|
||||
url = src.get("url", "")
|
||||
who = src.get("publisher") or (host(url) if url else "Source")
|
||||
facts_ = [words.HIKE_FACTS.get(f, f) for f in src.get("facts", [])]
|
||||
facts_ = list(dict.fromkeys(words.HIKE_FACTS.get(f, f) for f in src.get("facts", []))) # season and months read alike
|
||||
what = ("For " + words.join_names(facts_)) if facts_ else ""
|
||||
link = ext_link(url, who) if url else esc(who)
|
||||
detail = " · ".join(x for x in (host(url) if url else "", what) if x)
|
||||
|
||||
@@ -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
@@ -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)
|
||||
|
||||
@@ -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
@@ -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)
|
||||
|
||||
@@ -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))
|
||||
|
||||
@@ -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
@@ -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
@@ -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:
|
||||
|
||||
Reference in new issue
Block a user