test_wiki_page_nav.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  1. # SPDX-License-Identifier: Apache-2.0
  2. """The navigation blocks on every published wiki page (issue #417, moved to the publish step by issue #521).
  3. The blocks are not stored in docs/wiki/*.md any more: the publish step (scripts/gen_wiki_nav.py --publish-to, which
  4. scripts/gen-wiki.sh runs) renders them from docs/wiki/_nav.yaml. The tests below therefore read the PUBLISHED pages
  5. for everything about the blocks, and the repository pages only to prove they carry none.
  6. What is proved:
  7. - no page file carries a navigation block, and --check fails when one does (the guard bites);
  8. - every published page that should carry the blocks has exactly one top and one bottom block, in the right places, and
  9. Home, Contents and the pages another generator writes whole have none;
  10. - the published pages are the repository pages plus exactly those blocks, and publishing twice changes nothing;
  11. - previous and next agree (a page's next has it as previous), the first and last pages have one neighbor, and
  12. a group with no reading order has none;
  13. - related targets exist, are not the page itself and do not repeat; the fallback rule is deterministic and
  14. never repeats a neighbor;
  15. - the generator only ever adds the two blocks: stripping them gives the original page back, and a banner stays
  16. where it was;
  17. - the checks bite: hostile manifests and hand-edited blocks are refused.
  18. """
  19. import copy
  20. import re
  21. import sys
  22. import tempfile
  23. from pathlib import Path
  24. import pytest
  25. import yaml
  26. ROOT = Path(__file__).resolve().parent.parent
  27. sys.path.insert(0, str(ROOT / "scripts"))
  28. import gen_wiki_nav as gwn
  29. WIKI = ROOT / "docs" / "wiki"
  30. PAGE_LINK = re.compile(r"\]\(([A-Za-z0-9_-]+)\.md(?:#[^)]*)?\)")
  31. PREV = re.compile(r"Previous: \[[^\]]*\]\(([A-Za-z0-9_-]+)\.md\)")
  32. NEXT = re.compile(r"Next: \[[^\]]*\]\(([A-Za-z0-9_-]+)\.md\)")
  33. def manifest() -> dict:
  34. return gwn.read_manifest(ROOT)
  35. def text_of(name: str) -> str:
  36. return (WIKI / f"{name}.md").read_text(encoding="utf-8")
  37. def pages_with_nav() -> list[str]:
  38. return sorted(n for n in gwn.wiki_pages(ROOT) if gwn.has_page_nav(n, text_of(n)))
  39. _PUBLISHED: dict[str, str] = {}
  40. def published(name: str) -> str:
  41. """The text of a page as the publish step writes it (blocks added, links not yet rewritten for the wiki)."""
  42. if not _PUBLISHED:
  43. with tempfile.TemporaryDirectory() as out:
  44. assert gwn.publish_pages(ROOT, Path(out)) >= 140
  45. _PUBLISHED.update({p.stem: p.read_text(encoding="utf-8") for p in Path(out).glob("*.md")})
  46. return _PUBLISHED[name]
  47. def block(text: str, where: str) -> str:
  48. begin, end = gwn.NAV_BEGIN.format(where=where), gwn.NAV_END.format(where=where)
  49. assert text.count(begin) == 1 and text.count(end) == 1, where
  50. return text.split(begin, 1)[1].split(end, 1)[0]
  51. def small() -> tuple[dict, dict[str, str]]:
  52. """A manifest with a three-page numbered track, a sorted group and an unordered group, and page texts for it."""
  53. m = {
  54. "groups": [
  55. {"id": "start", "title": "Start here", "order": "curated"},
  56. {"id": "core", "title": "Core path", "order": "curated", "numbered": True, "open": True},
  57. {"id": "trk", "title": "Track X", "order": "curated", "numbered": True, "track": True},
  58. {"id": "loose", "title": "Loose pages", "order": "curated"},
  59. {"id": "ref", "title": "Reference", "order": "sorted"},
  60. ],
  61. "pages": {
  62. "start": [
  63. {"page": "Home", "title": "Home", "audience": "everyone", "desc": "The front door."},
  64. {"page": "Contents", "title": "Contents", "audience": "everyone", "desc": "Index."},
  65. ],
  66. "core": [{"page": "One", "title": "One", "audience": "newcomer", "desc": "The first page."}],
  67. "trk": [
  68. {"page": "T1", "title": "Tee one", "audience": "learner", "desc": "x", "subgroup": "Early"},
  69. {"page": "T2", "title": "Tee two", "audience": "learner", "desc": "x", "subgroup": "Early"},
  70. {"page": "T3", "title": "Tee three", "audience": "learner", "desc": "x", "subgroup": "Late"},
  71. {"page": "T4", "title": "Tee four", "audience": "learner", "desc": "x", "subgroup": "Late"},
  72. {"page": "T5", "title": "Tee five", "audience": "learner", "desc": "x"},
  73. ],
  74. "loose": [
  75. {"page": "L1", "title": "Loose one", "audience": "learner", "desc": "x"},
  76. {"page": "L2", "title": "Loose two", "audience": "learner", "desc": "x"},
  77. ],
  78. "ref": [
  79. {"page": "Zed", "title": "Zed", "audience": "everyone", "desc": "x"},
  80. {"page": "Apple", "title": "Apple", "audience": "everyone", "desc": "x"},
  81. ],
  82. },
  83. }
  84. m["pages"]["ref"].sort(key=lambda e: e["title"])
  85. texts = {
  86. n: f"# {n}\n\n> **Banner.**\n\n> Unfamiliar word? See the Glossary.\n\nBody of {n}.\n\n| A | B |\n|---|---|\n| 1 | 2 |\n"
  87. for n in ("One", "T1", "T2", "T3", "T4", "T5", "L1", "L2", "Zed", "Apple")
  88. }
  89. texts["Home"] = f"# Home\n\n{gwn.HOME_BEGIN}\n{gwn.HOME_END}\n"
  90. texts["Contents"] = "# Contents\n"
  91. return m, texts
  92. def write_tree(root: Path, m: dict, texts: dict[str, str]) -> Path:
  93. wiki = root / "docs" / "wiki"
  94. wiki.mkdir(parents=True)
  95. (wiki / "_nav.yaml").write_text(yaml.safe_dump(m), encoding="utf-8")
  96. for name, text in texts.items():
  97. (wiki / f"{name}.md").write_text(text, encoding="utf-8")
  98. return wiki
  99. # -- the committed wiki ------------------------------------------------------------------------
  100. def test_no_page_file_carries_a_navigation_block():
  101. names = sorted(gwn.wiki_pages(ROOT))
  102. assert len(names) >= 140, f"the guard collected only {len(names)} pages"
  103. for name in names:
  104. assert not gwn.has_nav_blocks(text_of(name)), f"{name}: the block is written by the publish step, not stored"
  105. assert gwn.check(ROOT) == []
  106. def test_the_no_stored_block_guard_bites():
  107. name = pages_with_nav()[0]
  108. assert gwn.has_nav_blocks(published(name)) # a page with the blocks is seen as carrying them
  109. assert not gwn.has_nav_blocks(text_of(name))
  110. def test_every_published_page_that_should_have_the_blocks_has_exactly_one_top_and_one_bottom():
  111. names = pages_with_nav()
  112. assert len(names) >= 140, f"the guard collected only {len(names)} pages"
  113. for name in names:
  114. text = published(name)
  115. for where in gwn.NAV_PLACES:
  116. assert text.count(gwn.NAV_BEGIN.format(where=where)) == 1, f"{name}: {where} BEGIN"
  117. assert text.count(gwn.NAV_END.format(where=where)) == 1, f"{name}: {where} END"
  118. assert text.index(gwn.NAV_BEGIN.format(where="top")) < text.index(gwn.NAV_BEGIN.format(where="bottom")), name
  119. assert text.rstrip("\n").endswith(gwn.NAV_END.format(where="bottom")), f"{name}: the bottom block is not last"
  120. def test_home_contents_and_the_pages_other_generators_write_have_no_block():
  121. exempt = sorted(set(gwn.wiki_pages(ROOT)) - set(pages_with_nav()))
  122. assert {"Home", "Contents"} <= set(exempt)
  123. assert exempt == ["Contents", "Home", "Project-Status", "Repository-Growth", "Settings-Reference"]
  124. for name in exempt:
  125. assert "GENERATED PAGE NAV" not in published(name), name
  126. assert published(name) == text_of(name), f"{name}: published unchanged"
  127. def test_a_published_page_is_the_repository_page_plus_exactly_the_two_blocks():
  128. m = manifest()
  129. for name in pages_with_nav():
  130. text = text_of(name)
  131. assert gwn.strip_page_nav(published(name)) == text, name
  132. assert published(name) == gwn.apply_page_nav(text, gwn.render_page_nav(m, name)), name
  133. again = gwn.apply_page_nav(published(name), gwn.render_page_nav(copy.deepcopy(m), name))
  134. assert again == published(name), f"{name}: not idempotent"
  135. def test_the_published_page_is_the_stripped_page_with_its_contents_and_navigation_blocks_put_back():
  136. from wikitext import page_text
  137. m = manifest()
  138. for name in pages_with_nav():
  139. stripped = page_text(WIKI / f"{name}.md")
  140. assert "GENERATED PAGE NAV" not in stripped, name
  141. # Issue #441: the longest pages also carry a contents block, which page_text() strips too, so the
  142. # round trip puts back the contents block (kept in the file), then the navigation blocks (publish only).
  143. in_file = gwn.apply_page_contents(stripped, gwn.render_page_contents(stripped))
  144. assert in_file == text_of(name), name
  145. assert gwn.apply_page_nav(in_file, gwn.render_page_nav(m, name)) == published(name), name
  146. def test_previous_and_next_agree_within_every_group_with_a_reading_order():
  147. m = manifest()
  148. prev, nxt, ordered_groups = {}, {}, 0
  149. for name in pages_with_nav():
  150. top = block(published(name), "top")
  151. found_p, found_n = PREV.findall(top), NEXT.findall(top)
  152. assert len(found_p) <= 1 and len(found_n) <= 1, name
  153. prev[name], nxt[name] = (found_p or [None])[0], (found_n or [None])[0]
  154. assert block(published(name), "bottom").count("Previous:") == len(found_p), name
  155. for g in gwn.groups_of(m):
  156. names = [e["page"] for e in gwn.entries(m, g["id"])]
  157. if not gwn.has_reading_order(g):
  158. assert all(prev.get(n) is None and nxt.get(n) is None for n in names), g["id"]
  159. continue
  160. ordered_groups += 1
  161. # The order includes pages that carry no block themselves (the status and growth pages): they are still
  162. # neighbors, so they are linked, and only the pages that carry a block are checked.
  163. for i, n in enumerate(names):
  164. if n in prev:
  165. assert nxt[n] == (names[i + 1] if i + 1 < len(names) else None), n
  166. assert prev[n] == (names[i - 1] if i else None), n
  167. if names[-1] in prev:
  168. assert nxt[names[-1]] is None, g["id"]
  169. if names[0] in prev:
  170. assert prev[names[0]] is None, g["id"]
  171. assert ordered_groups >= 7, "the guard saw too few groups with a reading order"
  172. def test_a_page_next_has_it_as_previous():
  173. pairs = 0
  174. for name in pages_with_nav():
  175. following = NEXT.findall(block(published(name), "top"))
  176. if following and following[0] in pages_with_nav(): # a followed page that carries no block has no Previous to check
  177. assert PREV.findall(block(published(following[0]), "top")) == [name], name
  178. pairs += 1
  179. assert pairs >= 100
  180. def test_the_breadcrumb_names_home_the_group_and_the_page_without_linking_the_page():
  181. m = manifest()
  182. homes = {e["page"]: (g, e) for g in gwn.groups_of(m) for e in gwn.entries(m, g["id"])}
  183. for name in pages_with_nav():
  184. g, e = homes[name]
  185. top = block(published(name), "top")
  186. assert f"[Home](Home.md) > [{g['title']}](Contents.md#{gwn.slug(g['title'])}) > {e['title']}\n" in top, name
  187. assert f"]({name}.md)" not in top, f"{name}: links itself"
  188. def test_only_the_heading_and_leading_quote_banners_come_before_the_top_block():
  189. seen = 0
  190. for name in pages_with_nav():
  191. text = published(name)
  192. head = text.split(gwn.NAV_BEGIN.format(where="top"), 1)[0].splitlines()
  193. assert head[0].startswith("# "), name
  194. assert all(not line.strip() or line.startswith(">") for line in head[1:]), f"{name}: prose before the top block"
  195. seen += sum(1 for line in head if line.startswith("> **"))
  196. assert seen >= 20, "the guard found too few status banners above the block"
  197. def test_every_related_target_exists_and_is_not_the_page_itself():
  198. m = manifest()
  199. names = set(gwn.all_page_names(m))
  200. shown = 0
  201. for name in pages_with_nav():
  202. part = block(published(name), "bottom").split("Related pages:", 1)
  203. if len(part) == 1:
  204. continue
  205. targets = PAGE_LINK.findall(part[1])
  206. shown += 1
  207. assert targets and len(targets) == len(set(targets)) <= gwn.RELATED_MAX, name
  208. assert name not in targets and set(targets) <= names, name
  209. assert shown >= 140
  210. def test_the_pages_the_brief_names_have_a_hand_chosen_related_list():
  211. m = manifest()
  212. chosen = {e["page"]: e["related"] for g in ("privacy", "grc") for e in m["pages"][g] if "related" in e}
  213. for gid in ("privacy", "grc"):
  214. for e in m["pages"][gid]:
  215. assert e["page"] in chosen, f"{e['page']} has no related list"
  216. assert gwn.RELATED_MIN <= len(chosen[e["page"]]) <= gwn.RELATED_MAX
  217. # 29: every page in the privacy and GRC tracks has a hand-chosen list. The HSM lesson (issue #464), the paper wallets lesson (issue #431),
  218. # the OPSEC lesson (issue #389), the onion service lab (issue #391) and the hands-on Whonix and Qubes lesson
  219. # (issue #372) each joined the privacy track with a list of its own. The count stays an exact equality: a page
  220. # that joins either track without a list still fails.
  221. assert len(chosen) == 29, "every page in the privacy and GRC tracks has a hand-chosen list"
  222. # Jumping between sections works: the lists cross the track boundary both ways.
  223. by_group = {e["page"]: gid for gid, pages in m["pages"].items() for e in pages}
  224. assert any(by_group[r] != "privacy" for p, rel in chosen.items() if by_group[p] == "privacy" for r in rel)
  225. assert any(by_group[r] != "grc" for p, rel in chosen.items() if by_group[p] == "grc" for r in rel)
  226. assert any(by_group[r] == "grc" for p, rel in chosen.items() if by_group[p] == "privacy" for r in rel)
  227. assert any(by_group[r] == "privacy" for p, rel in chosen.items() if by_group[p] == "grc" for r in rel)
  228. def test_the_continuity_pages_link_each_other_and_the_cia_triad():
  229. m = manifest()
  230. related = {e["page"]: e["related"] for e in m["pages"]["grc"] if "related" in e}
  231. raid = next(p for p in related if p.startswith("RAID-Levels"))
  232. bcp = next(p for p in related if p.startswith("Business-Continuity"))
  233. cia = next(p for p in related if p.startswith("The-CIA-Triad"))
  234. backups = [p for p in related if p.startswith("Backups-")]
  235. assert len(backups) == 2
  236. assert {bcp, *backups} <= set(related[raid]) and cia in related[raid]
  237. assert {raid, *backups} <= set(related[bcp])
  238. assert bcp in related[backups[0]] and bcp in related[backups[1]]
  239. # -- the fallback rule and the rendering -------------------------------------------------------
  240. def test_the_fallback_is_the_nearest_pages_of_the_same_subgroup_first_and_never_a_neighbor():
  241. m, _ = small()
  242. # T2: previous T1, next T3 are shown beside it; the other subgroup pages follow by distance.
  243. assert gwn.related_for(m, "T2") == ["T4", "T5"]
  244. # T3: subgroup Late, neighbors T2 and T4 are left out; same-subgroup candidates are none, so the rest by distance.
  245. assert gwn.related_for(m, "T3") == ["T1", "T5"]
  246. # T1 is first: no previous, so only T2 is a neighbor.
  247. assert gwn.related_for(m, "T1") == ["T3", "T4", "T5"]
  248. for p in ("T1", "T2", "T3", "T4", "T5"):
  249. got = gwn.related_for(m, p)
  250. assert p not in got and len(got) == len(set(got)) <= gwn.RELATED_FALLBACK
  251. def test_the_fallback_in_a_group_without_a_reading_order_keeps_every_other_page():
  252. m, _ = small()
  253. assert gwn.related_for(m, "L1") == ["L2"]
  254. assert gwn.related_for(m, "One") == [] # a group of one page has none
  255. assert "Related pages" not in gwn.render_page_nav(m, "One")["bottom"]
  256. def test_a_related_list_replaces_the_fallback_in_the_order_written():
  257. m, _ = small()
  258. next(e for e in m["pages"]["trk"] if e["page"] == "T2")["related"] = ["Zed", "One", "L1"]
  259. assert gwn.related_for(m, "T2") == ["Zed", "One", "L1"]
  260. bottom = gwn.render_page_nav(m, "T2")["bottom"]
  261. assert bottom.index("(Zed.md)") < bottom.index("(One.md)") < bottom.index("(L1.md)")
  262. def test_first_and_last_pages_have_one_neighbor_and_an_unordered_group_has_none():
  263. m, _ = small()
  264. first, last, mid = (gwn.render_page_nav(m, p)["top"] for p in ("T1", "T5", "T3"))
  265. assert "Previous:" not in first and "Next: [Tee two](T2.md)" in first
  266. assert "Next:" not in last and "Previous: [Tee four](T4.md)" in last
  267. assert "Previous: [Tee two](T2.md) / Next: [Tee four](T4.md)" in mid
  268. loose = gwn.render_page_nav(m, "L1")["top"]
  269. assert "Previous:" not in loose and "Next:" not in loose and "Loose one" in loose
  270. only = gwn.render_page_nav(m, "One")["top"]
  271. assert "Previous:" not in only and "Next:" not in only
  272. def test_a_sorted_group_goes_in_title_order():
  273. m, _ = small()
  274. assert "Next: [Zed](Zed.md)" in gwn.render_page_nav(m, "Apple")["top"]
  275. assert "Previous: [Apple](Apple.md)" in gwn.render_page_nav(m, "Zed")["top"]
  276. def test_the_bottom_block_lists_the_track_by_subgroup_and_does_not_link_the_page_itself():
  277. m, _ = small()
  278. bottom = gwn.render_page_nav(m, "T3")["bottom"]
  279. assert "- Early: [Tee one](T1.md) / [Tee two](T2.md)" in bottom
  280. assert "- Late: **Tee three** / [Tee four](T4.md)" in bottom
  281. assert "- Also here: [Tee five](T5.md)" in bottom
  282. assert "(T3.md)" not in bottom
  283. assert "In this track:" in bottom and "In this group:" not in bottom
  284. assert "In this group:" in gwn.render_page_nav(m, "L1")["bottom"]
  285. # -- inserting, rewriting and the checks bite ---------------------------------------------------
  286. def test_the_blocks_go_after_the_banners_and_stripping_them_gives_the_page_back():
  287. m, texts = small()
  288. for name in ("T2", "L1"):
  289. original = texts[name]
  290. done = gwn.apply_page_nav(original, gwn.render_page_nav(m, name))
  291. head = done.split(gwn.NAV_BEGIN.format(where="top"), 1)[0]
  292. assert head == f"# {name}\n\n> **Banner.**\n\n> Unfamiliar word? See the Glossary.\n\n"
  293. assert done.rstrip("\n").endswith(gwn.NAV_END.format(where="bottom"))
  294. assert gwn.strip_page_nav(done) == original
  295. assert gwn.apply_page_nav(done, gwn.render_page_nav(m, name)) == done
  296. @pytest.mark.parametrize(
  297. "original",
  298. [
  299. "# Plain\n\nProse straight after the heading.\n\n## Section\n\ntext\n",
  300. "# Plain\n\n> **Banner only.**\n\nProse.\n",
  301. "# Plain\n",
  302. "# Plain\n\n> only a quote\n",
  303. "# Plain\nprose with no blank line\n",
  304. ],
  305. )
  306. def test_insertion_handles_every_page_shape_and_only_adds_the_two_blocks(original):
  307. m, _ = small()
  308. done = gwn.apply_page_nav(original, gwn.render_page_nav(m, "T2"))
  309. assert done.count("BEGIN GENERATED PAGE NAV") == 2 and done.endswith("\n")
  310. assert gwn.strip_page_nav(done).split() == original.split() # same words in the same order
  311. for line in original.splitlines():
  312. assert line in done.splitlines()
  313. def test_a_page_with_a_missing_or_repeated_marker_is_refused():
  314. m, texts = small()
  315. blocks = gwn.render_page_nav(m, "T2")
  316. done = gwn.apply_page_nav(texts["T2"], blocks)
  317. with pytest.raises(ValueError, match="marker"):
  318. gwn.apply_page_nav(done.replace(gwn.NAV_END.format(where="top"), ""), blocks)
  319. with pytest.raises(ValueError, match="marker"):
  320. gwn.apply_page_nav(done + blocks["top"], blocks)
  321. with pytest.raises(ValueError, match="heading"):
  322. gwn.apply_page_nav("no heading here\n", blocks)
  323. swapped = done.replace("PAGE NAV top", "PAGE NAV TMP").replace("PAGE NAV bottom", "PAGE NAV top").replace("PAGE NAV TMP", "PAGE NAV bottom")
  324. with pytest.raises(ValueError, match="top|before"):
  325. gwn.apply_page_nav(swapped, blocks)
  326. def publish(root: Path, out: Path) -> dict[str, str]:
  327. assert gwn.main(["--root", str(root), "--publish-to", str(out)]) == 0
  328. return {p.stem: p.read_text(encoding="utf-8") for p in out.glob("*.md")}
  329. def test_a_stored_block_fails_check_and_a_rerun_removes_it_without_touching_the_page(tmp_path):
  330. m, texts = small()
  331. wiki = write_tree(tmp_path, m, texts)
  332. (wiki / "Home.md").write_text(f"# Home\n\n{gwn.HOME_BEGIN}\n{gwn.HOME_END}\n", encoding="utf-8")
  333. assert gwn.main(["--root", str(tmp_path), "--check"]) == 1 # Contents, sidebar and Home map not written yet
  334. assert gwn.main(["--root", str(tmp_path)]) == 0
  335. assert gwn.main(["--root", str(tmp_path), "--check"]) == 0
  336. page = wiki / "T3.md"
  337. assert page.read_text(encoding="utf-8") == texts["T3"] # the generator adds nothing to a short page
  338. # A navigation block left in a page (a branch from before issue #521) is refused, then removed by a rerun.
  339. stored = gwn.apply_page_nav(texts["T3"], gwn.render_page_nav(m, "T3"))
  340. page.write_text(stored, encoding="utf-8")
  341. assert gwn.main(["--root", str(tmp_path), "--check"]) == 1
  342. assert gwn.main(["--root", str(tmp_path)]) == 0
  343. assert page.read_text(encoding="utf-8") == texts["T3"]
  344. assert gwn.main(["--root", str(tmp_path), "--check"]) == 0
  345. def test_a_manifest_edit_changes_the_published_pages_and_no_page_file(tmp_path):
  346. m, texts = small()
  347. wiki = write_tree(tmp_path, m, texts)
  348. assert gwn.main(["--root", str(tmp_path)]) == 0
  349. files = {p.name: p.read_bytes() for p in wiki.iterdir() if p.is_file()}
  350. before = publish(tmp_path, tmp_path / "out1")
  351. assert "Tee two" in before["T3"] and "Tee second" not in before["T3"]
  352. m2 = copy.deepcopy(m)
  353. next(e for e in m2["pages"]["trk"] if e["page"] == "T2")["title"] = "Tee second"
  354. (wiki / "_nav.yaml").write_text(yaml.safe_dump(m2), encoding="utf-8")
  355. files["_nav.yaml"] = (wiki / "_nav.yaml").read_bytes()
  356. # Contents and the sidebar show the title, so --check wants them rewritten; the page files stay as they are.
  357. assert gwn.main(["--root", str(tmp_path), "--check"]) == 1
  358. assert gwn.main(["--root", str(tmp_path)]) == 0
  359. after = publish(tmp_path, tmp_path / "out2")
  360. assert "Tee second" in after["T3"] and "Tee second" in after["T1"]
  361. changed = sorted(p.name for p in wiki.iterdir() if p.is_file() and p.read_bytes() != files.get(p.name))
  362. assert changed == ["Contents.md", "Home.md", "_Sidebar.md"], changed # the registries only, never a lesson page
  363. assert gwn.strip_page_nav(after["T3"]) == texts["T3"]
  364. def test_publishing_an_invalid_manifest_or_a_page_without_a_heading_fails_and_writes_nothing_wrong(tmp_path, capsys):
  365. m, texts = small()
  366. texts["T4"] = "no heading at all\n"
  367. write_tree(tmp_path, m, texts)
  368. assert gwn.main(["--root", str(tmp_path), "--publish-to", str(tmp_path / "out")]) == 1
  369. assert "heading" in capsys.readouterr().err or not (tmp_path / "out" / "T4.md").exists()
  370. m2, texts2 = small()
  371. m2["pages"]["trk"].append({"page": "Ghost", "title": "Ghost", "audience": "learner", "desc": "x"})
  372. root2 = tmp_path / "second"
  373. root2.mkdir()
  374. write_tree(root2, m2, texts2)
  375. assert gwn.main(["--root", str(root2), "--publish-to", str(root2 / "out")]) == 1
  376. assert "Ghost" in capsys.readouterr().err
  377. assert not (root2 / "out").exists()
  378. def test_running_the_generator_twice_changes_nothing(tmp_path):
  379. m, texts = small()
  380. wiki = write_tree(tmp_path, m, texts)
  381. assert gwn.main(["--root", str(tmp_path)]) == 0
  382. first = {p.name: p.read_bytes() for p in wiki.iterdir() if p.is_file()}
  383. assert gwn.main(["--root", str(tmp_path)]) == 0
  384. assert {p.name: p.read_bytes() for p in wiki.iterdir() if p.is_file()} == first
  385. assert gwn.HOME_BEGIN.encode() in first["Home.md"]
  386. assert b"GENERATED PAGE NAV" not in first["Home.md"] and b"GENERATED PAGE NAV" not in first["Contents.md"]
  387. def test_a_page_another_generator_writes_whole_is_left_alone(tmp_path):
  388. m, texts = small()
  389. m["pages"]["ref"].append({"page": "Status", "title": "Status", "audience": "everyone", "desc": "x"})
  390. m["pages"]["ref"].sort(key=lambda e: e["title"])
  391. generated = "<!-- GENERATED from elsewhere. -->\n\n# Status\n\nrows\n"
  392. texts["Status"] = generated
  393. wiki = write_tree(tmp_path, m, texts)
  394. assert gwn.main(["--root", str(tmp_path)]) == 0
  395. assert (wiki / "Status.md").read_text(encoding="utf-8") == generated
  396. assert "(Status.md)" in gwn.render_page_nav(m, "Apple")["top"] # but it is still a neighbor
  397. def test_a_page_that_cannot_take_the_blocks_stops_the_run_before_anything_is_written(tmp_path, capsys):
  398. m, texts = small()
  399. texts["T4"] = "no heading at all\n"
  400. wiki = write_tree(tmp_path, m, texts)
  401. before = {p.name: p.read_bytes() for p in wiki.iterdir() if p.is_file()}
  402. assert gwn.main(["--root", str(tmp_path)]) == 1
  403. assert "heading" in capsys.readouterr().err
  404. assert {p.name: p.read_bytes() for p in wiki.iterdir() if p.is_file()} == before
  405. def test_strip_page_nav_removes_exactly_the_blocks():
  406. m, texts = small()
  407. done = gwn.apply_page_nav(texts["T1"], gwn.render_page_nav(m, "T1"))
  408. assert "GENERATED PAGE NAV" in done and "](T2.md)" in done
  409. assert gwn.strip_page_nav(done) == texts["T1"]
  410. assert gwn.strip_page_nav(texts["T1"]) == texts["T1"]
  411. assert "](T2.md)" not in gwn.strip_page_nav(done)
  412. # -- the related field is validated --------------------------------------------------------------
  413. def with_related(related) -> dict:
  414. m, _ = small()
  415. next(e for e in m["pages"]["trk"] if e["page"] == "T2")["related"] = related
  416. return m
  417. PAGES = {"One", "T1", "T2", "T3", "T4", "T5", "L1", "L2", "Zed", "Apple", "Home", "Contents"}
  418. def test_the_small_manifest_is_valid_with_a_good_related_list():
  419. assert gwn.validate(small()[0], PAGES) == []
  420. assert gwn.validate(with_related(["T1", "T3", "Zed"]), PAGES) == []
  421. assert gwn.validate(with_related(["T1", "T3", "T4", "T5", "Zed", "Apple"]), PAGES) == []
  422. @pytest.mark.parametrize(
  423. ("related", "needle"),
  424. [
  425. (["T1", "T3", "Nowhere"], "'Nowhere' is not a page"),
  426. (["T1", "T2", "T3"], "lists the page itself"),
  427. (["T1", "T3", "T3"], "lists 'T3' twice"),
  428. (["T1", "T3"], "needs 3 to 6"),
  429. (["T1", "T3", "T4", "T5", "Zed", "Apple", "L1"], "needs 3 to 6"),
  430. ("T1", "must be a list"),
  431. ([1, 2, 3], "must be a list"),
  432. ],
  433. )
  434. def test_a_bad_related_list_is_refused(related, needle):
  435. assert any(needle in p for p in gwn.validate(with_related(related), PAGES))
  436. def test_a_related_list_cannot_name_a_special_or_missing_page():
  437. problems = gwn.validate(with_related(["T1", "_Sidebar", "T3"]), PAGES)
  438. assert any("'_Sidebar' is not a page" in p for p in problems)