test_gen_wiki.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. """Tests for scripts/gen-wiki.sh, the generate step of the Wiki workflow.
  2. The script copies docs/wiki/ into an output directory and rewrites relative
  3. page links for the flat GitHub wiki. It never pushes; git-your-ship-together's
  4. wiki-publish.yml does that from main only.
  5. """
  6. import re
  7. import subprocess
  8. from pathlib import Path
  9. import pytest
  10. ROOT = Path(__file__).resolve().parent.parent
  11. SCRIPT = ROOT / "scripts" / "gen-wiki.sh"
  12. WIKI = ROOT / "docs" / "wiki"
  13. RELATIVE_MD_LINK = re.compile(r"\]\([A-Za-z0-9_-]+\.md(#[^)]*)?\)")
  14. # Every run gets this environment, not the caller's: a workflow in a fork sets
  15. # GITHUB_REPOSITORY, and the raw image URL depends on it.
  16. CLEAN_ENV = {"PATH": "/usr/bin:/bin"}
  17. def run(*args: str) -> subprocess.CompletedProcess:
  18. return subprocess.run(
  19. ["bash", str(SCRIPT), *args],
  20. capture_output=True,
  21. text=True,
  22. check=False,
  23. env=CLEAN_ENV,
  24. )
  25. @pytest.fixture(scope="module")
  26. def tree(tmp_path_factory) -> Path:
  27. out = tmp_path_factory.mktemp("wiki-out")
  28. result = run(str(out))
  29. assert result.returncode == 0, result.stderr
  30. return out
  31. def test_every_page_is_written(tree):
  32. assert sorted(p.name for p in tree.glob("*.md")) == sorted(
  33. p.name for p in WIKI.glob("*.md")
  34. )
  35. def test_relative_page_links_lose_their_md_suffix(tree):
  36. for page in tree.glob("*.md"):
  37. assert not RELATIVE_MD_LINK.search(page.read_text()), (
  38. f"{page.name} still links to a .md page"
  39. )
  40. def test_home_links_become_wiki_page_names(tree):
  41. assert "](Twingate.md)" in (WIKI / "Home.md").read_text()
  42. assert "](Twingate)" in (tree / "Home.md").read_text()
  43. def test_a_link_with_an_anchor_keeps_the_anchor(tmp_path):
  44. """The script finds docs/wiki from its own location, so a copy in a scratch tree reads that tree."""
  45. (tmp_path / "scripts").mkdir()
  46. (tmp_path / "docs" / "wiki").mkdir(parents=True)
  47. copy = tmp_path / "scripts" / "gen-wiki.sh"
  48. copy.write_text(SCRIPT.read_text())
  49. (tmp_path / "docs" / "wiki" / "Page.md").write_text(
  50. "[a](Other.md#some-section) [b](Other.md) [c](https://example.org/x.md)\n"
  51. )
  52. out = tmp_path / "out"
  53. result = subprocess.run(
  54. ["bash", str(copy), str(out)],
  55. capture_output=True,
  56. text=True,
  57. check=False,
  58. env=CLEAN_ENV,
  59. )
  60. assert result.returncode == 0, result.stderr
  61. assert (
  62. (out / "Page.md").read_text()
  63. == "[a](Other#some-section) [b](Other) [c](https://example.org/x.md)\n"
  64. )
  65. def test_an_empty_source_is_refused(tmp_path):
  66. (tmp_path / "scripts").mkdir()
  67. (tmp_path / "docs" / "wiki").mkdir(parents=True)
  68. copy = tmp_path / "scripts" / "gen-wiki.sh"
  69. copy.write_text(SCRIPT.read_text())
  70. result = subprocess.run(
  71. ["bash", str(copy), str(tmp_path / "out")],
  72. capture_output=True,
  73. text=True,
  74. check=False,
  75. env=CLEAN_ENV,
  76. )
  77. assert result.returncode == 1
  78. assert "no pages" in result.stderr
  79. def test_absolute_links_are_left_alone(tree):
  80. for page in WIKI.glob("*.md"):
  81. for url in re.findall(r"\]\((https?://[^)]+)\)", page.read_text()):
  82. assert url in (tree / page.name).read_text(), (
  83. f"{page.name}: absolute link {url} was changed"
  84. )
  85. def test_the_complete_output_set_is_pages_plus_images(tree):
  86. expected = {p.name for p in WIKI.glob("*.md")} | {p.name for p in (WIKI / "images").iterdir()}
  87. assert {p.name for p in tree.iterdir()} == expected
  88. assert not (tree / "images").exists()
  89. def test_images_are_copied_flat(tree):
  90. images = sorted((WIKI / "images").iterdir())
  91. assert images, "no images examined"
  92. for img in images:
  93. assert (tree / img.name).read_bytes() == img.read_bytes()
  94. def scratch(tmp_path, pages, images=None, env=None, out="out", prepare=None):
  95. """A scratch copy of the script with its own docs/wiki; returns (result, out path)."""
  96. (tmp_path / "scripts").mkdir(parents=True, exist_ok=True)
  97. wiki = tmp_path / "docs" / "wiki"
  98. (wiki / "images").mkdir(parents=True, exist_ok=True)
  99. copy = tmp_path / "scripts" / "gen-wiki.sh"
  100. copy.write_text(SCRIPT.read_text())
  101. for name, text in pages.items():
  102. (wiki / name).write_text(text)
  103. for name, data in (images or {}).items():
  104. (wiki / "images" / name).write_bytes(data)
  105. if prepare:
  106. prepare(tmp_path)
  107. target = tmp_path / out
  108. result = subprocess.run(
  109. ["bash", str(copy), str(target)],
  110. capture_output=True,
  111. text=True,
  112. check=False,
  113. env={**CLEAN_ENV, **(env or {})},
  114. )
  115. return result, target
  116. @pytest.mark.parametrize(
  117. "value",
  118. [
  119. "x/\\1)#g\ne touch PWNED\n#",
  120. "a/b\nc/d",
  121. "a/b c",
  122. "a/b#c",
  123. "a/b/c",
  124. "/b",
  125. "a/",
  126. "noslash",
  127. "../b",
  128. "a/..",
  129. "a/b$(touch PWNED)",
  130. "a/b`touch PWNED`",
  131. "a/b;touch PWNED",
  132. "a/b&c",
  133. "a/b\\c",
  134. ],
  135. )
  136. @pytest.mark.parametrize("variable", ["GITHUB_REPOSITORY", "WIKI_REPO"])
  137. def test_a_hostile_repository_value_is_refused_before_anything_runs(tmp_path, variable, value):
  138. pages = {"Page.md": "![alt text here](images/a.png)\n"}
  139. result, out = scratch(tmp_path, pages, {"a.png": b"x"}, env={variable: value})
  140. assert result.returncode == 2, result.stderr
  141. assert "owner/repository" in result.stderr
  142. assert not out.exists()
  143. assert not list(tmp_path.rglob("PWNED"))
  144. def test_wiki_repo_is_the_fallback_and_github_repository_wins(tmp_path):
  145. pages = {"Page.md": "![alt text here](images/a.png)\n"}
  146. result, out = scratch(tmp_path / "a", pages, {"a.png": b"x"}, env={"WIKI_REPO": "fall/back"})
  147. assert result.returncode == 0, result.stderr
  148. assert "wiki/fall/back/a.png)" in (out / "Page.md").read_text()
  149. both = {"WIKI_REPO": "fall/back", "GITHUB_REPOSITORY": "actions/value"}
  150. result, out = scratch(tmp_path / "b", pages, {"a.png": b"x"}, env=both)
  151. assert "wiki/actions/value/a.png)" in (out / "Page.md").read_text()
  152. def test_a_valid_but_unusual_repository_name_is_accepted(tmp_path):
  153. pages = {"Page.md": "![alt text here](images/a.png)\n"}
  154. result, out = scratch(tmp_path, pages, {"a.png": b"x"}, env={"GITHUB_REPOSITORY": "Some-Org_1/repo.name-2"})
  155. assert result.returncode == 0, result.stderr
  156. assert "wiki/Some-Org_1/repo.name-2/a.png)" in (out / "Page.md").read_text()
  157. def test_a_symlinked_image_is_refused_and_nothing_is_published(tmp_path):
  158. secret = tmp_path / "private.png"
  159. secret.write_bytes(b"PRIVATE")
  160. def link(root):
  161. (root / "docs" / "wiki" / "images" / "leak.png").symlink_to(secret)
  162. result, out = scratch(tmp_path, {"Page.md": "![a private diagram](images/leak.png)\n"}, prepare=link)
  163. assert result.returncode == 1
  164. assert "symlink" in result.stderr
  165. assert not out.exists()
  166. def test_a_symlinked_images_directory_or_page_is_refused(tmp_path):
  167. outside = tmp_path / "outside"
  168. outside.mkdir()
  169. (outside / "x.png").write_bytes(b"x")
  170. def link_dir(root):
  171. import shutil
  172. shutil.rmtree(root / "docs" / "wiki" / "images")
  173. (root / "docs" / "wiki" / "images").symlink_to(outside)
  174. result, out = scratch(tmp_path / "a", {"Page.md": "text\n"}, prepare=link_dir)
  175. assert result.returncode == 1 and "symlink" in result.stderr and not out.exists()
  176. def link_page(root):
  177. (root / "docs" / "wiki" / "Linked.md").symlink_to(outside / "x.png")
  178. result, out = scratch(tmp_path / "b", {"Page.md": "text\n"}, prepare=link_page)
  179. assert result.returncode == 1 and "symlink" in result.stderr and not out.exists()
  180. @pytest.mark.parametrize("name", ["photo.jpg", "photo.jpeg", "notes.txt", "A.PNG.bak", ".hidden"])
  181. def test_only_png_files_may_be_in_the_images_directory(tmp_path, name):
  182. result, out = scratch(tmp_path, {"Page.md": "text\n"}, {name: b"x"})
  183. assert result.returncode == 1
  184. assert "only .png" in result.stderr
  185. assert not out.exists()
  186. def test_a_subdirectory_in_images_is_refused(tmp_path):
  187. def sub(root):
  188. (root / "docs" / "wiki" / "images" / "deep").mkdir()
  189. result, _out = scratch(tmp_path, {"Page.md": "text\n"}, prepare=sub)
  190. assert result.returncode == 1 and "not a regular file" in result.stderr
  191. def test_a_non_empty_output_directory_is_refused_and_left_alone(tmp_path):
  192. def stale(root):
  193. (root / "out").mkdir()
  194. (root / "out" / "unexpected.bin").write_text("secret")
  195. (root / "out" / "Deleted-Page.md").write_text("stale")
  196. result, out = scratch(tmp_path, {"Page.md": "text\n"}, prepare=stale)
  197. assert result.returncode == 2
  198. assert "not empty" in result.stderr
  199. assert sorted(p.name for p in out.iterdir()) == ["Deleted-Page.md", "unexpected.bin"]
  200. assert (out / "unexpected.bin").read_text() == "secret"
  201. def test_an_empty_existing_output_directory_is_fine_and_a_file_is_not(tmp_path):
  202. result, out = scratch(tmp_path / "a", {"Page.md": "text\n"}, prepare=lambda r: (r / "out").mkdir())
  203. assert result.returncode == 0, result.stderr
  204. assert [p.name for p in out.iterdir()] == ["Page.md"]
  205. result, _ = scratch(tmp_path / "b", {"Page.md": "text\n"}, prepare=lambda r: (r / "out").write_text("x"))
  206. assert result.returncode == 2 and "not a plain directory" in result.stderr
  207. def test_image_links_are_rewritten_only_in_prose(tmp_path):
  208. raw = "https://raw.githubusercontent.com/wiki/o/r/a.png"
  209. page = (
  210. "before ![alt text here](images/a.png) after\n"
  211. "\n"
  212. "inline `![alt text here](images/a.png)` code and ![alt text here](images/a.png) prose\n"
  213. "\n"
  214. "```markdown\n"
  215. "![alt text here](images/a.png)\n"
  216. "```\n"
  217. "\n"
  218. "~~~\n"
  219. "![alt text here](images/a.png)\n"
  220. "~~~\n"
  221. "\n"
  222. " ![alt text here](images/a.png)\n"
  223. "\n"
  224. "- list item\n"
  225. "\n"
  226. " ![alt text here](images/a.png)\n"
  227. "\n"
  228. "again ![alt text here](images/a.png)\n"
  229. )
  230. result, out = scratch(tmp_path, {"Page.md": page}, {"a.png": b"x"}, env={"GITHUB_REPOSITORY": "o/r"})
  231. assert result.returncode == 0, result.stderr
  232. lines = (out / "Page.md").read_text().splitlines()
  233. img = "![alt text here](images/a.png)"
  234. rewritten = f"![alt text here]({raw})"
  235. assert lines[0] == f"before {rewritten} after"
  236. assert lines[2] == f"inline `{img}` code and {rewritten} prose"
  237. assert lines[5] == img # inside a backtick fence
  238. assert lines[9] == img # inside a tilde fence
  239. assert lines[12] == f" {img}" # indented code block
  240. assert lines[16] == f" {rewritten}" # nested under a list item, so prose
  241. assert lines[18] == f"again {rewritten}"
  242. def test_image_links_become_raw_wiki_urls(tree):
  243. page = (tree / "Threat-Dragon-Exercise.md").read_text()
  244. assert "](images/" not in page
  245. assert (
  246. "](https://raw.githubusercontent.com/wiki/ChiefGyk3D/Clouds-Against-Humanity/"
  247. "threat-dragon-stride-diagram.png)" in page
  248. )
  249. def test_raw_url_follows_the_repository_in_a_fork(tmp_path):
  250. (tmp_path / "scripts").mkdir()
  251. (tmp_path / "docs" / "wiki" / "images").mkdir(parents=True)
  252. copy = tmp_path / "scripts" / "gen-wiki.sh"
  253. copy.write_text(SCRIPT.read_text())
  254. (tmp_path / "docs" / "wiki" / "images" / "a-b.png").write_bytes(b"x")
  255. (tmp_path / "docs" / "wiki" / "Page.md").write_text(
  256. "![alt text here](images/a-b.png) ![x](https://example.org/i.png) ![y](images/sub/c.png)\n"
  257. )
  258. out = tmp_path / "out"
  259. result = subprocess.run(
  260. ["bash", str(copy), str(out)],
  261. capture_output=True,
  262. text=True,
  263. check=False,
  264. env={**CLEAN_ENV, "GITHUB_REPOSITORY": "someone/their-fork"},
  265. )
  266. assert result.returncode == 0, result.stderr
  267. assert (out / "a-b.png").read_bytes() == b"x"
  268. assert (out / "Page.md").read_text() == (
  269. "![alt text here](https://raw.githubusercontent.com/wiki/someone/their-fork/a-b.png)"
  270. " ![x](https://example.org/i.png) ![y](images/sub/c.png)\n"
  271. )
  272. def test_no_argument_is_a_usage_error():
  273. result = run()
  274. assert result.returncode == 2
  275. assert "usage" in result.stderr
  276. # -- the page navigation is rendered here, not stored in the pages (issue #521) -------------------
  277. def page_named(prefix: str) -> str:
  278. found = sorted(p.stem for p in WIKI.glob(f"{prefix}*.md"))
  279. assert len(found) == 1, found
  280. return found[0]
  281. def test_published_pages_show_previous_next_and_the_track_count_but_the_sources_do_not(tree):
  282. import sys
  283. sys.path.insert(0, str(ROOT / "scripts"))
  284. import gen_wiki_nav as gwn
  285. manifest = gwn.read_manifest(ROOT)
  286. home = gwn.page_home(manifest)
  287. checked = 0
  288. for prefix in ("Kubernetes-for-Beginners", "Cron-Systemd-Timers"):
  289. name = page_named(prefix)
  290. group, ordered, index = home[name]
  291. source = (WIKI / f"{name}.md").read_text()
  292. published = (tree / f"{name}.md").read_text()
  293. assert "Previous:" not in source and "In this track:" not in source and "GENERATED PAGE NAV" not in source
  294. prev_page, next_page = ordered[index - 1]["page"], ordered[index + 1]["page"]
  295. assert f"Previous: [{ordered[index - 1]['title']}]({prev_page})" in published
  296. assert f"Next: [{ordered[index + 1]['title']}]({next_page})" in published
  297. assert f"In this track: [{group['title']}](Contents#{gwn.slug(group['title'])}), {len(ordered)} pages" in published
  298. nav_lines = [ln for ln in published.splitlines() if ln.startswith("Previous: [")]
  299. assert len(nav_lines) == 2 and nav_lines[0] == nav_lines[1] # the top block and the bottom block agree
  300. assert "Related pages:" in published
  301. checked += 1
  302. assert checked == 2
  303. def test_every_published_page_that_takes_navigation_has_both_blocks_and_the_others_have_none(tree):
  304. with_blocks = [p for p in tree.glob("*.md") if "BEGIN GENERATED PAGE NAV top" in p.read_text()]
  305. assert len(with_blocks) >= 140, len(with_blocks)
  306. for name in ("Home", "Contents", "_Sidebar"):
  307. assert "GENERATED PAGE NAV" not in (tree / f"{name}.md").read_text(), name
  308. for page in with_blocks:
  309. text = page.read_text()
  310. assert text.count("BEGIN GENERATED PAGE NAV") == 2 and text.count("END GENERATED PAGE NAV") == 2, page.name
  311. def test_a_tree_with_a_manifest_it_cannot_render_is_refused_not_published_without_navigation(tmp_path):
  312. result, _ = scratch(
  313. tmp_path,
  314. {"Page.md": "# Page\n"},
  315. prepare=lambda root: (root / "docs" / "wiki" / "_nav.yaml").write_text("groups: []\n"),
  316. )
  317. assert result.returncode != 0
  318. assert "navigation" in result.stderr