Search reads more than the name: summary, places, author and land unit, strongest matches first

Each row's search words come in four tiers (name and abbreviation, author, the full names of
the states, provinces and countries plus where it starts and ends and the land unit or body its
record names, and the summary). Typed words match at the start of words in any order, without
regard to case, accents or apostrophes, and the strongest matches come first. A row that matched
only beyond its name says where in one quiet line.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-19 14:04:13 -07:00
1 parent ffc342b590
commit 3ff2281129
6 files changed
+453 -15

No files matched your search

+73 -5
View File
@@ -1505,6 +1505,11 @@
function compareEntries(a, b, key) {
key = normalizeSortKey(key, 'name');
var an = a.dataset.name || '', bn = b.dataset.name || '';
/* While words are typed in the search box, the strongest matches come first (data-match, set by
the filter bar: 0 name, 1 author, 2 places, 3 summary); within each, the order chosen. */
if (a.dataset.match !== b.dataset.match && a.dataset.match !== undefined && b.dataset.match !== undefined) {
return cmpNum(Number(a.dataset.match), Number(b.dataset.match));
}
if (key === 'saved') {
var ao = a.dataset.order ? Number(a.dataset.order) : Infinity;
var bo = b.dataset.order ? Number(b.dataset.order) : Infinity;
@@ -1633,17 +1638,53 @@
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, where: [], km, time, months: [], terrain: [], kind, walking, shape, gpx}.
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}. */
var FacetCount = (function () {
var FACETS = ['where', 'length', 'time', 'month', 'terrain', 'kind', 'walking', 'shape', 'gpx'];
function has(list, v) { return list.indexOf(v) !== -1; }
/* The search. A row's search is four texts, strongest first: [name, author, places, summary],
each its words with a space before and after (olt/searchtext.py writes them; fold() here is
its fold(): lower case, no accents, apostrophes dropped, anything else that is not a letter
or a digit a space). A typed word matches at the start of a word of a text; the summary is
looked in only for a typed word of three letters or more. */
var SUMMARY = 3, SUMMARY_MIN = 3, NOT_FOUND = 9;
function fold(text) {
return String(text || '').normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase()
.replace(/[’‘'`´]/g, '').replace(/[^\p{L}\p{N}]+/gu, ' ').trim();
}
function wordsOf(text) { return fold(text).split(' ').filter(Boolean); }
function textsOf(attr) {
var texts = String(attr || '').split('|').map(function (t) { return ' ' + t + ' '; });
while (texts.length < 4) texts.push(' ');
return texts;
}
/* The strongest text a typed word is found in (0 name ... 3 summary), or -1. */
function tierOf(texts, w) {
for (var t = 0; t < texts.length; t++) {
if (t === SUMMARY && w.length < SUMMARY_MIN) break;
if (texts[t].indexOf(' ' + w) !== -1) return t;
}
return -1;
}
/* How well a row matches the typed words: the weakest text any of them needs (0 name, 1 author,
2 places, 3 summary), NOT_FOUND when a word is in none, 0 when nothing is typed. */
function match(texts, typed) {
var worst = 0;
for (var i = 0; i < typed.length; i++) {
var t = tierOf(texts, typed[i]);
if (t === -1) return NOT_FOUND;
if (t > worst) worst = t;
}
return worst;
}
/* Does the row pass the search and every filter but `skip`? Within Time, Terrain, Walking,
Shape and GPX the choices are alternatives: a row with any one of them passes. */
function passes(d, s, skip) {
if (s.words.some(function (w) { return d.search.indexOf(w) === -1; })) return false;
if (match(d.search, s.words) === NOT_FOUND) return false;
if (skip !== 'where' && s.where && !has(d.where, s.where)) return false;
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;
@@ -1697,7 +1738,8 @@
return (shown === total ? '' : 'of ' + total + ' ') + noun;
}
return { passes: passes, count: count, countWords: countWords };
return { passes: passes, count: count, countWords: countWords, fold: fold, wordsOf: wordsOf, textsOf: textsOf, match: match,
NOT_FOUND: NOT_FOUND };
})();
/* facet-counts:end */
@@ -1707,7 +1749,7 @@
function split(v) { return (v || '').split(' ').filter(Boolean); }
var rows = Array.prototype.map.call(resultsRoot.querySelectorAll('.entry[data-id]'), function (li) {
var d = li.dataset;
return { li: li, id: d.id, search: d.search || '', where: split(d.where), km: Number(d.km), time: d.time || '',
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 || '',
shape: d.shape || '', gpx: d.gpx || '' };
});
@@ -1808,7 +1850,7 @@
var q = value(el.q).trim();
var s = {
q: q,
words: q.toLowerCase().split(/\s+/).filter(Boolean),
words: FacetCount.wordsOf(q),
where: value(el.where),
min: min,
max: max,
@@ -2064,8 +2106,34 @@
if (none) none.hidden = shown > 0;
}
/* With words typed, every row is marked with how well it matches them (data-match: 0 name,
1 author, 2 places, 3 summary, 9 not at all), for the list to put the strongest first, and a
row that matched only beyond its name says where, in one quiet line. */
var MATCH_SAYS = ['', 'author', 'place names', 'summary'];
function markMatches(typed) {
rows.forEach(function (d) {
var m = typed.length ? FacetCount.match(d.search, typed) : -1;
if (m === -1) delete d.li.dataset.match; else d.li.dataset.match = String(m);
var says = m > 0 && m < FacetCount.NOT_FOUND ? 'Matches: ' + MATCH_SAYS[m] : '';
if (says && !d.note) {
var body = d.li.querySelector('.entry__body');
if (body) {
d.note = document.createElement('p');
d.note.className = 'entry__small entry__match';
body.appendChild(d.note);
}
}
if (d.note) {
d.note.hidden = !says;
setText(d.note, says);
}
});
}
function apply(updateUrl) {
var s = read();
markMatches(s.words);
applySort();
var c = FacetCount.count(rows, s, lengthSteps());
var shown = [];
rows.forEach(function (d) {
+8 -6
View File
@@ -7,7 +7,7 @@ attributes in olt/facets.py, under the same names the trail pages use.
import collections
import math
from . import browse, common, datafiles, facets, hike, sketch, words
from . import browse, common, datafiles, facets, hike, searchtext, sketch, words
from .markup import Markup, esc
# Length range choices for the filters, round in the unit they are written in.
@@ -151,7 +151,7 @@ def route_by_html(rec):
return Markup(text)
def entry(rec, *, level=3, extra="", routes_list=False, hidden=False, eager=False, lead=None, rank=None, more=(), by=None, here=None):
def entry(rec, *, level=3, extra="", routes_list=False, hidden=False, eager=False, lead=None, rank=None, more=(), by=None, here=None, search=True):
"""One trail in a list. Its data-* attributes drive the filters in app.js.
level: the heading level of the trail's name. extra: HTML placed last in the row.
@@ -167,6 +167,8 @@ def entry(rec, *, level=3, extra="", routes_list=False, hidden=False, eager=Fals
names only the others a route is credited to); "" for none.
here: 0 for a trail wholly in the place a place page is about, 1 for one that lies elsewhere too
(data-here, the order that page opens in; see results()).
search: write the row's words for the search box (data-search, olt/searchtext.py); results() leaves
them out of a list with no search box over it.
The Save star follows the name in the markup (so it is the next stop for the
keyboard) but is drawn under the logo, out of the row's flow (style.css
@@ -174,8 +176,6 @@ def entry(rec, *, level=3, extra="", routes_list=False, hidden=False, eager=Fals
"""
route = facets.kind(rec) == "route"
lo, hi, est = facets.time_days(rec)
search = " ".join([rec["name"], rec.get("common_name", ""), rec.get("short_name", ""), rec["id"],
facets.author(rec)]).lower()
abbr = rec.get("short_name", "")
abbr_cls = "entry__abbr" if common.shield_url(rec) else "entry__abbr vh"
abbr_html = f' <span class="{abbr_cls}">{esc(abbr)}</span>' if abbr else ""
@@ -188,8 +188,10 @@ def entry(rec, *, level=3, extra="", routes_list=False, hidden=False, eager=Fals
"climb": climb_m if climb_m is not None else "",
"days": hi, "time": facets.time_band(rec), "months": " ".join(map(str, facets.months(rec))),
"terrain": " ".join(facets.terrain(rec)), "kind": facets.kind(rec), "walking": facets.walking(rec),
"shape": facets.shape(rec), "gpx": facets.gpx(rec), "name": sort_name(rec), "search": search.strip(),
"shape": facets.shape(rec), "gpx": facets.gpx(rec), "name": sort_name(rec),
}
if search:
data["search"] = searchtext.attribute(rec)
attrs = "".join(f' data-{k}="{esc(v)}"' for k, v in data.items())
if common.line_differs(rec):
attrs += ' data-partial="yes"'
@@ -588,7 +590,7 @@ def results(recs=None, *, finder=False, groups=None, routes_list=False, default_
eager=not saved and seen + i < EAGER_ROWS,
lead=lead(r) if lead else None, more=more(r) if more else (),
rank=seen + i + 1 if ranked else None, by=by,
here=(0 if wholly(r) else 1) if wholly else None) for i, r in enumerate(items))
here=(0 if wholly(r) else 1) if wholly else None, search=finder) for i, r in enumerate(items))
seen += len(items)
if isinstance(heading, tuple):
heading, intro = heading
+81
View File
@@ -0,0 +1,81 @@
"""The words a search box looks in (data-search on each row of a list; app.js matches against them).
A row's words come in four tiers, strongest first, so that the list can put the best matches first:
0 name the name, its common name, its abbreviation and its id
1 author who made a route
2 places the full names of the states and provinces it lies in, the countries, the place it
starts and the place it ends, and the land unit or managing body its record names
3 summary the trail's summary
Each tier is folded (fold) and written once per word (the summary's words of fewer than three letters are
left out): a word that a stronger tier has is left out of the
weaker ones, since a search asks for the strongest tier a word is found in. The tiers are joined with "|".
app.js folds what is typed the same way (its fold(), checked against this one by web/tests/test_search.py)
and finds each typed word at the start of a word of the row.
"""
import re
import unicodedata
from . import common, facets, hike, words
TIERS = 4
SUMMARY = 3 # the summary tier
SUMMARY_MIN = 3 # it holds words of this many letters or more, and a typed word is looked for there only if it has as many
# A designation that only says who made the route, and that no agency holds it: the author is in
# the author tier already, and "no agency or association" would match every route.
_NO_BODY = re.compile(r"^(person-defined route|guidebook route)\b", re.I)
_APOSTROPHES = re.compile("[’‘'`´]")
_NOT_WORD = re.compile(r"[\W_]+")
def fold(text):
"""Lower-case, without accents, apostrophes dropped ("Road's End" -> "roads end"), every other run of
anything that is not a letter or a digit a single space."""
text = unicodedata.normalize("NFD", str(text or ""))
text = "".join(c for c in text if not unicodedata.combining(c)).lower()
return _NOT_WORD.sub(" ", _APOSTROPHES.sub("", text)).strip()
def place_names(rec):
"""The names of the places a record carries: states, provinces and countries in full, where it
starts and ends, and the land unit or body of its designation."""
names = [facets.place_name(k) for k in facets.place_keys(rec)]
names += [words.COUNTRIES.get(c, c) for c in common.countries(rec)]
h = hike.table(rec)
names += [h.get("start", ""), h.get("end", "")]
designation = rec.get("designation", "")
if designation and not _NO_BODY.match(designation):
names.append(designation)
return [n for n in names if isinstance(n, str) and n.strip()]
def tier_texts(rec):
"""The four texts of a record, unfolded."""
return [
" ".join([rec["name"], rec.get("common_name", ""), rec.get("short_name", ""), rec["id"]]),
facets.author(rec),
" ".join(place_names(rec)),
hike.table(rec).get("summary", ""),
]
def tiers(rec):
"""The four tiers as lists of words, each word in the strongest tier that has it."""
seen = set()
out = []
for i, text in enumerate(tier_texts(rec)):
mine = []
for word in fold(text).split():
if i == SUMMARY and len(word) < SUMMARY_MIN:
continue
if word not in seen:
seen.add(word)
mine.append(word)
out.append(mine)
return out
def attribute(rec):
"""The value of a row's data-search: the tiers' words, tiers joined with "|"."""
return "|".join(" ".join(t) for t in tiers(rec))
+4 -3
View File
@@ -234,7 +234,7 @@ def rows_of(body):
for attrs in re.findall(r'<li class="entry"([^>]*)>', str(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": d["search"], "where": split(d["where"]), "km": float(d["km"]),
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"]),
"kind": d["kind"], "walking": d["walking"], "shape": d["shape"], "gpx": d["gpx"]})
return out
@@ -306,9 +306,10 @@ class CountsAreTrueTest(unittest.TestCase):
def test_search_counts_too(self):
c = run_counts(self.rows, state(words=["trail"], kind="route"))
want = [r for r in self.rows if "trail" in r["search"] and r["kind"] == "route"]
said = lambda r: any(" trail" in t for t in r["search"]) # noqa: E731 (a word at the start of a word of any text)
want = [r for r in self.rows if said(r) and r["kind"] == "route"]
self.assertEqual(c["total"], len(want))
self.assertEqual(c["kind"]["trail"], sum(1 for r in self.rows if "trail" in r["search"] and r["kind"] == "trail"))
self.assertEqual(c["kind"]["trail"], sum(1 for r in self.rows if said(r) and r["kind"] == "trail"))
def test_the_script_takes_out_what_would_show_nothing(self):
js = read(WEB, "assets", "app.js")
+2 -1
View File
@@ -351,7 +351,8 @@ class PageTopsTest(unittest.TestCase):
_, _, body, _ = regions.region_page("us-co", recs, SITE)
body = str(body)
self.assertLess(body.index('class="browse__list"'), body.index('class="browse-about"'))
self.assertNotIn("percent", body)
# (the words a row's search reads, in its data-search, are not the page's text)
self.assertNotIn("percent", re.sub(r' data-search="[^"]*"', "", body))
def test_every_page_head_is_compact(self):
css = read(WEB, "assets", "style.css")
+285
View File
@@ -0,0 +1,285 @@
"""The search box reads more than a trail's name: its author, the places it lies in and starts and ends at,
the land unit or body its record names, and its summary (olt/searchtext.py writes the words into each
row's data-search; app.js, between the facet-counts markers, matches them and ranks the rows).
The matching is run under node, on the rows the home page writes from the real records, and checked
against the records' own fields; nothing here names a trail's expected rank except where a case is
spelled out. The site is not built.
"""
import json
import os
import re
import shutil
import subprocess
import sys
import unicodedata
import unittest
WEB = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
ROOT = os.path.dirname(WEB)
sys.path.insert(0, WEB)
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, os.path.join(ROOT, "tools"))
from olt import facets, home, searchtext, words # noqa: E402
import test_filter_bar as bar # noqa: E402
NODE = shutil.which("node")
NAME, AUTHOR, PLACES, SUMMARY, NONE = 0, 1, 2, 3, 9
def match_under_node(rows, queries):
"""{query: {id: how well it matches (0 name, 1 author, 2 places, 3 summary)}} for the rows that match."""
prog = bar.facet_count_source() + """
var input = JSON.parse(require('fs').readFileSync(0, 'utf8'));
var out = {};
input.queries.forEach(function (q) {
var typed = FacetCount.wordsOf(q), hits = {};
input.rows.forEach(function (r) {
var m = FacetCount.match(r.search, typed);
if (m !== FacetCount.NOT_FOUND) hits[r.id] = m;
});
out[q] = hits;
});
process.stdout.write(JSON.stringify(out));
"""
out = subprocess.run([NODE, "-e", prog], input=json.dumps({"rows": rows, "queries": list(queries)}),
capture_output=True, text=True, check=True)
return json.loads(out.stdout)
def plain(text):
text = unicodedata.normalize("NFD", text.lower().replace("'", "").replace("’", ""))
return re.sub(r"[^a-z0-9]+", " ", "".join(c for c in text if not unicodedata.combining(c)))
def starts_a_word(text, typed):
return any(w.startswith(typed) for w in plain(text).split())
class FoldTest(unittest.TestCase):
def test_accents_apostrophes_hyphens_and_case(self):
self.assertEqual(searchtext.fold("Road’s End, Cedar Grove"), "roads end cedar grove")
self.assertEqual(searchtext.fold("Road's End"), "roads end")
self.assertEqual(searchtext.fold("Québec"), "quebec")
self.assertEqual(searchtext.fold("Long-Distance TRAIL"), "long distance trail")
self.assertEqual(searchtext.fold(""), "")
self.assertEqual(searchtext.fold(None), "")
@unittest.skipUnless(NODE, "node is not installed")
def test_the_script_folds_as_the_page_builder_does(self):
recs = bar.Pages.recs()
samples = [t for r in recs for t in searchtext.tier_texts(r)] + [
"Road’s End", "Québec", "Long-Distance", " spaced out ", "Nèw-Brünswick", "100 mi", "4x4 tracks", "St. John’s"]
prog = bar.facet_count_source() + """
var input = JSON.parse(require('fs').readFileSync(0, 'utf8'));
process.stdout.write(JSON.stringify(input.map(FacetCount.fold)));
"""
out = subprocess.run([NODE, "-e", prog], input=json.dumps(samples), capture_output=True, text=True, check=True)
got = json.loads(out.stdout)
bad = [(s, g, searchtext.fold(s)) for s, g in zip(samples, got) if g != searchtext.fold(s)]
self.assertEqual(bad, [])
class RowWordsTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.recs = bar.Pages.recs()
cls.by_id = {r["id"]: r for r in cls.recs}
def test_four_tiers_and_each_word_once(self):
for rec in self.recs:
attr = searchtext.attribute(rec)
self.assertEqual(attr.count("|"), searchtext.TIERS - 1, rec["id"])
seen = [w for tier in attr.split("|") for w in tier.split()]
self.assertEqual(len(seen), len(set(seen)), rec["id"])
self.assertEqual(attr, attr.lower())
def test_the_name_tier_has_the_name_the_abbreviation_and_the_id(self):
rec = self.by_id["john-muir"]
name = searchtext.tiers(rec)[NAME]
for word in ("john", "muir", "jmt"):
self.assertIn(word, name)
def test_the_places_tier_has_full_state_names_both_ends_and_the_body(self):
rec = self.by_id["rae-lakes-loop"]
places = searchtext.tiers(rec)[PLACES]
for word in ("california", "united", "states", "cedar", "grove", "roads", "end", "kings", "canyon", "national", "park", "service"):
self.assertTrue(word in places or word in searchtext.tiers(rec)[NAME], word)
# the code is not what is written: the name is
self.assertNotIn("ca", places)
def test_a_route_by_a_person_has_no_body_in_the_places_tier(self):
for rec in self.recs:
if rec.get("designation", "").lower().startswith(("person-defined route", "guidebook route")):
self.assertNotIn("agency", " ".join(searchtext.tiers(rec)[PLACES]).split(), rec["id"])
def test_a_route_author_is_in_the_author_tier_or_the_name(self):
for rec in self.recs:
who = facets.author(rec)
if not who:
continue
have = set(searchtext.tiers(rec)[NAME] + searchtext.tiers(rec)[AUTHOR])
self.assertTrue(set(searchtext.fold(who).split()) <= have, rec["id"])
def test_the_summary_keeps_no_word_of_fewer_than_three_letters(self):
for rec in self.recs:
self.assertTrue(all(len(w) >= searchtext.SUMMARY_MIN for w in searchtext.tiers(rec)[SUMMARY]), rec["id"])
def test_only_a_list_with_a_search_box_carries_the_words(self):
recs = self.recs[:12]
with_box = home.results(recs, finder=True)
without = home.results(recs)
self.assertEqual(str(with_box).count(' data-search="'), len(recs))
self.assertNotIn(" data-search=", str(without))
def test_the_words_are_written_where_the_script_reads_them(self):
body = str(home.render(self.recs, bar.SITE, bar.ROOT))
self.assertEqual(body.count(' data-search="'), len(self.recs))
@unittest.skipUnless(NODE, "node is not installed")
class QueriesTest(unittest.TestCase):
"""What each query returns, on the home page's rows from the real records."""
@classmethod
def setUpClass(cls):
cls.recs = bar.Pages.recs()
cls.rows = bar.rows_of(home.render(cls.recs, bar.SITE, bar.ROOT))
cls.queries = ["grand canyon", "canyon grand", "glacier", "mount whitney", "roads end", "road's end", "ROADS END",
"new mexico", "colorado", "québec", "quebec", "jamal green", "green jamal", "zzzqx", "at", "jmt",
"long-distance", "grand zzzqx"]
cls.hits = match_under_node(cls.rows, cls.queries)
def ids(self, query):
return set(self.hits[query])
def fields(self, rec):
h = rec.get("hike", {})
return [rec["name"], rec.get("common_name", ""), rec.get("short_name", ""), rec["id"], facets.author(rec),
" ".join(words.region_name(c) for c in rec.get("regions", [])), h.get("start", ""), h.get("end", ""),
rec.get("designation", ""), h.get("summary", "")]
def expected(self, *typed):
"""Every record in whose fields each typed word starts a word, worked out from the fields themselves."""
return {r["id"] for r in self.recs
if all(any(starts_a_word(f, w) for f in self.fields(r)) for w in typed)}
def test_grand_canyon_finds_the_trails_that_go_there(self):
got = self.ids("grand canyon")
self.assertGreaterEqual(len(got), 7)
self.assertLessEqual(got, self.expected("grand", "canyon"))
# everything the fields say, but for the designation of a route that only says who made it
missing = self.expected("grand", "canyon") - got
for rid in missing:
self.assertTrue(starts_a_word(self.by(rid).get("designation", ""), "grand") or starts_a_word(self.by(rid).get("designation", ""), "canyon"), rid)
for rid in ("tonto-trail", "powell-plateau-loop", "nankoweap-bright-angel-loop"):
self.assertIn(rid, got)
self.assertNotIn("appalachian", got)
self.assertNotIn("pacific-crest", got)
def by(self, rid):
return next(r for r in self.recs if r["id"] == rid)
def test_words_in_any_order_find_the_same_trails_with_the_same_rank(self):
self.assertEqual(self.hits["grand canyon"], self.hits["canyon grand"])
def test_glacier_finds_the_trails_that_name_a_glacier_place_or_say_so(self):
got = self.ids("glacier")
self.assertGreaterEqual(len(got), 7)
self.assertEqual(got, self.expected("glacier"))
self.assertIn("ptarmigan-glenns-lake-highline-loop", got)
self.assertNotIn("appalachian", got)
def test_mount_whitney(self):
got = self.ids("mount whitney")
self.assertIn("john-muir", got)
self.assertEqual(got, self.expected("mount", "whitney"))
self.assertNotIn("appalachian", got)
def test_roads_end_finds_road_s_end_with_or_without_the_apostrophe_and_case(self):
got = self.ids("roads end")
self.assertEqual(got, self.ids("road's end"))
self.assertEqual(got, self.ids("ROADS END"))
self.assertIn("rae-lakes-loop", got)
self.assertEqual(got, self.expected("roads", "end"))
self.assertNotIn("appalachian", got)
def test_a_state_s_full_name_finds_the_trails_in_it(self):
got = self.ids("new mexico")
for r in self.recs:
if "NM" in r.get("regions", []):
self.assertIn(r["id"], got, r["id"])
self.assertEqual(got, self.expected("new", "mexico"))
self.assertIn("continental-divide", got)
def test_a_province_with_an_accent_is_found_without_it(self):
self.assertEqual(self.hits["québec"], self.hits["quebec"])
self.assertTrue(self.hits["quebec"])
for r in self.recs:
if "QC" in r.get("regions", []):
self.assertIn(r["id"], self.hits["quebec"], r["id"])
def test_an_author_s_name_finds_the_route_in_either_order(self):
who = next(r for r in self.recs if r["id"] == "across-utah-route")
self.assertEqual(facets.author(who), "Jamal Green")
self.assertEqual(self.hits["jamal green"], self.hits["green jamal"])
self.assertEqual(self.hits["jamal green"].get("across-utah-route"), AUTHOR)
def test_the_abbreviation_finds_the_trail_first(self):
self.assertEqual(self.hits["jmt"], {"john-muir": NAME})
self.assertEqual(self.hits["at"]["appalachian"], NAME)
def test_a_word_of_the_name_ranks_above_one_of_the_places(self):
hits = self.hits["colorado"]
names = [i for i, t in hits.items() if t == NAME]
self.assertTrue({"colorado-trail"} <= set(names))
self.assertGreater(len(set(hits.values())), 1)
# a trail in the state whose name does not say so is still found, after
self.assertEqual(hits["continental-divide"], PLACES)
self.assertLess(max(hits[i] for i in names), hits["continental-divide"])
def test_the_summary_is_the_weakest_place_to_match(self):
hits = self.hits["glacier"]
for rid, how in hits.items():
text = self.fields(self.by(rid))
in_place = any(starts_a_word(f, "glacier") for f in text[:9])
self.assertEqual(how == SUMMARY, not in_place, rid)
def test_every_word_has_to_be_found(self):
self.assertEqual(self.hits["zzzqx"], {})
self.assertEqual(self.hits["grand zzzqx"], {})
def test_a_short_word_is_not_looked_for_in_the_summary(self):
self.assertTrue(all(how != SUMMARY for how in self.hits["at"].values()))
def test_a_hyphenated_word_is_two_words(self):
self.assertEqual(self.hits["long-distance"], match_under_node(self.rows, ["long distance"])["long distance"])
def test_a_nonsense_word_leaves_the_no_results_state_to_show(self):
js = bar.read(WEB, "assets", "app.js")
self.assertIn("if (empty) empty.hidden = shown.length > 0;", js)
page = str(home.render(self.recs, bar.SITE, bar.ROOT))
self.assertIn('id="empty-state" hidden', page)
self.assertIn("No trails match these filters.", page)
class ScriptTest(unittest.TestCase):
"""What the filter bar does with the rank, read from the script."""
def test_the_rows_are_ranked_while_words_are_typed_and_in_their_own_order_otherwise(self):
js = bar.read(WEB, "assets", "app.js")
self.assertIn("d.li.dataset.match = String(m)", js)
self.assertIn("if (m === -1) delete d.li.dataset.match", js)
self.assertIn("return cmpNum(Number(a.dataset.match), Number(b.dataset.match));", js)
# ranked before the counts, and the line only for a match beyond the name
self.assertIn("var says = m > 0 && m < FacetCount.NOT_FOUND ? 'Matches: ' + MATCH_SAYS[m] : '';", js)
def test_the_search_stays_in_the_address(self):
js = bar.read(WEB, "assets", "app.js")
self.assertIn("if (s.q) p.set('q', s.q);", js)
self.assertIn("el.q.value = p.get('q') || '';", js)
if __name__ == "__main__":
unittest.main()