diff --git a/tests/test_docs.py b/tests/test_docs.py new file mode 100644 index 0000000..a39c769 --- /dev/null +++ b/tests/test_docs.py @@ -0,0 +1,71 @@ +"""The README and docs/ pages link to each other; keep those links from rotting.""" + +import os +import re +import unittest + +from helpers import REPO + +PAGES = ["README.md"] + sorted(f"docs/{n}" for n in os.listdir(os.path.join(REPO, "docs")) + if n.endswith(".md")) + + +def read(rel): + with open(os.path.join(REPO, rel)) as f: + return f.read() + + +def strip_code(text): + """Drop fenced blocks and inline code, where `[x](y)` is an example, not a link.""" + text = re.sub(r"^```.*?^```", "", text, flags=re.S | re.M) + return re.sub(r"`[^`\n]*`", "", text) + + +def slug(heading): + """The anchor Gitea/GitHub make for a heading.""" + heading = heading.replace("`", "").strip().lower() + return re.sub(r"\s", "-", re.sub(r"[^\w\s-]", "", heading)) + + +def anchors(rel): + text = re.sub(r"^```.*?^```", "", read(rel), flags=re.S | re.M) + return {slug(m.group(2)) for m in re.finditer(r"^(#{1,6})\s+(.*)$", text, re.M)} + + +def links(rel): + for m in re.finditer(r"\[[^\]]*\]\(([^)\s]+)\)", strip_code(read(rel)).replace("\n", " ")): + target = m.group(1) + if not re.match(r"[a-z]+:", target): # skip https:, mailto: + yield target + + +class DocsLinksTest(unittest.TestCase): + def test_relative_links_and_anchors_resolve(self): + problems = [] + for page in PAGES: + for target in links(page): + path, _, fragment = target.partition("#") + dest = os.path.normpath(os.path.join(os.path.dirname(page), path)) if path else page + if not os.path.exists(os.path.join(REPO, dest)): + problems.append(f"{page}: {target} -> {dest} does not exist") + elif fragment and dest.endswith(".md") and fragment not in anchors(dest): + problems.append(f"{page}: {target} -> no heading #{fragment} in {dest}") + self.assertEqual(problems, []) + + def test_every_docs_page_is_linked_from_the_readme(self): + linked = {os.path.normpath(t.partition("#")[0]) for t in links("README.md")} + self.assertEqual(sorted(set(PAGES[1:]) - linked), []) + + def test_every_docs_page_links_back_to_the_readme(self): + for page in PAGES[1:]: + self.assertIn("../README.md", set(links(page)), page) + + def test_slug_matches_how_gitea_names_anchors(self): + self.assertEqual(slug("Heartbeat: is kernelwatch itself running?"), + "heartbeat-is-kernelwatch-itself-running") + self.assertEqual(slug("Scripting: `kernelwatch status`"), "scripting-kernelwatch-status") + self.assertEqual(slug("Authelia (forward auth)"), "authelia-forward-auth") + + +if __name__ == "__main__": + unittest.main()