Show each trail's own emblem, keep a history on every record, and list what was left out
Mirror to forge / mirror (push) Canceled after 0s
Validate / validate (push) Canceled after 0s
Validate / history (push) Canceled after 0s
Validate / site (push) Canceled after 0s
Validate / deploy (push) Canceled after 0s

- Emblems for 81 trails, up from 41. Each is the trail's own crest, badge
  or roundel alone, cropped out of a larger logo where need be and made
  transparent where that could be done cleanly. Records without one say
  where an emblem was looked for. The validator checks the logo state.
- Every record has a `[[history]]` list: what changed or was asked for,
  on what basis, who asked and whether it was applied or declined.
  `tools/check_history.py` fails a changed fact with no history entry and
  prints earlier entries about a changed field. It runs in CI before the
  site deploys. Each trail page shows the history.
- A new page, "Considered and left out", built from `left-out.toml`:
  35 trails and routes with the reason, the deciding fact and its source.
- The Hoosier Heritage Trail has its ends, its free map set and its
  emblem from its association (issue 2). Any trail may list its holder's
  own guide or map set.
- A stated permission is quoted in the download credit box.
- `tools/gpx_track.py` turns a GPX file from a holder or a hiker into a
  record's track files.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-16 13:40:03 -07:00
1 parent d34a9617cd
commit 24bfbb2fa8
374 files changed
+7796 -703

No files matched your search

+145
View File
@@ -0,0 +1,145 @@
"""Tests for tools/gpx_track.py: no network.
Run from the repository root:
python3 -m unittest discover tools/tests
"""
import argparse
import json
import os
import sys
import tempfile
import unittest
sys.dont_write_bytecode = True
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import gpx_track as G # noqa: E402
GPX = """<?xml version="1.0" encoding="UTF-8"?>
<gpx version="1.1" creator="Some Device 9000" xmlns="http://www.topografix.com/GPX/1/1">
<metadata><name>Jane Doe's hikes</name><author><name>Jane Doe</name></author></metadata>
<wpt lat="40.5" lon="-100.5"><name>Camp</name></wpt>
<trk><name>Day 1 by Jane</name><desc>private note</desc>
<trkseg>
<trkpt lat="40.0" lon="-100.0"><ele>12.5</ele><time>2020-01-01T10:00:00Z</time></trkpt>
<trkpt lat="40.0" lon="-100.0"><ele>12.5</ele><time>2020-01-01T10:00:05Z</time></trkpt>
<trkpt lat="40.001" lon="-100.0"><ele>13</ele><time>2020-01-01T10:01:00Z</time></trkpt>
<trkpt lat="40.002" lon="-100.0000004"><ele>14</ele></trkpt>
</trkseg>
<trkseg>
<trkpt lat="40.002" lon="-100.0"/>
<trkpt lat="40.003" lon="-100.0"/>
</trkseg>
</trk>
<trk><trkseg>
<trkpt lat="41.0" lon="-100.0"/>
<trkpt lat="41.001" lon="-100.0"/>
</trkseg></trk>
</gpx>"""
def args_for(tmp, gpx, **kw):
d = dict(gpx=gpx, id="t", out=tmp, source="S", licence="L", attribution="A",
route_name=None, gap_km=1.0, dry=False, force=False)
d.update(kw)
return argparse.Namespace(**d)
class ParseTests(unittest.TestCase):
def test_counts_and_order(self):
p = G.parse(GPX)
self.assertEqual(len(p["tracks"]), 2)
self.assertEqual([len(s) for s in p["segments"]], [3, 2, 2]) # repeat dropped
self.assertEqual(p["waypoints"], 1)
self.assertEqual(p["segments"][0][0], [-100.0, 40.0])
self.assertEqual(p["segments"][2][0], [-100.0, 41.0])
def test_rounding(self):
self.assertEqual(G.parse(GPX)["segments"][0][-1], [-100.0, 40.002])
def test_html_refused(self):
with self.assertRaises(G.TrackError):
G.parse("<!DOCTYPE html>\n<html><body>lost</body></html>")
def test_doctype_refused(self):
with self.assertRaises(G.TrackError):
G.parse('<?xml version="1.0"?><!DOCTYPE gpx [<!ENTITY a "b">]><gpx/>')
def test_not_gpx_and_empty_refused(self):
with self.assertRaises(G.TrackError):
G.parse("<kml/>")
with self.assertRaises(G.TrackError):
G.parse('<gpx><trk><trkseg><trkpt lat="1" lon="1"/></trkseg></trk></gpx>')
with self.assertRaises(G.TrackError):
G.parse("not xml")
def test_bad_point_refused(self):
with self.assertRaises(G.TrackError):
G.parse('<gpx><trk><trkseg><trkpt lat="95" lon="1"/><trkpt lat="1" lon="1"/>'
"</trkseg></trk></gpx>")
def test_gpx_10_namespace(self):
p = G.parse('<gpx xmlns="http://www.topografix.com/GPX/1/0"><trk><trkseg>'
'<trkpt lat="1" lon="1"/><trkpt lat="1.001" lon="1"/></trkseg></trk></gpx>')
self.assertEqual(len(p["segments"]), 1)
class FigureTests(unittest.TestCase):
def test_gap_and_parts(self):
f = G.figures(G.parse(GPX))
self.assertEqual((f["tracks"], f["segments"], f["points"]), (2, 3, 7))
self.assertEqual(f["parts"], 2) # first two join, third is ~111 km away
self.assertEqual(len(f["gaps"]), 1)
self.assertEqual(f["gaps"][0]["after_segment"], 2)
self.assertAlmostEqual(f["gaps"][0]["km"], 110.6, delta=1)
self.assertAlmostEqual(f["measured_km"], 0.4448, delta=0.01)
class RunTests(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.mkdtemp()
os.mkdir(os.path.join(self.tmp, "t"))
self.gpx = os.path.join(self.tmp, "in.gpx")
with open(self.gpx, "w") as f:
f.write(GPX)
self.log = []
def test_writes_geometry_only(self):
G.run(args_for(self.tmp, self.gpx, route_name="The Trail"),
today=__import__("datetime").date(2026, 11, 16), out=self.log.append)
text = open(os.path.join(self.tmp, "t", "line.geojson")).read()
doc = json.loads(text)
self.assertEqual(len(doc["features"]), 3)
self.assertEqual(doc["features"][0]["properties"], {"route_name": "The Trail"})
for leak in ("Jane", "Device", "2020", "Camp", "private", "12.5", "ele", "time"):
self.assertNotIn(leak, text)
rel = open(os.path.join(self.tmp, "t", "release.txt")).read()
self.assertIn("Source read: 2026-11-16", rel)
self.assertNotIn("Jane", rel)
self.assertTrue(any(l.startswith("gap after segment 2") for l in self.log))
def test_dry_writes_nothing(self):
G.run(args_for(self.tmp, self.gpx, dry=True), out=self.log.append)
self.assertEqual(os.listdir(os.path.join(self.tmp, "t")), [])
def test_force_and_missing_dir(self):
G.run(args_for(self.tmp, self.gpx), out=self.log.append)
with self.assertRaises(G.TrackError):
G.run(args_for(self.tmp, self.gpx), out=self.log.append)
G.run(args_for(self.tmp, self.gpx, force=True), out=self.log.append)
with self.assertRaises(G.TrackError):
G.run(args_for(self.tmp, self.gpx, id="nope"), out=self.log.append)
def test_needs_release_fields(self):
with self.assertRaises(G.TrackError):
G.run(args_for(self.tmp, self.gpx, licence=None), out=self.log.append)
def test_main_reports_html_cleanly(self):
bad = os.path.join(self.tmp, "bad.gpx")
with open(bad, "w") as f:
f.write("<!DOCTYPE html><html></html>")
self.assertEqual(G.main([bad, "--id", "t", "--out", self.tmp, "--dry"]), 1)
if __name__ == "__main__":
unittest.main()
+43
View File
@@ -0,0 +1,43 @@
"""[[guide]] on a trail that is not a route: its holder's own guide or map set."""
import os
import sys
import unittest
sys.dont_write_bytecode = True
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import validate as V # noqa: E402
GOOD = {"title": "Guide and Map Set", "author": "An Association", "access": "free",
"url": "https://example.org/mapset.pdf", "format": "PDF"}
def check(guides):
errors = []
V.check_guides("t", guides, errors)
return errors
class GuideTest(unittest.TestCase):
def test_no_guide_is_fine(self):
self.assertEqual(check(None), [])
def test_a_complete_guide_passes(self):
self.assertEqual(check([dict(GOOD)]), [])
def test_each_required_field(self):
for field in ("title", "author", "access", "url"):
errors = check([{k: v for k, v in GOOD.items() if k != field}])
self.assertTrue(errors, field)
def test_access_and_url_are_checked(self):
self.assertTrue(check([dict(GOOD, access="gift")]))
self.assertTrue(check([dict(GOOD, url="ftp://example.org/x")]))
def test_price_needs_its_date(self):
self.assertTrue(check([dict(GOOD, price="$5")]))
self.assertEqual(check([dict(GOOD, price="$5", price_checked="2026-11-16")]), [])
if __name__ == "__main__":
unittest.main()
+378
View File
@@ -0,0 +1,378 @@
"""Tests for [[history]]: the validator's checks and tools/check_history.py.
No network. The check runs against small git repositories made in a temporary directory.
Run from the repository root:
python3 -m unittest discover tools/tests
"""
import contextlib
import io
import os
import subprocess
import sys
import tempfile
import unittest
sys.dont_write_bytecode = True
TOOLS = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, TOOLS)
import build_index # noqa: E402
import check_history as C # noqa: E402
import trail_history as H # noqa: E402
OWN = H.OWN_CHECK
def entry(date="2026-11-10", change="Changed it.", fields=("length_km",), basis="A page said so.",
url="https://example.org/page", who=OWN, outcome="applied"):
lines = ["[[history]]", f'date = "{date}"', f'change = "{change}"',
"fields = [" + ", ".join(f'"{f}"' for f in fields) + "]", f'basis = "{basis}"']
if url:
lines.append(f'basis_url = "{url}"')
lines += [f'asked_by = "{who}"', f'outcome = "{outcome}"']
return "\n".join(lines) + "\n"
ADDED = entry("2026-11-01", "The record was added.", ("record",), "The record's own source entry.", None)
def record(length=100, summary="A trail.", measured=99.0, extra="", history=ADDED, line_file=""):
return f'''id = "t"
name = "Test Trail"
length_km = {length}
[source]
line_file = "{line_file}"
[verification]
measured_km = {measured}
[hike]
summary = "{summary}"
caution = "Water is scarce."
{extra}
{history}'''
class Repo:
"""A scratch git repository with one trail, `t`, committed as the base."""
def __init__(self, test, text):
self.dir = tempfile.TemporaryDirectory()
test.addCleanup(self.dir.cleanup)
self.root = self.dir.name
self.git("init", "-q")
os.makedirs(os.path.join(self.root, "t"))
self.write(text)
self.git("add", "-A")
self.commit("base")
self.base = self.git("rev-parse", "HEAD").strip()
def git(self, *args):
done = subprocess.run(["git", "-C", self.root, "-c", "user.name=t", "-c", "user.email=t@example.invalid",
*args], capture_output=True, text=True, check=True)
return done.stdout
def commit(self, message):
self.git("commit", "-q", "-m", message)
def write(self, text, name="trail.toml", tid="t"):
os.makedirs(os.path.join(self.root, tid), exist_ok=True)
with open(os.path.join(self.root, tid, name), "w", encoding="utf-8") as f:
f.write(text)
def run(self, **kwargs):
lines = []
status = C.run(self.root, self.base, out=lines.append, **kwargs)
return status, "\n".join(lines)
class ClassifyTest(unittest.TestCase):
def test_facts_and_not_facts(self):
for path in ("name", "length_km", "length_note", "kind", "source.licence", "source.line_file",
"source.publisher_url", "route.creator", "route.line_policy", "hike.start", "hike.caution",
"hike.official_url", "shield.logo_file", "shield.logo_owner", "short_name_url", "guide.url",
"osm.relation", "a_field_added_later"):
self.assertTrue(H.is_fact(path), path)
for path in ("history", "history.outcome", "verification.measured_km", "verification.date",
"source.source_checked", "hike.summary", "hike.checked", "hike.source.url", "guide.price",
"link.url", "shield.note", "osm.note", "wave"):
self.assertFalse(H.is_fact(path), path)
def test_every_schema_field_is_classified_somewhere(self):
self.assertIn("source.licence", H.SCHEMA_FIELDS)
self.assertNotIn("history", H.SCHEMA_FIELDS)
self.assertNotIn("record", H.SCHEMA_FIELDS)
def test_changed_paths_handles_tables_and_lists(self):
old = {"name": "A", "regions": ["VT"], "guide": [{"title": "x", "url": "u"}], "history": [{"date": "1"}]}
new = {"name": "A", "regions": ["VT", "NH"], "guide": [{"title": "x", "url": "u"}, {"title": "y", "url": "v"}],
"history": [{"date": "1"}, {"date": "2"}], "route": {"creator": "C"}}
self.assertEqual(H.changed_paths(old, new), ["guide.title", "guide.url", "regions", "route.creator"])
def test_an_entry_covers_its_field_and_what_is_under_a_table(self):
e = {"fields": ["source"]}
self.assertTrue(H.entry_covers(e, "source.licence"))
self.assertFalse(H.entry_covers({"fields": ["source.licence"]}, "source.licence_text"))
self.assertFalse(H.entry_covers({"fields": ["record"]}, "name"))
class EntryShapeTest(unittest.TestCase):
def check(self, history, **kw):
errors = []
rec = {"history": history} if history is not None else {}
H.check_entries("t", rec, errors)
return errors
def good(self, **kw):
e = {"date": "2026-11-01", "change": "Added.", "fields": ["record"], "basis": "Source.",
"asked_by": OWN, "outcome": "applied"}
e.update(kw)
return e
def second(self, **kw):
e = {"date": "2026-11-02", "change": "Changed.", "fields": ["length_km"], "basis": "A page.",
"basis_url": "https://example.org/", "asked_by": "a hiker", "outcome": "declined"}
e.update(kw)
return e
def test_good(self):
self.assertEqual(self.check([self.good(), self.second()]), [])
def test_the_added_entry_may_leave_out_the_address(self):
self.assertEqual(self.check([self.good()]), [])
second = self.second()
del second["basis_url"]
self.assertTrue(any("missing basis_url" in e for e in self.check([self.good(), second])))
def test_no_history_is_an_error(self):
self.assertTrue(any("no [[history]]" in e for e in self.check(None)))
self.assertTrue(any("no [[history]]" in e for e in self.check([])))
def test_missing_and_unknown_fields(self):
e = self.good()
del e["asked_by"]
e["extra"] = 1
errors = self.check([e])
self.assertTrue(any("missing asked_by" in x for x in errors))
self.assertTrue(any("unknown field extra" in x for x in errors))
def test_outcome(self):
errors = self.check([self.good(), self.second(outcome="maybe")])
self.assertTrue(any("outcome must be one of applied, declined" in x for x in errors))
def test_dates(self):
self.assertTrue(any("YYYY-MM-DD" in x for x in self.check([self.good(date="11/01/2026")])))
self.assertTrue(any("not a real date" in x for x in self.check([self.good(date="2026-02-30")])))
errors = self.check([self.good(date="2026-11-05"), self.second(date="2026-11-02")])
self.assertTrue(any("earlier than the entry before" in x for x in errors))
self.assertEqual(self.check([self.good(date="2026-11-02"), self.second(date="2026-11-02")]), [])
def test_fields(self):
self.assertTrue(any("non-empty list" in x for x in self.check([self.good(fields=[])])))
errors = self.check([self.good(), self.second(fields=["lenght_km"])])
self.assertTrue(any("not a field of the record" in x for x in errors))
self.assertTrue(any("not a field of the record" in x for x in self.check([self.good(), self.second(fields=["history"])])))
self.assertEqual(self.check([self.good(), self.second(fields=["source", "hike.source", "guide.price"])]), [])
def test_record_entry_comes_first_and_alone(self):
self.assertTrue(any("first entry must be" in x for x in self.check([self.second()])))
self.assertTrue(any("only the first entry" in x for x in self.check([self.good(), self.good(date="2026-11-03")])))
self.assertTrue(any("cannot be listed with other" in x for x in self.check([self.good(fields=["record", "name"])])))
def test_basis_url_is_an_address(self):
self.assertTrue(any("http(s) address" in x for x in self.check([self.good(), self.second(basis_url="page")])))
def test_real_records_all_have_valid_history(self):
root = os.path.dirname(TOOLS)
errors = []
for tid in build_index.trail_dirs(root):
H.check_entries(tid, build_index.load_toml(os.path.join(root, tid, "trail.toml")), errors)
self.assertEqual(errors, [])
class CheckTest(unittest.TestCase):
def test_a_fact_changed_with_no_entry_fails_and_names_record_and_field(self):
repo = Repo(self, record())
repo.write(record(length=120))
status, out = repo.run()
self.assertEqual(status, 1)
self.assertIn("FAIL t: facts changed and no new history entry was added. Changed: length_km.", out)
def test_a_fact_changed_with_its_entry_passes(self):
repo = Repo(self, record())
repo.write(record(length=120, history=ADDED + "\n" + entry("2026-11-12", fields=("length_km",))))
status, out = repo.run()
self.assertEqual(status, 0, out)
self.assertIn("OK history", out)
def test_an_entry_for_another_field_does_not_cover(self):
repo = Repo(self, record())
repo.write(record(length=120, history=ADDED + "\n" + entry("2026-11-12", fields=("name",))))
status, out = repo.run()
self.assertEqual(status, 1)
self.assertIn('no new history entry with outcome "applied" names length_km', out)
def test_a_declined_entry_does_not_cover_a_change(self):
repo = Repo(self, record())
repo.write(record(length=120, history=ADDED + "\n" + entry("2026-11-12", outcome="declined")))
self.assertEqual(repo.run()[0], 1)
def test_a_declined_entry_alone_is_fine(self):
repo = Repo(self, record())
repo.write(record(history=ADDED + "\n" + entry("2026-11-12", outcome="declined", who="a hiker")))
status, out = repo.run()
self.assertEqual(status, 0, out)
def test_not_facts_need_no_entry(self):
repo = Repo(self, record())
repo.write(record(summary="A different sentence.", measured=95.5))
status, out = repo.run()
self.assertEqual(status, 0, out)
self.assertIn("not facts", out)
self.assertIn("hike.summary", out)
def test_a_hiker_fact_needs_an_entry(self):
repo = Repo(self, record())
repo.write(record().replace("Water is scarce.", "Water is scarce in August."))
status, out = repo.run()
self.assertEqual(status, 1)
self.assertIn("Changed: hike.caution", out)
def test_a_changed_track_file_counts_as_a_change_to_source_line_file(self):
repo = Repo(self, record(line_file="line.geojson"))
repo.write("{}", "line.geojson")
repo.git("add", "-A")
repo.commit("track")
repo.base = repo.git("rev-parse", "HEAD").strip()
repo.write('{"type":"FeatureCollection"}', "line.geojson")
status, out = repo.run()
self.assertEqual(status, 1)
self.assertIn("Changed: source.line_file", out)
repo.write(record(line_file="line.geojson", history=ADDED + "\n" + entry(
"2026-11-12", fields=("source.line_file",), change="A newer track.")))
self.assertEqual(repo.run()[0], 0)
def test_earlier_entry_for_the_same_field_is_printed(self):
past = ADDED + "\n" + entry("2026-11-05", change="Changed the length.", basis="The holder's page says 100 km.",
url="https://holder.example/trail")
repo = Repo(self, record(history=past))
repo.write(record(length=120, history=past + "\n" + entry("2026-11-12")))
status, out = repo.run()
self.assertEqual(status, 0, out)
self.assertIn("length_km of t was last changed on 2026-11-05 at the request of the dataset's own check, "
"because The holder's page says 100 km (https://holder.example/trail); outcome applied.", out)
self.assertNotIn("!!", out)
def test_an_earlier_request_by_someone_else_is_printed_loudly(self):
past = ADDED + "\n" + entry("2026-11-05", who="the trail association's president")
repo = Repo(self, record(history=past))
repo.write(record(length=120, history=past + "\n" + entry("2026-11-12")))
status, out = repo.run()
self.assertEqual(status, 0, out)
loud = [line for line in out.split("\n") if line.startswith("!!")]
self.assertEqual(len(loud), 1, out)
self.assertIn("the trail association's president", loud[0])
self.assertIn("NOT the dataset's own check", loud[0])
def test_an_earlier_declined_request_is_printed_loudly(self):
past = ADDED + "\n" + entry("2026-11-05", who="a hiker", outcome="declined",
basis="The holder's page says 100 km.")
repo = Repo(self, record(history=past))
repo.write(record(length=120, history=past + "\n" + entry("2026-11-12")))
status, out = repo.run()
self.assertEqual(status, 0, out)
loud = [line for line in out.split("\n") if line.startswith("!!")]
self.assertEqual(len(loud), 1, out)
self.assertIn("DECLINED", loud[0])
self.assertIn("A request to change length_km on 2026-11-05 at the request of a hiker", loud[0])
def test_earlier_entries_about_other_fields_are_not_printed(self):
past = ADDED + "\n" + entry("2026-11-05", fields=("name",), who="a hiker", outcome="declined")
repo = Repo(self, record(history=past))
repo.write(record(length=120, history=past + "\n" + entry("2026-11-12")))
status, out = repo.run()
self.assertEqual(status, 0, out)
self.assertNotIn("!!", out)
self.assertNotIn("a hiker", out)
def test_github_annotations(self):
past = ADDED + "\n" + entry("2026-11-05", who="a hiker", outcome="declined")
repo = Repo(self, record(history=past))
repo.write(record(length=120))
os.environ["GITHUB_ACTIONS"] = "true"
self.addCleanup(os.environ.pop, "GITHUB_ACTIONS", None)
status, out = repo.run()
self.assertEqual(status, 1)
self.assertIn("::error file=t/trail.toml::", out)
self.assertIn("::warning file=t/trail.toml::", out)
def test_earlier_entries_cannot_be_rewritten(self):
past = ADDED + "\n" + entry("2026-11-05")
repo = Repo(self, record(history=past))
repo.write(record(history=ADDED + "\n" + entry("2026-11-05", basis="Another reason.")))
status, out = repo.run()
self.assertEqual(status, 1)
self.assertIn("earlier history entries were changed or removed", out)
self.assertEqual(repo.run(allow_edits=True)[0], 0)
def test_a_new_record_needs_its_added_entry(self):
repo = Repo(self, record())
repo.write(record(history=entry("2026-11-12")).replace('id = "t"', 'id = "u"'), tid="u")
status, out = repo.run()
self.assertEqual(status, 1)
self.assertIn('a new record needs a history entry with fields = ["record"]', out)
repo.write(record(history=ADDED).replace('id = "t"', 'id = "u"'), tid="u")
status, out = repo.run()
self.assertEqual(status, 0, out)
self.assertIn("new record", out)
def test_an_entry_naming_a_field_that_did_not_change_is_noted(self):
repo = Repo(self, record())
repo.write(record(history=ADDED + "\n" + entry("2026-11-12", fields=("name",))))
status, out = repo.run()
self.assertEqual(status, 0, out)
self.assertIn("says name changed, but it did not change here", out)
def test_only_changed_records_are_looked_at(self):
repo = Repo(self, record())
repo.write(record(length=999, history=""), tid="u") # untracked, a new record without history
repo.git("add", "-A")
repo.commit("u")
repo.base = repo.git("rev-parse", "HEAD").strip()
status, out = repo.run()
self.assertEqual(status, 0, out)
self.assertIn("0 changed records", out)
def test_work_is_compared_with_the_merge_base(self):
repo = Repo(self, record())
repo.git("checkout", "-q", "-b", "other")
repo.write(record(length=120, history=ADDED + "\n" + entry("2026-11-12")))
repo.git("add", "-A")
repo.commit("someone else's change")
repo.git("checkout", "-q", "-")
repo.base = "other" # the work here leaves the record as it was
status, out = repo.run()
self.assertEqual(status, 0, out)
self.assertIn("0 changed records", out)
def test_a_base_that_cannot_be_read_says_so(self):
repo = Repo(self, record())
repo.base = "no-such-revision"
with self.assertRaises(C.BaseError):
repo.run()
with contextlib.redirect_stdout(io.StringIO()) as printed:
self.assertEqual(C.main(["--facts"]), 0)
self.assertIn("length_km", printed.getvalue())
def test_an_all_zero_base_falls_back_to_the_default(self):
repo = Repo(self, record())
repo.git("branch", "-m", "main")
repo.base = "0" * 40
status, out = repo.run()
self.assertEqual(status, 0, out)
if __name__ == "__main__":
unittest.main()
+130
View File
@@ -0,0 +1,130 @@
"""Tests for the left-out.toml checks in tools/validate.py: no network.
Run from the repository root:
python3 -m unittest discover tools/tests
"""
import os
import sys
import unittest
sys.dont_write_bytecode = True
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import validate as V # noqa: E402
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
GOOD = {
"id": "example-trail",
"name": "Example Trail",
"country": "US",
"regions": ["PA"],
"length_mi": 42.0,
"length_km": 68,
"reason": "below-floor",
"note": "The holder gives it as 42 miles, below the 50 mile floor.",
"source_url": "https://example.org/example-trail",
"decided": "2026-11-14",
"was_listed": False,
}
WAITING = dict(
GOOD,
id="waiting-trail",
name="Waiting Trail",
reason="waiting",
waiting_for="The holder builds enough of it to walk through.",
)
TRAILS = [{"id": "long-trail", "name": "Long Trail (Vermont)"}]
def check(entries, trails=TRAILS):
errors = []
V.check_left_out_entries(entries, trails, errors)
return errors
class LeftOutTest(unittest.TestCase):
def test_good_entries_are_valid(self):
self.assertEqual(check([GOOD, WAITING]), [])
def test_every_required_field(self):
for field in ("id", "name", "country", "regions", "reason", "note",
"decided", "was_listed"):
entry = {k: v for k, v in GOOD.items() if k != field}
self.assertTrue(check([entry]), field)
self.assertTrue(check([dict(GOOD, **{field: ""})]), field)
self.assertTrue(check([dict(GOOD, **{field: " "})]), field)
def test_unknown_key(self):
self.assertTrue(any("unknown field rank" in e
for e in check([dict(GOOD, rank=1)])))
def test_unknown_reason(self):
errors = check([dict(GOOD, reason="too-short")])
self.assertTrue(any("reason" in e for e in errors))
def test_bad_country_and_region(self):
self.assertTrue(any("country" in e for e in check([dict(GOOD, country="MX")])))
self.assertTrue(any("region" in e for e in check([dict(GOOD, regions=["XX"])])))
self.assertTrue(any("regions" in e for e in check([dict(GOOD, regions="PA")])))
def test_bad_date(self):
for bad in ("2026-11-31", "November 2026", "2026/11/14"):
self.assertTrue(any("decided" in e
for e in check([dict(GOOD, decided=bad)])), bad)
def test_source_url_must_be_http(self):
self.assertTrue(any("http(s)" in e
for e in check([dict(GOOD, source_url="ftp://example.org/a")])))
def test_source_url_may_be_missing_only_when_the_note_says_why(self):
entry = {k: v for k, v in GOOD.items() if k != "source_url"}
self.assertTrue(check([entry]))
said = dict(entry, note="No page publishes it as one trail, so there is no source page to give.")
self.assertEqual(check([said]), [])
def test_waiting_needs_waiting_for_and_others_must_not_have_it(self):
entry = {k: v for k, v in WAITING.items() if k != "waiting_for"}
self.assertTrue(any("waiting_for" in e for e in check([entry])))
self.assertTrue(any("waiting_for" in e
for e in check([dict(GOOD, waiting_for="Something changes.")])))
def test_was_listed_must_be_a_boolean(self):
self.assertTrue(any("was_listed" in e
for e in check([dict(GOOD, was_listed="yes")])))
def test_lengths_must_agree_and_be_positive(self):
self.assertTrue(check([dict(GOOD, length_mi=42.0, length_km=420)]))
self.assertTrue(check([dict(GOOD, length_mi=-1)]))
no_length = {k: v for k, v in GOOD.items() if not k.startswith("length_")}
self.assertEqual(check([no_length]), [])
def test_entries_must_be_sorted_by_name(self):
errors = check([WAITING, GOOD])
self.assertTrue(any("sorted" in e for e in errors))
def test_no_duplicate_id_or_name(self):
self.assertTrue(any("duplicate" in e for e in check([GOOD, dict(GOOD)])))
def test_no_entry_matches_a_listed_trail(self):
by_id = dict(GOOD, id="long-trail")
self.assertTrue(any("listed" in e for e in check([by_id])))
by_name = dict(GOOD, name="Long Trail (Vermont)")
self.assertTrue(any("listed" in e for e in check([by_name])))
def test_the_real_file_passes(self):
errors = []
trails = []
import tomllib
for name in sorted(os.listdir(ROOT)):
path = os.path.join(ROOT, name, "trail.toml")
if os.path.isfile(path):
with open(path, "rb") as f:
rec = tomllib.load(f)
trails.append({"id": rec.get("id", name), "name": rec.get("name", "")})
V.check_left_out(ROOT, trails, errors)
self.assertEqual(errors, [])
if __name__ == "__main__":
unittest.main()
+79
View File
@@ -0,0 +1,79 @@
"""Tests for the [shield] checks in tools/validate.py: no network.
Run from the repository root:
python3 -m unittest discover tools/tests
"""
import os
import sys
import tempfile
import unittest
sys.dont_write_bytecode = True
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import validate as V # noqa: E402
WITH_FILE = {"status": "use-real-logo", "logo_source": "https://example.org/logo.png", "contact": "Club",
"note": "The club's crest.", "logo_file": "shield.png", "logo_owner": "Club"}
NO_EMBLEM = {"status": "no-logo-exists", "logo_source": "", "contact": "", "note": "Looked at https://example.org/; no crest.",
"logo_file": "", "logo_owner": ""}
NOT_FOUND = dict(NO_EMBLEM, status="logo-not-found", note="A sign shows one; no artwork found at https://example.org/.")
def check(shield, files=()):
with tempfile.TemporaryDirectory() as d:
for f in files:
open(os.path.join(d, f), "wb").write(b"x")
errors = []
V.check_shield("t", shield, d, errors)
return errors
class ShieldStatusTest(unittest.TestCase):
def test_the_three_states_pass(self):
self.assertEqual(check(WITH_FILE, ["shield.png"]), [])
self.assertEqual(check(NO_EMBLEM), [])
self.assertEqual(check(NOT_FOUND), [])
def test_status_is_required(self):
errors = check({k: v for k, v in NO_EMBLEM.items() if k != "status"})
self.assertEqual(len(errors), 1)
self.assertIn("shield.status", errors[0])
def test_status_must_be_one_of_the_three(self):
for bad in ("no-logo", "logo not found", "use-logo", "none"):
errors = check(dict(NO_EMBLEM, status=bad))
self.assertTrue(any("not one of" in e for e in errors), bad)
def test_use_real_logo_needs_a_file(self):
errors = check(dict(WITH_FILE, logo_file=""))
self.assertTrue(any("use-real-logo" in e and "names no file" in e for e in errors), errors)
def test_use_real_logo_needs_the_file_on_disk(self):
errors = check(WITH_FILE)
self.assertTrue(any("does not exist" in e for e in errors), errors)
def test_logo_file_name_is_limited(self):
errors = check(dict(WITH_FILE, logo_file="crest.jpg"), ["crest.jpg"])
self.assertTrue(any("shield.svg or shield.png" in e for e in errors), errors)
def test_a_file_on_disk_means_use_real_logo(self):
for status in ("no-logo-exists", "logo-not-found"):
errors = check(dict(NO_EMBLEM, status=status), ["shield.svg"])
self.assertTrue(any("is use-real-logo" in e for e in errors), (status, errors))
errors = check(dict(NO_EMBLEM, status=status, logo_file="shield.png"), ["shield.png"])
self.assertTrue(any("is use-real-logo" in e for e in errors), (status, errors))
def test_a_trail_without_a_file_says_where_it_looked(self):
for base in (NO_EMBLEM, NOT_FOUND):
errors = check(dict(base, note=" "))
self.assertEqual(len(errors), 1, base["status"])
self.assertIn("shield.note", errors[0])
def test_logo_owner_is_still_required_with_a_file(self):
errors = check(dict(WITH_FILE, logo_owner=""), ["shield.png"])
self.assertTrue(any("logo_owner" in e for e in errors), errors)
if __name__ == "__main__":
unittest.main()