"""The IaC modules Skill: every module call validates against the pinned provider. A module is usable only with provider versions its own requirements admit, and several of the organisation's modules do not admit the pinned one. Each reference's example is run through `terraform validate`, which downloads the module, so a version bump that breaks one is found here. With no network the test is skipped. """ import re import shutil from pathlib import Path import pytest from app.config import Settings from app.providers import load_provider from app.tools.local import TerraformRunner from app.tools.modules import module_calls SKILL = "google-cloud-iac-modules" SKILLS = Path(__file__).resolve().parent.parent / "skills" ROOT = SKILLS / SKILL VERSIONS = SKILLS / "google-cloud-iac-patterns" / "assets" / "versions.tf" REFERENCES = sorted((ROOT / "references").glob("*.md")) _HCL = re.compile(r"^```hcl\n(.*?)^```", re.MULTILINE | re.DOTALL) needs_terraform = pytest.mark.skipif( shutil.which("terraform") is None, reason="terraform CLI not installed" ) def _code(reference: Path) -> str: return "\n".join(_HCL.findall(reference.read_text(encoding="utf-8"))) def test_every_reference_is_listed_and_calls_only_allowed_pinned_modules(): bundle = load_provider("gcp") skill = (ROOT / "SKILL.md").read_text(encoding="utf-8") assert REFERENCES listed = set(re.findall(r"references/([\w-]+\.md)", skill)) assert listed == {reference.name for reference in REFERENCES} for reference in REFERENCES: calls = module_calls({"main.tf": _code(reference)}) assert calls, reference.name for call in calls: assert call.source.split("/")[0] in bundle.terraform_module_namespaces # The version the example uses is the one the Skill's table gives. assert call.version in skill, f"{reference.name}: {call.version}" def test_the_skill_names_the_provider_version_the_bundle_pins(): pin = load_provider("gcp").terraform_providers["google"] skill = (ROOT / "SKILL.md").read_text(encoding="utf-8") assert f"{pin['source']} {pin['version']}" in skill @needs_terraform @pytest.mark.parametrize("reference", REFERENCES, ids=lambda path: path.stem) async def test_module_example_validates(reference: Path): bundle = load_provider("gcp") runner = TerraformRunner( plugin_cache_dir=Settings().terraform_plugin_cache(), module_namespaces=bundle.terraform_module_namespaces, ) files = { "terraform/versions.tf": VERSIONS.read_text(), "terraform/main.tf": _code(reference), } result = await runner.validate(files) if result.message.startswith("terraform init failed"): pytest.skip("the module or the pinned provider could not be downloaded") assert result.message.startswith("terraform validate passed"), result.message