| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162 |
- # SPDX-License-Identifier: Apache-2.0
- """The OpenTofu-from-zero lesson is a short hub and parts, none of them long (issue #562).
- 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
- banners, plus numbered part pages. The hub must list every part, each part must link back to the hub and stay under
- a line cap, the manifest must hold the pages as one series with the hub first, and every exercise the hub indexes must
- point at a part that really holds that heading. The text itself moved verbatim; that is checked against a record of the
- old page in tests/test_stale_sibling_statements.py.
- """
- import re
- import sys
- from pathlib import Path
- sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "scripts"))
- import gen_wiki_nav as gwn
- from wikitext import page_text
- ROOT = Path(__file__).resolve().parent.parent
- WIKI = ROOT / "docs" / "wiki"
- STEM = "OpenTofu-From-Zero"
- SERIES = "OpenTofu from zero"
- MAX_PART_LINES = 450
- PARTS = (
- f"{STEM}-Part-1-Concepts-Install-and-Exercises-1-and-2",
- f"{STEM}-Part-2-Exercises-3-to-6-Plan-Symbols-State-Count-and-Modules",
- f"{STEM}-Part-3-Exercise-7-Build-and-Destroy-a-Bunch",
- f"{STEM}-Part-4-Build-Break-Defend-the-Checkpoint-and-Claims",
- )
- LINK = re.compile(r"\]\(([A-Za-z0-9_-]+)\.md(?:#([^)]*))?\)")
- def part_names(wiki: Path) -> list[str]:
- return sorted(p.stem for p in wiki.glob(f"{STEM}-Part-*.md"))
- def split_problems(wiki: Path, cap: int = MAX_PART_LINES, expected: tuple[str, ...] = PARTS) -> list[str]:
- """Every way the split is broken: a part missing or extra, one the hub does not list, a long part, no way back."""
- parts = part_names(wiki)
- problems = []
- if tuple(parts) != tuple(sorted(expected)):
- problems.append(f"parts are {parts}, expected {sorted(expected)}")
- hub = page_text(wiki / f"{STEM}.md")
- linked = [name for name, _ in LINK.findall(hub)]
- for name in parts:
- if name not in linked:
- problems.append(f"the hub does not list {name}")
- text = page_text(wiki / f"{name}.md")
- lines = len(text.splitlines())
- if lines > cap:
- problems.append(f"{name} is {lines} lines, over {cap}")
- if f"]({STEM}.md)" not in text:
- problems.append(f"{name} does not link back to the hub")
- return problems
- def part_headings(name: str) -> set[str]:
- return {gwn.slug(h) for h in re.findall(r"^#{2,3} (.+)$", page_text(WIKI / f"{name}.md"), re.MULTILINE)}
- def test_the_hub_lists_every_part_and_each_part_is_short():
- assert part_names(WIKI) == sorted(PARTS)
- assert split_problems(WIKI) == []
- def test_every_exercise_the_hub_indexes_is_a_heading_of_the_part_it_names():
- hub = page_text(WIKI / f"{STEM}.md")
- index = [(n, a) for n, a in LINK.findall(hub) if n.startswith(f"{STEM}-Part-") and a]
- assert len(index) >= 7, "the hub indexes fewer than the seven exercises"
- for name, anchor in index:
- assert anchor in part_headings(name), (name, anchor)
- def dangling_anchors(text: str, headings: set[str]) -> list[str]:
- """Same-page anchors that are not a heading of the page: after a split they must be links to the part instead."""
- return [a for a in re.findall(r"\]\(#([^)]+)\)", text) if a not in headings]
- def test_every_link_into_the_lesson_names_the_part_that_holds_the_heading():
- """Other pages' links (the glossary, the native-IaC page) and the lesson's own cross-references name the part."""
- headings = {name: part_headings(name) for name in PARTS}
- checked = 0
- for path in WIKI.glob("*.md"):
- for name, anchor in LINK.findall(page_text(path)):
- if not anchor or not (name == STEM or name in PARTS):
- continue
- checked += 1
- assert name != STEM or anchor == "the-parts", (path.name, anchor)
- assert name == STEM or anchor in headings[name], (path.name, name, anchor)
- assert checked >= 25, "the guard collected too few links into the lesson"
- for name in PARTS:
- assert dangling_anchors(page_text(WIKI / f"{name}.md"), headings[name]) == [], name
- def test_the_same_page_anchor_check_bites():
- assert dangling_anchors("see [x](#clean-up)", {"clean-up"}) == []
- assert dangling_anchors("see [x](#clean-up)", {"other"}) == ["clean-up"]
- def bare_exercise_refs(text: str, held: set[int]) -> list[int]:
- """Exercise numbers named in plain text (not as a link) that this part does not hold: they must be links."""
- prose = re.sub(r"```.*?```", "", text, flags=re.DOTALL)
- prose = re.sub(r"^#{1,6} .*$", "", prose, flags=re.MULTILINE)
- prose = re.sub(r"\[[^\]]*\]\([^)]*\)", "", prose)
- return sorted({int(n) for n in re.findall(r"\bExercises? (\d+)\b", prose)} - held)
- def held_exercises(text: str) -> set[int]:
- return {int(n) for n in re.findall(r"^### Exercise (\d+)\b", text, re.MULTILINE)}
- def test_an_exercise_that_lives_in_another_part_is_always_a_link():
- seen = 0
- for name in PARTS:
- text = page_text(WIKI / f"{name}.md")
- assert bare_exercise_refs(text, held_exercises(text)) == [], name
- seen += len(held_exercises(text))
- assert seen == 7, "the parts hold seven exercises between them"
- def test_the_bare_exercise_check_bites():
- assert bare_exercise_refs("as in Exercise 2 (same HCL)", {3}) == [2]
- assert bare_exercise_refs("as in [Exercise 2](Part-1.md#x) (same HCL)", {3}) == []
- assert bare_exercise_refs("as in Exercise 3 here", {3}) == []
- def test_the_hub_links_the_centerpiece_script_and_each_part_names_where_it_is_in_the_lesson():
- hub = page_text(WIKI / f"{STEM}.md")
- assert f"]({PARTS[2]}.md#exercise-7-centerpiece-build-and-destroy-a-bunch)" in hub
- for i, name in enumerate(PARTS, start=1):
- assert f"Part {i} of 4 of [" in page_text(WIKI / f"{name}.md"), name
- def test_the_manifest_holds_hub_and_parts_as_one_series_hub_first():
- m = gwn.read_manifest(ROOT)
- group = next(g["id"] for g in gwn.groups_of(m) if any(e["page"] == STEM for e in gwn.entries(m, g["id"])))
- rows = [e for e in gwn.entries(m, group) if e.get("series") == SERIES]
- assert [e["page"] for e in rows] == [STEM, *PARTS]
- assert all(len(e["title"]) <= 80 for e in rows[1:])
- def test_every_part_starts_with_a_title_then_a_section_heading():
- for name in PARTS:
- headings = re.findall(r"^(#{1,3}) ", page_text(WIKI / f"{name}.md"), re.MULTILINE)
- assert headings[:2] == ["#", "##"], name
- def test_the_split_check_bites(tmp_path):
- wiki = tmp_path
- for name in (STEM, *(f"{STEM}-Part-{i}-X" for i in (1, 2, 3))):
- body = "\n".join(["line"] * 10)
- (wiki / f"{name}.md").write_text(f"# t\n\n{body}\n[hub]({STEM}.md)\n", encoding="utf-8")
- hub = "\n".join(f"- [p]({STEM}-Part-{i}-X.md)" for i in (1, 2, 3))
- (wiki / f"{STEM}.md").write_text(f"# hub\n\n{hub}\n", encoding="utf-8")
- fake = tuple(f"{STEM}-Part-{i}-X" for i in (1, 2, 3))
- assert split_problems(wiki, expected=fake) == []
- assert any("expected" in p for p in split_problems(wiki, expected=(*fake, f"{STEM}-Part-4-X")))
- (wiki / f"{STEM}-Part-2-X.md").write_text("\n".join(["line"] * 500) + f"\n[hub]({STEM}.md)\n", encoding="utf-8")
- assert any("over" in p for p in split_problems(wiki, expected=fake))
- (wiki / f"{STEM}.md").write_text(f"# hub\n\n- [p]({STEM}-Part-1-X.md)\n", encoding="utf-8")
- assert any("does not list" in p for p in split_problems(wiki, expected=fake))
- (wiki / f"{STEM}-Part-3-X.md").write_text("# t\n", encoding="utf-8")
- assert any("does not link back" in p for p in split_problems(wiki, expected=fake))
|