gen_example_tests.py 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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. }
  39. RUN = """\
  40. run "the_example_values_are_valid" {
  41. command = plan
  42. }
  43. """
  44. def render(stack: str, root: Path) -> str:
  45. example = (root / stack / EXAMPLE).read_text(encoding="utf-8")
  46. body = example.rstrip("\n")
  47. indented = "\n".join((" " + line) if line.strip() else "" for line in body.splitlines())
  48. return f"{HEADER}\n{MOCKS[stack]}\nvariables {{\n{indented}\n}}\n{RUN}"
  49. def main(argv: list[str] | None = None) -> int:
  50. parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
  51. parser.add_argument("--check", action="store_true")
  52. parser.add_argument("--root", default=str(Path(__file__).resolve().parent.parent))
  53. args = parser.parse_args(argv)
  54. root = Path(args.root).resolve()
  55. status = 0
  56. for stack in MOCKS:
  57. target = root / stack / TEST
  58. try:
  59. want = render(stack, root)
  60. except OSError as exc:
  61. print(f"gen_example_tests: {stack}: cannot read {EXAMPLE} ({exc.strerror})", file=sys.stderr)
  62. return 1
  63. if args.check:
  64. have = target.read_text(encoding="utf-8") if target.is_file() else None
  65. if have != want:
  66. print(
  67. f"gen_example_tests: {stack}/{TEST} is out of date. "
  68. "Run: python -I scripts/gen_example_tests.py",
  69. file=sys.stderr,
  70. )
  71. status = 1
  72. else:
  73. target.parent.mkdir(parents=True, exist_ok=True)
  74. target.write_text(want, encoding="utf-8")
  75. print(f"gen_example_tests: wrote {stack}/{TEST}")
  76. return status
  77. if __name__ == "__main__":
  78. sys.exit(main())