test_environments_lesson.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. # SPDX-License-Identifier: Apache-2.0
  2. """The environments and promotion lesson keeps the promises it makes (issue #313).
  3. docs/wiki/Environments-and-Promotion-Dev-Staging-Production.md teaches environments from
  4. this repository's files and marks staging as planned and unbuilt. These tests hold what a
  5. machine can hold: the honest banner, that every repository path it cites exists, that the
  6. numbers it quotes match docs/stages/approved.json, that it stops saying "planned" only when
  7. a staging stack really exists, no real address or credential shape, and the registrations.
  8. Each guard also has a case proving it bites.
  9. """
  10. import ipaddress
  11. import json
  12. import re
  13. from pathlib import Path
  14. ROOT = Path(__file__).resolve().parent.parent
  15. WIKI = ROOT / "docs" / "wiki"
  16. PAGE = WIKI / "Environments-and-Promotion-Dev-Staging-Production.md"
  17. NAME = PAGE.name
  18. IPV4 = re.compile(r"\b(?:\d{1,3}\.){3}\d{1,3}\b")
  19. DOC_NETS = [ipaddress.ip_network(n) for n in ("192.0.2.0/24", "198.51.100.0/24", "203.0.113.0/24")]
  20. SECRET_SHAPE = re.compile(r"(?i)(password|passwd|token|secret)\s*[:=]\s*(?!\$|<|\{|\.\.\.|')[^\s`]{4,}")
  21. CITED_PATH = re.compile(r"`((?:docs|scripts|stacks|\.spacelift|tests)/[A-Za-z0-9_./*-]+)`")
  22. def text() -> str:
  23. return PAGE.read_text(encoding="utf-8")
  24. def real_addresses(body: str) -> list[str]:
  25. bad = []
  26. for m in IPV4.findall(body):
  27. ip = ipaddress.ip_address(m)
  28. if ip.is_loopback or ip.is_unspecified:
  29. continue
  30. if not any(ip in net for net in DOC_NETS):
  31. bad.append(m)
  32. return bad
  33. def missing_paths(body: str, root: Path) -> list[str]:
  34. missing = []
  35. for p in sorted(set(CITED_PATH.findall(body))):
  36. if "*" in p:
  37. if not list(root.glob(p)):
  38. missing.append(p)
  39. elif not (root / p).exists():
  40. missing.append(p)
  41. return missing
  42. def test_banner_says_written_from_reading_and_staging_is_not_built():
  43. banner = next(l for l in text().splitlines() if l.startswith("> **"))
  44. low = banner.lower()
  45. assert "written from reading" in low
  46. assert "staging is planned and not built" in low
  47. def test_every_repository_path_it_cites_exists():
  48. body = text()
  49. assert len(set(CITED_PATH.findall(body))) >= 8, "the lesson must cite the files it leans on"
  50. assert missing_paths(body, ROOT) == []
  51. def test_numbers_match_the_cost_file():
  52. approved = json.loads((ROOT / "docs" / "stages" / "approved.json").read_text())
  53. body = text()
  54. current = approved["current_phase"]
  55. assert f"`{current}`" in body, "the lesson names the current phase"
  56. assert f"${approved['phases'][current]['ceiling']:.0f} per month" in body
  57. assert f"${approved['hard_max']:.0f}" in body
  58. assert "$20 per month" in body
  59. def test_staging_is_still_planned_only_when_no_staging_phase_or_stack_exists():
  60. approved = json.loads((ROOT / "docs" / "stages" / "approved.json").read_text())
  61. stacks = [p.name.lower() for p in (ROOT / "stacks").iterdir() if p.is_dir()]
  62. built = any("staging" in k.lower() for k in approved["phases"]) or any("staging" in s for s in stacks)
  63. assert not built, "a staging phase or stack now exists: rewrite the lesson's planned-only claims"
  64. body = text()
  65. assert "Planned, not built" in body or "**Planned, not built.**" in body
  66. assert "Staging stack | **Planned, not built**" in body
  67. def test_hook_really_only_trusts_main():
  68. script = (ROOT / "scripts" / "spacelift" / "doppler-env.sh").read_text()
  69. assert '"$_branch" != "main"' in script
  70. assert "is not main; skipping" in script and "is not main; skipping" in text()
  71. def test_no_real_address_and_no_credential_shape():
  72. body = text()
  73. assert real_addresses(body) == []
  74. assert SECRET_SHAPE.findall(body) == []
  75. def test_guards_bite():
  76. assert real_addresses("host 8.8.8.8 and 192.0.2.5") == ["8.8.8.8"]
  77. assert SECRET_SHAPE.findall("password: hunter2x") != []
  78. assert SECRET_SHAPE.findall("token: $DOPPLER_TOKEN") == []
  79. assert missing_paths("see `docs/does-not-exist.md`", ROOT) == ["docs/does-not-exist.md"]
  80. assert missing_paths("see `docs/cost.md`", ROOT) == []
  81. def test_registered_everywhere():
  82. for page in ("_Sidebar.md", "Contents.md", "Reading-Order.md", "Build-and-Destroy-Stack-Per-Service.md"):
  83. assert NAME in (WIKI / page).read_text(), page
  84. glossary = (WIKI / "Glossary.md").read_text()
  85. for term in ("Environment (deployment)", "Promotion", "Staging", "Trunk-based development"):
  86. assert f"| **{term}** |" in glossary, term
  87. assert re.search(r"page: Environments-and-Promotion-Dev-Staging-Production,", (WIKI / "_nav.yaml").read_text())