test_unused_variables.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. """Every variable is used, or is on the short documented list of exceptions.
  2. tflint's terraform_unused_declarations rule runs in CI. `site_name` is declared
  3. before anything reads it (the telemetry stage uses it), so it carries a
  4. `tflint-ignore` annotation. This test keeps that list explicit: a new unused
  5. variable fails here instead of being quietly ignored, and an annotation on a
  6. variable that is used (or on one not listed) fails too.
  7. """
  8. import re
  9. from pathlib import Path
  10. ROOT = Path(__file__).resolve().parent.parent
  11. ANNOTATION = "tflint-ignore: terraform_unused_declarations"
  12. # (directory, variable): declared on purpose, read by a later stage.
  13. DOCUMENTED_UNUSED = {
  14. ("stacks/00-foundation", "site_name"),
  15. ("stacks/10-access", "site_name"),
  16. }
  17. def directories():
  18. for top in ("stacks", "modules"):
  19. for path in sorted((ROOT / top).rglob("variables.tf")):
  20. if ".terraform" not in path.parts:
  21. yield path.parent
  22. def strip_comments(text: str) -> str:
  23. return re.sub(r"(?m)(#|//).*$", "", text)
  24. def annotated(directory: Path) -> set[str]:
  25. text = (directory / "variables.tf").read_text()
  26. return set(
  27. re.findall(rf"(?m)^# {re.escape(ANNOTATION)}\nvariable \"([A-Za-z0-9_-]+)\"", text)
  28. )
  29. def unused(directory: Path) -> set[str]:
  30. declared = re.findall(
  31. r'(?m)^variable "([A-Za-z0-9_-]+)"', (directory / "variables.tf").read_text()
  32. )
  33. others = "\n".join(
  34. strip_comments(p.read_text()) for p in directory.glob("*.tf") if p.name != "variables.tf"
  35. )
  36. # A variable is used when var.<name> appears in another file, or in a
  37. # validation of another variable in variables.tf is not use (it is its own).
  38. return {n for n in declared if not re.search(rf"\bvar\.{re.escape(n)}\b", others)}
  39. def test_there_are_directories_to_check():
  40. assert len(list(directories())) >= 6
  41. def test_the_unused_variables_are_exactly_the_documented_ones():
  42. found = {
  43. (d.relative_to(ROOT).as_posix(), name) for d in directories() for name in unused(d)
  44. }
  45. assert found == DOCUMENTED_UNUSED
  46. def test_the_annotations_are_exactly_the_documented_ones():
  47. found = {
  48. (d.relative_to(ROOT).as_posix(), name) for d in directories() for name in annotated(d)
  49. }
  50. assert found == DOCUMENTED_UNUSED
  51. for d in directories():
  52. text = (d / "variables.tf").read_text()
  53. assert text.count(ANNOTATION) == len(annotated(d)), d