\s*(.*?)
', page, re.S):
self.assertIn('alt=""', img)
self.assertIn('class="vh"', img) # the link around the image still has a name
def test_sources_page_counts_measured_lines(self):
page = read_out("sources/index.html")
measured = sum(1 for r in self.records if r.get("verification", {}).get("verified"))
self.assertIn(f"Line measured{measured}<", page)
self.assertIn("Source status: OpenStreetMap only", page)
self.assertEqual(page.count('Trails and routes | '), 2)
self.assertNotRegex(page, r'[^<]*, ')
for name in ("all-gpx.zip", "all-geojson.zip"):
size = words.fmt_bytes(os.path.getsize(os.path.join(OUT, "data", name)))
self.assertRegex(page, rf'/data/{re.escape(name)} | [^<]* | {re.escape(size)}<')
self.assertIn(f'"contentUrl":"{site.load().base_url}/data/{name}"', page)
def test_archives_hold_every_line(self):
lines = [r for r in self.records if r["derived"]["has_line"]]
for name, ext in (("all-gpx.zip", ".gpx"), ("all-geojson.zip", ".geojson")):
with zipfile.ZipFile(os.path.join(OUT, "data", name)) as zf:
names = set(zf.namelist())
for doc in ("README.txt", "trails.csv", "SOURCES.md"):
self.assertIn(doc, names, name)
for r in lines:
self.assertIn(f'{r["id"]}/{r["id"]}{ext}', names, name)
self.assertIn(f'{r["id"]}/release.txt', names, name)
if "alternates" in r["derived"]["files"]:
self.assertIn(f'{r["id"]}/{r["id"]}-alternates{ext}', names, name)
self.assertTrue(all(n.endswith((ext, "release.txt")) or "/" not in n for n in names), name)
readme = zf.read("README.txt").decode("utf-8")
self.assertIn("release.txt", readme)
self.assertIn("trails.csv", readme)
self.assertIn("5 m", readme)
if ext == ".gpx":
self.assertIsNone(zf.testzip())
info = zf.getinfo(f"{lines[0]['id']}/{lines[0]['id']}.gpx")
self.assertEqual(info.compress_type, zipfile.ZIP_DEFLATED)
def test_document_requests_link_only_when_configured(self):
text = (" Open an issue, or send a patch. Ask by opening an issue in this repository, "
"or by writing to the repository maintainers through the contact. ")
self.assertEqual(docs.link_requests(text, site.Site("N", "T")), text)
out = docs.link_requests(text, site.Site("N", "T", repo_url="https://example.org/r"))
self.assertIn('Open an issue', out)
self.assertIn('opening an issue', out)
self.assertIn('writing to the repository maintainers', out)
out = docs.link_requests(text, site.Site("N", "T", contact_url="mailto:a@example.org"))
self.assertIn('writing to the repository maintainers', out)
self.assertIn('Open an issue', out)
configured = site.load()
if not (configured.repo_url or configured.contact_url): # left as the documents have it
self.assertIn("Open an issue, or send a patch", read_out("about/index.html"))
self.assertIn(" by opening an issue in this repository, or by writing to the repository maintainers ",
read_out("logos/index.html"))
class HeadersTest(unittest.TestCase):
"""The built _headers, read the way serve.py applies it, over every file in the built site."""
NETLIFY_DEFAULT_CACHE = "public, max-age=0, must-revalidate" # when no rule sets Cache-Control
@classmethod
def setUpClass(cls):
cls.rules = serve.parse_headers(os.path.join(OUT, "_headers"))
cls.paths = []
for base, _, names in os.walk(OUT):
for n in names:
cls.paths.append("/" + os.path.relpath(os.path.join(base, n), OUT).replace(os.sep, "/"))
def headers(self, path):
"""{lower name: value}, failing when two matching rules set the same header."""
out = {}
for pattern, headers in self.rules:
if pattern.match(path):
for name, value in headers:
self.assertNotIn(name.lower(), out, f"{path}: {name} set by two rules")
out[name.lower()] = value
return out
def test_pages_revalidate(self):
pages = [p for p in self.paths if p.endswith(".html")]
self.assertGreater(len(pages), 200)
clean = [p[:-len("index.html")] for p in pages if p.endswith("/index.html")]
for path in pages + clean:
cache = self.headers(path).get("cache-control", self.NETLIFY_DEFAULT_CACHE)
self.assertIn("max-age=0", cache, path)
for path in ("/data/", "/data/index.html", "/data/schema/", "/data/changelog/"):
self.assertIn("max-age=0", self.headers(path).get("cache-control", self.NETLIFY_DEFAULT_CACHE), path)
def test_line_files_and_licences_get_their_types(self):
seen = {".gpx": 0, ".geojson": 0}
for path in self.paths:
h = self.headers(path)
if path.startswith("/trails/") and path.endswith(".gpx"):
seen[".gpx"] += 1
self.assertEqual(h.get("content-type"), "application/gpx+xml", path)
elif path.startswith("/trails/") and path.endswith(".geojson"):
seen[".geojson"] += 1
self.assertEqual(h.get("content-type"), "application/geo+json", path)
elif path.startswith("/data/") and path.endswith(".zip"):
self.assertEqual(h.get("content-type"), "application/zip", path)
self.assertGreater(seen[".gpx"], 85)
self.assertGreater(seen[".geojson"], 85)
self.assertEqual(self.headers("/licences/LICENSE").get("content-type"), "text/plain; charset=utf-8")
self.assertIn("/licences/LICENSE", self.paths)
def test_fonts_are_same_origin(self):
csp = self.headers("/").get("content-security-policy", "")
font_src = re.search(r"font-src ([^;]*)", csp).group(1)
self.assertEqual(font_src.strip(), "'self'")
self.assertIn("https://tiles.openfreemap.org", re.search(r"connect-src ([^;]*)", csp).group(1))
class SeoTest(unittest.TestCase):
def test_sitemap_absent_without_base_url(self):
import tempfile
with tempfile.TemporaryDirectory() as tmp:
seo.write_seo_files(tmp, ["/"], site.Site("N", "T"))
self.assertFalse(os.path.exists(os.path.join(tmp, "sitemap.xml")))
with open(os.path.join(tmp, "robots.txt"), encoding="utf-8") as f:
self.assertNotIn("Sitemap:", f.read())
def test_sitemap_complete_with_base_url(self):
import tempfile
recs = records.load_records(ROOT)
by_slug, _ = regions_mod.collect_regions(recs)
region_paths = [f"/regions/{s}/" for s in sorted(by_slug)]
paths = seo.all_paths(recs, region_paths)
s = site.Site("N", "T", base_url="https://example.org")
with tempfile.TemporaryDirectory() as tmp:
seo.write_seo_files(tmp, paths, s)
with open(os.path.join(tmp, "sitemap.xml"), encoding="utf-8") as f:
xml = f.read()
for p in paths:
self.assertIn(f"https://example.org{p}", xml, p)
with open(os.path.join(tmp, "robots.txt"), encoding="utf-8") as f:
self.assertIn("Sitemap: https://example.org/sitemap.xml", f.read())
if __name__ == "__main__":
unittest.main()
|