test_resource_key.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. """resource_key and site_name (stage 2 design, section 3.1), checked on the sources.
  2. `resource_key` builds NAMES; `region` is only the region argument. `site_name`
  3. is a telemetry label and must never reach a resource name, a tag, a `moved`
  4. target or an output. The tofu tests prove the rendered names; these tests read
  5. every .tf file, so a name built another way, or a site_name used in a new
  6. file, fails here too.
  7. """
  8. import re
  9. from pathlib import Path
  10. ROOT = Path(__file__).resolve().parent.parent
  11. # The one file where the telemetry stack reads site_name (see the tests below).
  12. TELEMETRY_SITE_FILE = "stacks/20-telemetry/site.tf"
  13. def source_files():
  14. """Every .tf file under stacks and modules, except variable declarations."""
  15. for top in ("stacks", "modules"):
  16. for path in sorted((ROOT / top).rglob("*.tf")):
  17. if ".terraform" in path.parts or path.name == "variables.tf":
  18. continue
  19. # stack 20 reads site_name in exactly one file; its own test below
  20. # keeps that file honest, so the general rules skip it.
  21. if path.relative_to(ROOT).as_posix() == TELEMETRY_SITE_FILE:
  22. continue
  23. # resource_key is DigitalOcean-only for now: stacks/<NN-name> and
  24. # modules/<role>. The AWS code (stacks/aws/*, modules/aws/*) still
  25. # names from region and has no resource_key; see the PR text.
  26. if len(path.relative_to(ROOT / top).parts) > 2:
  27. continue
  28. yield path
  29. def without_comments(text: str) -> str:
  30. return re.sub(r"(?m)(#|//).*$", "", text)
  31. def test_resource_key_is_digitalocean_only_for_now():
  32. # Say so in a test: if an AWS stack or module gains resource_key, this
  33. # fails and the scope above must be widened on purpose, with golden names.
  34. for path in (ROOT / "stacks" / "aws").rglob("variables.tf"):
  35. assert 'variable "resource_key"' not in path.read_text(), path
  36. for path in (ROOT / "modules" / "aws").rglob("variables.tf"):
  37. assert 'variable "resource_key"' not in path.read_text(), path
  38. def test_there_are_source_files_to_check():
  39. assert len(list(source_files())) >= 12
  40. def test_site_name_is_declared_but_never_used():
  41. for path in source_files():
  42. assert "site_name" not in without_comments(path.read_text()), (
  43. f"{path.relative_to(ROOT)} uses site_name; it is for telemetry labels only"
  44. )
  45. def test_site_name_is_only_declared_in_the_stacks():
  46. declared = [
  47. p.parent.relative_to(ROOT).as_posix()
  48. for p in (ROOT / "stacks").glob("*/variables.tf")
  49. if 'variable "site_name"' in p.read_text()
  50. ]
  51. assert sorted(declared) == [
  52. "stacks/00-foundation",
  53. "stacks/10-access",
  54. "stacks/20-telemetry",
  55. ]
  56. for path in (ROOT / "modules").glob("*/variables.tf"):
  57. assert 'variable "site_name"' not in path.read_text(), path
  58. def test_no_name_is_built_from_the_region_directly():
  59. # A name must use resource_key (or the modules' name_key). A string that
  60. # interpolates var.region would ignore resource_key and rename on change.
  61. pattern = re.compile(r"\$\{[^}]*\bvar\.region\b[^}]*\}")
  62. for path in source_files():
  63. assert not pattern.search(without_comments(path.read_text())), (
  64. f"{path.relative_to(ROOT)} interpolates var.region into a string"
  65. )
  66. def test_region_is_only_used_as_an_argument_or_a_fallback():
  67. # Every use of var.region outside variables.tf is either `region = var.region`
  68. # (the real region argument) or the resource_key fallback.
  69. allowed = re.compile(
  70. r"(?m)^\s*region\s*=\s*var\.region\s*$"
  71. r"|^\s*value\s*=\s*var\.region\s*$"
  72. r"|\?\s*var\.resource_key\s*:\s*var\.region\b"
  73. r"|^\s*region\s*=\s*var\.region\b"
  74. )
  75. for path in source_files():
  76. text = without_comments(path.read_text())
  77. for line in text.splitlines():
  78. if "var.region" in line:
  79. assert allowed.search(line), (
  80. f"{path.relative_to(ROOT)}: unexpected use of var.region: {line.strip()}"
  81. )
  82. def test_resource_key_is_passed_down_next_to_every_region():
  83. # Wherever a module call receives the real region it also receives the key.
  84. for path in source_files():
  85. text = without_comments(path.read_text())
  86. for block in re.findall(r"(?ms)^module\s+\"[^\"]+\"\s*\{\n(.*?)^\}\n", text):
  87. if re.search(r"(?m)^\s*region\s*=\s*var\.region", block):
  88. assert re.search(r"(?m)^\s*resource_key\s*=\s*var\.resource_key\s*$", block), (
  89. f"{path.relative_to(ROOT)}: a module gets region but not resource_key"
  90. )
  91. def test_telemetry_reads_site_name_in_one_file_and_only_for_labels():
  92. # Stack 20 is the telemetry consumer of site_name. It may be read in site.tf
  93. # (into local.site) and local.site may feed outputs.tf, nothing else.
  94. stack = ROOT / "stacks" / "20-telemetry"
  95. site = without_comments((ROOT / TELEMETRY_SITE_FILE).read_text())
  96. assert "var.site_name" in site
  97. for path in sorted(stack.glob("*.tf")):
  98. if path.name in ("variables.tf", "site.tf"):
  99. continue
  100. text = without_comments(path.read_text())
  101. assert "site_name" not in text, f"{path.name} reads site_name"
  102. if path.name != "outputs.tf":
  103. assert "local.site" not in text, f"{path.name} uses the site label"
  104. # No name, tag or moved target is built from the label.
  105. main = without_comments((stack / "main.tf").read_text())
  106. assert not re.search(r"(?m)^\s*(name|tags?)\s*=.*(\bsite\b|site_name)", main)
  107. assert "moved" not in main