test_readme_layout.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. """The README's layout block and script list match the tree.
  2. A layout that lists last month's directories sends a new reader to the wrong
  3. place, so these tests fail when a script, a top-level directory or a module or
  4. stack directory exists without a mention, and when the README names a script
  5. that is gone. A script that deliberately has no README line goes in
  6. UNLISTED_SCRIPTS with the reason, so the exception is visible in review.
  7. """
  8. import re
  9. import subprocess
  10. from pathlib import Path
  11. ROOT = Path(__file__).resolve().parent.parent
  12. README = (ROOT / "README.md").read_text()
  13. # script path (relative to the repository root) -> why the README does not list it
  14. UNLISTED_SCRIPTS: dict[str, str] = {}
  15. # Top-level directories that exist in a working copy but are not part of the repository.
  16. UNTRACKED_DIRS = {".git", ".venv", ".claude", ".pytest_cache", ".ruff_cache", "__pycache__"}
  17. def layout_block() -> str:
  18. match = re.search(r"^## Layout\n+```\n(.*?)\n```", README, re.DOTALL | re.MULTILINE)
  19. assert match, "README.md has no fenced block under '## Layout'"
  20. return match.group(1)
  21. def tracked_top_level_dirs() -> set[str]:
  22. try:
  23. out = subprocess.run(
  24. ["git", "-C", str(ROOT), "ls-files"],
  25. capture_output=True,
  26. text=True,
  27. check=True,
  28. ).stdout.split("\n")
  29. return {line.split("/", 1)[0] for line in out if "/" in line}
  30. except (OSError, subprocess.CalledProcessError):
  31. return {
  32. p.name
  33. for p in ROOT.iterdir()
  34. if p.is_dir() and p.name not in UNTRACKED_DIRS
  35. }
  36. def scripts() -> list[str]:
  37. found = []
  38. for path in sorted((ROOT / "scripts").rglob("*")):
  39. if path.is_file() and "__pycache__" not in path.parts and path.suffix != ".pyc":
  40. found.append(path.relative_to(ROOT).as_posix())
  41. return found
  42. def test_every_script_is_in_the_readme_or_has_a_reason():
  43. missing = [
  44. s for s in scripts() if s not in README and s not in UNLISTED_SCRIPTS
  45. ]
  46. assert not missing, f"scripts not mentioned in README.md: {missing}"
  47. def test_unlisted_script_reasons_are_current():
  48. stale = [s for s in UNLISTED_SCRIPTS if s not in scripts() or s in README]
  49. assert not stale, f"UNLISTED_SCRIPTS entries to remove: {stale}"
  50. assert all(reason.strip() for reason in UNLISTED_SCRIPTS.values())
  51. def test_the_readme_names_no_script_that_is_gone():
  52. named = set(re.findall(r"\bscripts/[A-Za-z0-9_./-]*[A-Za-z0-9_]\.(?:py|sh)\b", README))
  53. gone = sorted(n for n in named if not (ROOT / n).is_file())
  54. assert not gone, f"README.md names scripts that do not exist: {gone}"
  55. def test_every_top_level_directory_is_in_the_layout_block():
  56. block = layout_block()
  57. missing = [
  58. d
  59. for d in sorted(tracked_top_level_dirs())
  60. if not re.search(rf"^\s+{re.escape(d)}/", block, re.MULTILINE)
  61. ]
  62. assert not missing, f"top-level directories missing from the README layout: {missing}"
  63. # Layout convention for directories below modules/ and stacks/: a directory is
  64. # covered when the layout block names its full path (`modules/aws/vpc`), or when
  65. # a brace form names it under its parent (`modules/aws/{vpc,firewall}` covers
  66. # modules/aws/vpc and modules/aws/firewall, and the parent modules/aws). Naming
  67. # only a parent covers the parent, never the directories under it.
  68. BRACE = re.compile(r"((?:modules|stacks)(?:/[\w.-]+)*)/\{([^}]*)\}")
  69. PLAIN = re.compile(r"(?<![\w./{-])((?:modules|stacks)(?:/[\w.-]+)*)")
  70. def covered_paths(block: str) -> set[str]:
  71. covered = set()
  72. for prefix, names in BRACE.findall(block):
  73. parts = prefix.split("/")
  74. covered.update("/".join(parts[:n]) for n in range(1, len(parts) + 1))
  75. covered.update(f"{prefix}/{n.strip()}" for n in names.split(",") if n.strip())
  76. stripped = BRACE.sub("", block)
  77. covered.update(m.rstrip("/") for m in PLAIN.findall(stripped))
  78. return covered
  79. def module_and_stack_dirs(root: Path) -> list[str]:
  80. """Every directory under modules/ and stacks/ that is a module, a stack or a
  81. grouping directory above them (provider, site). Stops at a directory that
  82. holds .tf files, and skips tests/ and hidden directories."""
  83. found: list[str] = []
  84. def walk(directory: Path) -> None:
  85. for child in sorted(directory.iterdir()):
  86. if not child.is_dir() or child.name == "tests" or child.name.startswith("."):
  87. continue
  88. found.append(child.relative_to(root).as_posix())
  89. if not any(child.glob("*.tf")):
  90. walk(child)
  91. for top in ("modules", "stacks"):
  92. if (root / top).is_dir():
  93. walk(root / top)
  94. return found
  95. def undocumented_dirs(root: Path, block: str) -> list[str]:
  96. covered = covered_paths(block)
  97. return [d for d in module_and_stack_dirs(root) if d not in covered]
  98. def test_every_module_and_stack_directory_is_in_the_layout_block():
  99. missing = undocumented_dirs(ROOT, layout_block())
  100. assert not missing, f"missing from the README layout: {missing}"
  101. def test_the_layout_check_reaches_nested_directories(tmp_path):
  102. for d in ("modules/aws/vpc", "stacks/aws/00-foundation", "stacks/aws/20-telemetry"):
  103. (tmp_path / d).mkdir(parents=True)
  104. (tmp_path / d / "main.tf").write_text("")
  105. (tmp_path / "stacks/aws/20-telemetry/tests").mkdir()
  106. block = "modules/aws/{vpc}\nstacks/aws/{00-foundation}\n"
  107. assert undocumented_dirs(tmp_path, block) == ["stacks/aws/20-telemetry"]
  108. # naming only the parent does not cover its children
  109. assert undocumented_dirs(tmp_path, "modules/aws/\nstacks/aws/\n") == [
  110. "modules/aws/vpc",
  111. "stacks/aws/00-foundation",
  112. "stacks/aws/20-telemetry",
  113. ]
  114. assert undocumented_dirs(tmp_path, block + "stacks/aws/20-telemetry/ x\n") == []