conftest.py 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. # SPDX-License-Identifier: Apache-2.0
  2. """Shared pytest setup.
  3. `slow` marks the tests that run OpenTofu (an init that may download a provider, then validate or
  4. plan). They always run, in CI too; the marker only lets a person on a laptop write
  5. `-m "not slow"` for a quick pass (#527).
  6. `tofu_lab` is one initialized copy of labs/email-security for the whole test session. Before this,
  7. `test_tofu_validate` and the plan test each copied the tree and ran `tofu init` in a fresh plugin
  8. cache, so the digitalocean provider was downloaded twice per run and initialized twice per directory.
  9. """
  10. import fcntl
  11. import os
  12. import shutil
  13. import subprocess
  14. from pathlib import Path
  15. import pytest
  16. ROOT = Path(__file__).resolve().parent.parent
  17. LAB = ROOT / "labs" / "email-security"
  18. NO_NETWORK = "tofu could not download its provider (no network)"
  19. def pytest_configure(config):
  20. config.addinivalue_line("markers", "slow: runs OpenTofu (provider download on a cold plugin cache); always run, CI included")
  21. def _plugin_cache(fallback: Path) -> Path:
  22. """A per-user plugin cache that survives between runs; a session directory if that cannot be made."""
  23. base = Path(os.environ.get("XDG_CACHE_HOME") or Path.home() / ".cache")
  24. cache = base / "cah-tests" / "tofu-plugins"
  25. try:
  26. cache.mkdir(parents=True, exist_ok=True)
  27. return cache
  28. except OSError:
  29. fallback.mkdir(parents=True, exist_ok=True)
  30. return fallback
  31. def lab_dirs(tree: Path) -> list[Path]:
  32. return sorted((tree / "cloud").iterdir()) + [tree / "compose"]
  33. @pytest.fixture(scope="session")
  34. def tofu_lab(tmp_path_factory):
  35. """(env, tree): the email-security lab copied once and `tofu init`ed once per session.
  36. Under pytest-xdist every worker is its own session, so the tree lives in the directory the workers
  37. share and a file lock lets the first worker build it while the others wait and then reuse it. The
  38. plugin cache is only written while that lock is held: a plugin cache is not documented as safe for
  39. two `tofu init` runs at once, so init is serialized rather than given one cache per worker. A
  40. failed init (no network) is remembered so the other workers skip at once instead of retrying.
  41. """
  42. if shutil.which("tofu") is None:
  43. pytest.skip("tofu is not installed")
  44. base = tmp_path_factory.getbasetemp()
  45. shared = base.parent if os.environ.get("PYTEST_XDIST_WORKER") else base
  46. tree = shared / "tofu-lab"
  47. state = shared / "tofu-lab.state"
  48. cache = _plugin_cache(shared / "tofu-plugins")
  49. env = dict(os.environ, TF_PLUGIN_CACHE_DIR=str(cache), TF_IN_AUTOMATION="1")
  50. with open(cache.parent / ".cah-tofu.lock", "w") as lock:
  51. fcntl.flock(lock, fcntl.LOCK_EX)
  52. if not state.exists():
  53. shutil.copytree(LAB, tree, ignore=shutil.ignore_patterns(".terraform*", "local"))
  54. verdict = "ok"
  55. for d in lab_dirs(tree):
  56. init = subprocess.run(["tofu", "init", "-backend=false", "-input=false"], cwd=d, env=env, capture_output=True, text=True, check=False)
  57. if init.returncode != 0:
  58. verdict = "no-network"
  59. break
  60. state.write_text(verdict)
  61. if state.read_text() != "ok":
  62. pytest.skip(NO_NETWORK)
  63. return env, tree