test_opentofu_from_zero_split.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  1. # SPDX-License-Identifier: Apache-2.0
  2. """The OpenTofu-from-zero lesson is a short hub and parts, none of them long (issue #562).
  3. The lesson was one page of about 1,070 lines. It is now a hub that keeps the page name and URL, the intro and the
  4. banners, plus numbered part pages. The hub must list every part, each part must link back to the hub and stay under
  5. a line cap, the manifest must hold the pages as one series with the hub first, and every exercise the hub indexes must
  6. point at a part that really holds that heading. The text itself moved verbatim; that is checked against a record of the
  7. old page in tests/test_stale_sibling_statements.py.
  8. """
  9. import re
  10. import sys
  11. from pathlib import Path
  12. sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "scripts"))
  13. import gen_wiki_nav as gwn
  14. from wikitext import page_text
  15. ROOT = Path(__file__).resolve().parent.parent
  16. WIKI = ROOT / "docs" / "wiki"
  17. STEM = "OpenTofu-From-Zero"
  18. SERIES = "OpenTofu from zero"
  19. MAX_PART_LINES = 450
  20. PARTS = (
  21. f"{STEM}-Part-1-Concepts-Install-and-Exercises-1-and-2",
  22. f"{STEM}-Part-2-Exercises-3-to-6-Plan-Symbols-State-Count-and-Modules",
  23. f"{STEM}-Part-3-Exercise-7-Build-and-Destroy-a-Bunch",
  24. f"{STEM}-Part-4-Build-Break-Defend-the-Checkpoint-and-Claims",
  25. )
  26. LINK = re.compile(r"\]\(([A-Za-z0-9_-]+)\.md(?:#([^)]*))?\)")
  27. def part_names(wiki: Path) -> list[str]:
  28. return sorted(p.stem for p in wiki.glob(f"{STEM}-Part-*.md"))
  29. def split_problems(wiki: Path, cap: int = MAX_PART_LINES, expected: tuple[str, ...] = PARTS) -> list[str]:
  30. """Every way the split is broken: a part missing or extra, one the hub does not list, a long part, no way back."""
  31. parts = part_names(wiki)
  32. problems = []
  33. if tuple(parts) != tuple(sorted(expected)):
  34. problems.append(f"parts are {parts}, expected {sorted(expected)}")
  35. hub = page_text(wiki / f"{STEM}.md")
  36. linked = [name for name, _ in LINK.findall(hub)]
  37. for name in parts:
  38. if name not in linked:
  39. problems.append(f"the hub does not list {name}")
  40. text = page_text(wiki / f"{name}.md")
  41. lines = len(text.splitlines())
  42. if lines > cap:
  43. problems.append(f"{name} is {lines} lines, over {cap}")
  44. if f"]({STEM}.md)" not in text:
  45. problems.append(f"{name} does not link back to the hub")
  46. return problems
  47. def part_headings(name: str) -> set[str]:
  48. return {gwn.slug(h) for h in re.findall(r"^#{2,3} (.+)$", page_text(WIKI / f"{name}.md"), re.MULTILINE)}
  49. def test_the_hub_lists_every_part_and_each_part_is_short():
  50. assert part_names(WIKI) == sorted(PARTS)
  51. assert split_problems(WIKI) == []
  52. def test_every_exercise_the_hub_indexes_is_a_heading_of_the_part_it_names():
  53. hub = page_text(WIKI / f"{STEM}.md")
  54. index = [(n, a) for n, a in LINK.findall(hub) if n.startswith(f"{STEM}-Part-") and a]
  55. assert len(index) >= 7, "the hub indexes fewer than the seven exercises"
  56. for name, anchor in index:
  57. assert anchor in part_headings(name), (name, anchor)
  58. def dangling_anchors(text: str, headings: set[str]) -> list[str]:
  59. """Same-page anchors that are not a heading of the page: after a split they must be links to the part instead."""
  60. return [a for a in re.findall(r"\]\(#([^)]+)\)", text) if a not in headings]
  61. def test_every_link_into_the_lesson_names_the_part_that_holds_the_heading():
  62. """Other pages' links (the glossary, the native-IaC page) and the lesson's own cross-references name the part."""
  63. headings = {name: part_headings(name) for name in PARTS}
  64. checked = 0
  65. for path in WIKI.glob("*.md"):
  66. for name, anchor in LINK.findall(page_text(path)):
  67. if not anchor or not (name == STEM or name in PARTS):
  68. continue
  69. checked += 1
  70. assert name != STEM or anchor == "the-parts", (path.name, anchor)
  71. assert name == STEM or anchor in headings[name], (path.name, name, anchor)
  72. assert checked >= 25, "the guard collected too few links into the lesson"
  73. for name in PARTS:
  74. assert dangling_anchors(page_text(WIKI / f"{name}.md"), headings[name]) == [], name
  75. def test_the_same_page_anchor_check_bites():
  76. assert dangling_anchors("see [x](#clean-up)", {"clean-up"}) == []
  77. assert dangling_anchors("see [x](#clean-up)", {"other"}) == ["clean-up"]
  78. def bare_exercise_refs(text: str, held: set[int]) -> list[int]:
  79. """Exercise numbers named in plain text (not as a link) that this part does not hold: they must be links."""
  80. prose = re.sub(r"```.*?```", "", text, flags=re.DOTALL)
  81. prose = re.sub(r"^#{1,6} .*$", "", prose, flags=re.MULTILINE)
  82. prose = re.sub(r"\[[^\]]*\]\([^)]*\)", "", prose)
  83. return sorted({int(n) for n in re.findall(r"\bExercises? (\d+)\b", prose)} - held)
  84. def held_exercises(text: str) -> set[int]:
  85. return {int(n) for n in re.findall(r"^### Exercise (\d+)\b", text, re.MULTILINE)}
  86. def test_an_exercise_that_lives_in_another_part_is_always_a_link():
  87. seen = 0
  88. for name in PARTS:
  89. text = page_text(WIKI / f"{name}.md")
  90. assert bare_exercise_refs(text, held_exercises(text)) == [], name
  91. seen += len(held_exercises(text))
  92. assert seen == 7, "the parts hold seven exercises between them"
  93. def test_the_bare_exercise_check_bites():
  94. assert bare_exercise_refs("as in Exercise 2 (same HCL)", {3}) == [2]
  95. assert bare_exercise_refs("as in [Exercise 2](Part-1.md#x) (same HCL)", {3}) == []
  96. assert bare_exercise_refs("as in Exercise 3 here", {3}) == []
  97. def test_the_hub_links_the_centerpiece_script_and_each_part_names_where_it_is_in_the_lesson():
  98. hub = page_text(WIKI / f"{STEM}.md")
  99. assert f"]({PARTS[2]}.md#exercise-7-centerpiece-build-and-destroy-a-bunch)" in hub
  100. for i, name in enumerate(PARTS, start=1):
  101. assert f"Part {i} of 4 of [" in page_text(WIKI / f"{name}.md"), name
  102. def test_the_manifest_holds_hub_and_parts_as_one_series_hub_first():
  103. m = gwn.read_manifest(ROOT)
  104. group = next(g["id"] for g in gwn.groups_of(m) if any(e["page"] == STEM for e in gwn.entries(m, g["id"])))
  105. rows = [e for e in gwn.entries(m, group) if e.get("series") == SERIES]
  106. assert [e["page"] for e in rows] == [STEM, *PARTS]
  107. assert all(len(e["title"]) <= 80 for e in rows[1:])
  108. def test_every_part_starts_with_a_title_then_a_section_heading():
  109. for name in PARTS:
  110. headings = re.findall(r"^(#{1,3}) ", page_text(WIKI / f"{name}.md"), re.MULTILINE)
  111. assert headings[:2] == ["#", "##"], name
  112. def test_the_split_check_bites(tmp_path):
  113. wiki = tmp_path
  114. for name in (STEM, *(f"{STEM}-Part-{i}-X" for i in (1, 2, 3))):
  115. body = "\n".join(["line"] * 10)
  116. (wiki / f"{name}.md").write_text(f"# t\n\n{body}\n[hub]({STEM}.md)\n", encoding="utf-8")
  117. hub = "\n".join(f"- [p]({STEM}-Part-{i}-X.md)" for i in (1, 2, 3))
  118. (wiki / f"{STEM}.md").write_text(f"# hub\n\n{hub}\n", encoding="utf-8")
  119. fake = tuple(f"{STEM}-Part-{i}-X" for i in (1, 2, 3))
  120. assert split_problems(wiki, expected=fake) == []
  121. assert any("expected" in p for p in split_problems(wiki, expected=(*fake, f"{STEM}-Part-4-X")))
  122. (wiki / f"{STEM}-Part-2-X.md").write_text("\n".join(["line"] * 500) + f"\n[hub]({STEM}.md)\n", encoding="utf-8")
  123. assert any("over" in p for p in split_problems(wiki, expected=fake))
  124. (wiki / f"{STEM}.md").write_text(f"# hub\n\n- [p]({STEM}-Part-1-X.md)\n", encoding="utf-8")
  125. assert any("does not list" in p for p in split_problems(wiki, expected=fake))
  126. (wiki / f"{STEM}-Part-3-X.md").write_text("# t\n", encoding="utf-8")
  127. assert any("does not link back" in p for p in split_problems(wiki, expected=fake))