gen_example_tests.py 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. """Generate stacks/<stack>/tests/example.tftest.hcl from terraform.tfvars.example.
  2. The example value file is only worth committing if it is valid. OpenTofu has no
  3. way to validate a tfvars file without real providers, but a test file's
  4. `variables { }` block takes the same assignments, so this script wraps the
  5. example verbatim in a test that plans the stack with mocked providers. Every
  6. validation then runs against the example, in the same `tofu test` that CI
  7. already runs for the stack.
  8. Usage (from the repository root):
  9. python -I scripts/gen_example_tests.py write the test files
  10. python -I scripts/gen_example_tests.py --check fail if one is stale
  11. python -I scripts/gen_example_tests.py --root DIR use a different root
  12. Exit codes: 0 ok, 1 stale or missing (--check), 2 usage.
  13. """
  14. from __future__ import annotations
  15. import argparse
  16. import sys
  17. from pathlib import Path
  18. EXAMPLE = "terraform.tfvars.example"
  19. TEST = Path("tests") / "example.tftest.hcl"
  20. HEADER = """\
  21. # GENERATED from terraform.tfvars.example by scripts/gen_example_tests.py. Do not
  22. # edit by hand: change the example file and run
  23. # `python -I scripts/gen_example_tests.py`. CI fails when this file is stale.
  24. # It plans the stack with the example values, so the example stays valid.
  25. """
  26. MOCKS = {
  27. "stacks/00-foundation": 'mock_provider "digitalocean" {}\n',
  28. "stacks/10-access": """\
  29. mock_provider "digitalocean" {
  30. mock_data "digitalocean_ssh_key" {
  31. defaults = {
  32. fingerprint = "aa:bb:cc:dd:ee:ff"
  33. }
  34. }
  35. }
  36. mock_provider "twingate" {}
  37. """,
  38. "stacks/20-telemetry": 'mock_provider "twingate" {}\n',
  39. "stacks/50-edge": 'mock_provider "digitalocean" {}\n',
  40. }
  41. RUN = """\
  42. run "the_example_values_are_valid" {
  43. command = plan
  44. }
  45. """
  46. def render(stack: str, root: Path) -> str:
  47. example = (root / stack / EXAMPLE).read_text(encoding="utf-8")
  48. body = example.rstrip("\n")
  49. indented = "\n".join((" " + line) if line.strip() else "" for line in body.splitlines())
  50. return f"{HEADER}\n{MOCKS[stack]}\nvariables {{\n{indented}\n}}\n{RUN}"
  51. def main(argv: list[str] | None = None) -> int:
  52. parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
  53. parser.add_argument("--check", action="store_true")
  54. parser.add_argument("--root", default=str(Path(__file__).resolve().parent.parent))
  55. args = parser.parse_args(argv)
  56. root = Path(args.root).resolve()
  57. status = 0
  58. for stack in MOCKS:
  59. target = root / stack / TEST
  60. try:
  61. want = render(stack, root)
  62. except OSError as exc:
  63. print(f"gen_example_tests: {stack}: cannot read {EXAMPLE} ({exc.strerror})", file=sys.stderr)
  64. return 1
  65. if args.check:
  66. have = target.read_text(encoding="utf-8") if target.is_file() else None
  67. if have != want:
  68. print(
  69. f"gen_example_tests: {stack}/{TEST} is out of date. "
  70. "Run: python -I scripts/gen_example_tests.py",
  71. file=sys.stderr,
  72. )
  73. status = 1
  74. else:
  75. target.parent.mkdir(parents=True, exist_ok=True)
  76. target.write_text(want, encoding="utf-8")
  77. print(f"gen_example_tests: wrote {stack}/{TEST}")
  78. return status
  79. if __name__ == "__main__":
  80. sys.exit(main())