"""Tests for the machine-readable side of the site: JSON-LD, social cards, the sitemap's dates, robots headers, the 404, the Atom feed, llms.txt and the favicon. The JSON-LD is checked against the properties schema.org and Google Search Central document for each type (REQUIRED below, read 2026-11); Google's Rich Results Test itself cannot be run here. The site is built into web/.cache/test-site, as the other page tests do. """ import html import json import os import re import subprocess import sys import unittest import xml.etree.ElementTree as ET WEB = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ROOT = os.path.dirname(WEB) sys.path.insert(0, WEB) import serve # noqa: E402 from olt import browse, cards, common, docs, feed, records, regions, seo, site, thumbs # noqa: E402 OUT = os.path.join(WEB, ".cache", "test-site") SITE = site.load() BASE = SITE.base_url # The properties each type must carry: Google's required ones where it has a feature # (BreadcrumbList, ListItem, Dataset), and the ones that make the node say what it is otherwise. REQUIRED = { "ItemPage": ("@id", "url", "name", "mainEntity", "dateModified"), "CollectionPage": ("@id", "url", "name", "mainEntity", "dateModified"), "Place": ("name",), "TouristAttraction": ("@id", "name", "url", "additionalProperty"), # a trail or route "ItemList": ("itemListElement", "numberOfItems"), "BreadcrumbList": ("itemListElement",), "ListItem": ("position", "name"), "WebSite": ("name", "url"), "Organization": ("name", "url", "logo"), "Dataset": ("name", "description", "license", "creator", "distribution", "keywords", "spatialCoverage", "temporalCoverage", "dateModified", "version", "isAccessibleForFree", "variableMeasured", "measurementTechnique"), "DataDownload": ("contentUrl", "encodingFormat"), "PropertyValue": ("name",), } # Things a page about a trail must not claim: the dataset holds none of them. FORBIDDEN = {"aggregateRating", "review", "reviews", "openingHours", "openingHoursSpecification", "priceRange", "offers", "price", "telephone", "ratingValue", "potentialAction"} def missing(node): """The required properties a node lacks, by its type; ListItem needs item or url as well.""" types = node.get("@type") types = types if isinstance(types, list) else [types] out = [] for t in types: out += [k for k in REQUIRED.get(t, ()) if node.get(k) in (None, "", [], {})] if t == "ListItem" and not (node.get("item") or node.get("url")): out.append("item") if t == "Dataset" and "description" in node and not 50 <= len(node["description"]) <= 5000: out.append("description (50 to 5000 characters)") return out def read(rel): with open(os.path.join(OUT, *rel.split("/")), encoding="utf-8") as f: return f.read() def ld_blocks(doc): """The raw text of every JSON-LD script in an HTML document.""" return re.findall(r'', doc, re.S) def nodes_of(doc): """Every JSON-LD node on a page, flattened out of any @graph.""" out = [] for raw in ld_blocks(doc): obj = json.loads(raw) out += obj["@graph"] if "@graph" in obj else [obj] return out def walk(obj): """Every dict inside a JSON-LD value.""" if isinstance(obj, dict): yield obj for v in obj.values(): yield from walk(v) elif isinstance(obj, list): for v in obj: yield from walk(v) def meta(doc, key, attr="property"): m = re.search(rf']*>(.*?)', doc, re.S) if not m: return [] items = [] for li in re.findall(r"]*>(.*?)", m.group(1), re.S): href = re.search(r'href="([^"]*)"', li) items.append((" ".join(html.unescape(re.sub(r"<[^>]+>", "", li)).split()), href.group(1) if href else "")) return items def setUpModule(): os.makedirs(os.path.dirname(OUT), exist_ok=True) subprocess.run([sys.executable, os.path.join(WEB, "build.py"), "--out", OUT], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) class RequiredPropertiesTest(unittest.TestCase): """The checker itself: it must fail on a node that lacks what its type needs.""" def test_missing_properties_are_found(self): self.assertEqual(missing({"@type": ["Place", "TouristAttraction"], "name": "X", "url": "u", "@id": "i"}), ["additionalProperty"]) self.assertEqual(missing({"@type": "Place"}), ["name"]) self.assertIn("name", missing({"@type": "BreadcrumbList", "itemListElement": []}) + ["name"]) self.assertEqual(missing({"@type": "BreadcrumbList"}), ["itemListElement"]) self.assertEqual(missing({"@type": "ListItem", "position": 1, "name": "A"}), ["item"]) self.assertEqual(missing({"@type": "ListItem", "position": 1, "name": "A", "item": "https://x/"}), []) self.assertIn("contentUrl", missing({"@type": "DataDownload", "encodingFormat": "text/csv"})) self.assertTrue(missing({"@type": "Dataset", "name": "n", "description": "too short"})) def test_a_trail_without_a_name_would_fail(self): rec = records.load_record(ROOT, "long-trail") rec["derived"]["downloads"] = [] node = seo.place_node(rec, SITE) self.assertEqual(missing(node), []) node.pop("additionalProperty") self.assertEqual(missing(node), ["additionalProperty"]) class JsonLdTest(unittest.TestCase): @classmethod def setUpClass(cls): cls.records = records.load_records(ROOT) cls.pages = {p: read(p) for p in page_paths()} def test_every_block_parses_and_is_escaped(self): seen = 0 for path, doc in self.pages.items(): for raw in ld_blocks(doc): seen += 1 obj = json.loads(raw) self.assertEqual(obj["@context"], "https://schema.org", path) self.assertNotRegex(raw, r"[<>&]", f"{path}: unescaped character inside JSON-LD") self.assertGreater(seen, 280) def test_blocks_are_data_blocks_the_policy_allows(self): """application/ld+json is not script: the browser does not run it, so script-src 'self' covers every page and nothing here needs a looser policy.""" rules = serve.parse_headers(os.path.join(OUT, "_headers")) csp = next(v for pat, hs in rules if pat.match("/") for k, v in hs if k.lower() == "content-security-policy") script_src = re.search(r"script-src ([^;]*)", csp).group(1).split() # Besides 'self': the Google tag's loader and the hash of its one inline script. self.assertEqual(script_src[:2], ["'self'", "https://www.googletagmanager.com"]) self.assertEqual(len(script_src), 3) self.assertTrue(script_src[2].startswith("'sha256-"), script_src) self.assertNotIn("unsafe-inline", csp.replace("style-src-attr 'unsafe-inline'", "")) for path, doc in self.pages.items(): self.assertNotRegex(doc, r'