test_build_destroy_split.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. # SPDX-License-Identifier: Apache-2.0
  2. """The build and destroy lesson is a short hub and parts, none of them long (issue #562).
  3. The lesson was one page of about 1,300 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: the parts are compared with a record of
  7. the pre-split page (its headings with their line counts and a digest of every fenced code line), not with themselves.
  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 test_stale_sibling_statements import split_inventory
  15. from wikitext import page_text
  16. ROOT = Path(__file__).resolve().parent.parent
  17. WIKI = ROOT / "docs" / "wiki"
  18. STEM = "Build-and-Destroy-Stack-Per-Service"
  19. SERIES = "Build and destroy a stack per service"
  20. MAX_PART_LINES = 450
  21. PARTS = (
  22. f"{STEM}-Part-1-Why-and-How-Stacks-Are-Split-and-the-Lab-Script",
  23. f"{STEM}-Part-2-The-PowerShell-Lab-and-Exercises-1-to-4",
  24. f"{STEM}-Part-3-Exercises-5-to-8-and-the-Cloud-Lab",
  25. f"{STEM}-Part-4-Spacelift-Break-Detect-Defend-and-Claims",
  26. )
  27. LINK = re.compile(r"\]\(([A-Za-z0-9_-]+)\.md(?:#([^)]*))?\)")
  28. def part_names(wiki: Path) -> list[str]:
  29. return sorted(p.stem for p in wiki.glob(f"{STEM}-Part-*.md"))
  30. def split_problems(wiki: Path, cap: int = MAX_PART_LINES, expected: tuple[str, ...] = PARTS) -> list[str]:
  31. """Every way the split is broken: a part missing or extra, one the hub does not list, a long part, no way back."""
  32. parts = part_names(wiki)
  33. problems = []
  34. if tuple(parts) != tuple(sorted(expected)):
  35. problems.append(f"parts are {parts}, expected {sorted(expected)}")
  36. hub = page_text(wiki / f"{STEM}.md")
  37. linked = [name for name, _ in LINK.findall(hub)]
  38. for name in parts:
  39. if name not in linked:
  40. problems.append(f"the hub does not list {name}")
  41. text = page_text(wiki / f"{name}.md")
  42. lines = len(text.splitlines())
  43. if lines > cap:
  44. problems.append(f"{name} is {lines} lines, over {cap}")
  45. if f"]({STEM}.md)" not in text:
  46. problems.append(f"{name} does not link back to the hub")
  47. return problems
  48. def test_the_hub_lists_every_part_and_each_part_is_short():
  49. assert part_names(WIKI) == sorted(PARTS)
  50. assert split_problems(WIKI) == []
  51. def test_every_exercise_the_hub_indexes_is_a_heading_of_the_part_it_names():
  52. hub = page_text(WIKI / f"{STEM}.md")
  53. index = [(n, a) for n, a in LINK.findall(hub) if n.startswith(f"{STEM}-Part-") and a]
  54. assert len(index) >= 8, "the hub indexes fewer than the eight exercises"
  55. for name, anchor in index:
  56. text = page_text(WIKI / f"{name}.md")
  57. assert anchor in {gwn.slug(h) for h in re.findall(r"^#{2,3} (.+)$", text, re.MULTILINE)}, (name, anchor)
  58. def test_the_manifest_holds_hub_and_parts_as_one_series_hub_first():
  59. m = gwn.read_manifest(ROOT)
  60. group = next(g["id"] for g in gwn.groups_of(m) if any(e["page"] == STEM for e in gwn.entries(m, g["id"])))
  61. rows = [e for e in gwn.entries(m, group) if e.get("series") == SERIES]
  62. assert [e["page"] for e in rows] == [STEM, *PARTS]
  63. def test_the_split_check_bites(tmp_path):
  64. wiki = tmp_path
  65. for name in (STEM, *(f"{STEM}-Part-{i}-X" for i in (1, 2, 3))):
  66. body = "\n".join(["line"] * 10)
  67. (wiki / f"{name}.md").write_text(f"# t\n\n{body}\n[hub]({STEM}.md)\n", encoding="utf-8")
  68. hub = "\n".join(f"- [p]({STEM}-Part-{i}-X.md)" for i in (1, 2, 3))
  69. (wiki / f"{STEM}.md").write_text(f"# hub\n\n{hub}\n", encoding="utf-8")
  70. fake = tuple(f"{STEM}-Part-{i}-X" for i in (1, 2, 3))
  71. assert split_problems(wiki, expected=fake) == []
  72. assert any("expected" in p for p in split_problems(wiki, expected=(*fake, f"{STEM}-Part-4-X")))
  73. (wiki / f"{STEM}-Part-2-X.md").write_text("\n".join(["line"] * 500) + f"\n[hub]({STEM}.md)\n", encoding="utf-8")
  74. assert any("over" in p for p in split_problems(wiki, expected=fake))
  75. (wiki / f"{STEM}.md").write_text(f"# hub\n\n- [p]({STEM}-Part-1-X.md)\n", encoding="utf-8")
  76. assert any("does not list" in p for p in split_problems(wiki, expected=fake))
  77. (wiki / f"{STEM}-Part-3-X.md").write_text("# t\n", encoding="utf-8")
  78. assert any("does not link back" in p for p in split_problems(wiki, expected=fake))
  79. # Record of the old single page (before the split into parts, issue #562), taken from the commit before it
  80. # (git show ce040cc:docs/wiki/Build-and-Destroy-Stack-Per-Service.md): each `##`/`###` heading with its non-blank lines.
  81. SPLIT_SECTIONS = (
  82. ('What you will be able to do', 8),
  83. ('What the wiki already says (and the gap)', 6),
  84. ('Why one stack per service', 10),
  85. ('What splitting costs', 10),
  86. ('What the layout looks like', 8),
  87. ('Layout conventions worth copying', 10),
  88. ('Passing values between stacks', 9),
  89. ('Build order and reverse destroy order', 4),
  90. ('Tag everything, so teardown can be proven', 5),
  91. ('Cost counters: a number per stack, and one for the whole', 5),
  92. ('How this project does it', 8),
  93. ('If you are terraforming an entire infrastructure', 10),
  94. ('Lessons-learned: what makes a destroy fail or leave a bill', 10),
  95. ('Free path: five stacks in a scratch folder', 0),
  96. ('Cost and teardown (read first)', 11),
  97. ('What the lab is', 1),
  98. ('Step 0: write the lab', 393),
  99. ('Exercise 1: predict before you build', 12),
  100. ('Exercise 2: build all five, in order', 22),
  101. ('Exercise 3: destroy all five, in reverse, and prove it', 24),
  102. ('Exercise 4: five full cycles', 13),
  103. ('Exercise 5: destroy in the wrong order, on purpose', 39),
  104. ('Exercise 6: a forgotten resource and an untagged one', 30),
  105. ('Exercise 7: read how this project pins its addresses (read-only)', 13),
  106. ('Optional: the same shape on your own cloud account', 2),
  107. ('Cost and teardown (read first)', 77),
  108. ('The files', 152),
  109. ('Exercise 8: build and destroy the cloud set', 22),
  110. ('Optional: run the same stacks through Spacelift', 1),
  111. ('Build, break, detect, evade, defend', 10),
  112. ('Flip the board', 7),
  113. ('Common mistakes', 8),
  114. ('Claims register', 20),
  115. )
  116. SPLIT_CODE_DIGEST = '31bdfbc61e6a7eac07fa0ab31298ddbac654722403e94ee276c171834a75a3c7'
  117. def part_inventory(texts: list[str]) -> tuple[list[tuple[str, int]], str]:
  118. """The sections of the parts, with the headings the split added folded into the section they continue."""
  119. sections, digest = split_inventory(texts)
  120. merged: list[list] = []
  121. for heading, count in sections:
  122. if heading.startswith("Free path, continued") and merged:
  123. merged[-1][1] += count
  124. else:
  125. merged.append([heading, count])
  126. return [(h, n) for h, n in merged], digest
  127. def part_texts() -> list[str]:
  128. return [page_text(WIKI / f"{name}.md") for name in PARTS]
  129. def test_the_parts_still_hold_every_section_of_the_old_page_once():
  130. sections, digest = part_inventory(part_texts())
  131. assert tuple(sections) == SPLIT_SECTIONS
  132. assert digest == SPLIT_CODE_DIGEST
  133. assert sum(h.startswith("Exercise ") for h, _ in sections) == 8
  134. def test_the_inventory_bites_when_a_section_is_lost_repeated_or_a_code_line_changes():
  135. texts = part_texts()
  136. base = part_inventory(texts)
  137. cut = re.sub(r"### Exercise 5:.*?(?=### Exercise 6:)", "", texts[2], flags=re.DOTALL)
  138. assert cut != texts[2]
  139. assert part_inventory([texts[0], texts[1], cut, texts[3]]) != base
  140. assert part_inventory([*texts, texts[0]]) != base
  141. changed = texts[2].replace("```bash", "```bash\n# extra", 1)
  142. assert changed != texts[2]
  143. assert part_inventory([texts[0], texts[1], changed, texts[3]])[1] != base[1]