test_cost_check_phases.py 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. """Per-phase cost ceilings in docs/stages/approved.json."""
  2. import json
  3. import shutil
  4. import sys
  5. from pathlib import Path
  6. import pytest
  7. sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts"))
  8. import cost_check
  9. ROOT = Path(__file__).resolve().parents[1]
  10. # Tests that need a known lifecycle state (stage-1 current, stage-2 planned) use a frozen
  11. # copy of approved.json, so advancing the real file's current phase does not break them.
  12. FIXTURE_STAGE1 = ROOT / "tests/fixtures/approved_stage1_current.json"
  13. def phase(ceiling, status="planned", reason="because", decided="2026-10-10", **extra):
  14. return {
  15. "ceiling": ceiling,
  16. "reason": reason,
  17. "decided": decided,
  18. "status": status,
  19. **extra,
  20. }
  21. def approved(**overrides):
  22. out = {
  23. "stage": 1,
  24. "current_phase": "stage-1",
  25. "hard_max": 100.0,
  26. "hard_max_reason": "test limit",
  27. "phases": {
  28. "stage-0": phase(30.0, "done"),
  29. "stage-1": phase(30.0, "current"),
  30. "stage-3": phase(36.0),
  31. },
  32. "providers": {"digitalocean": {"approved_monthly_total": 12.0, "active": True}},
  33. }
  34. out.update(overrides)
  35. return out
  36. def problems(doc):
  37. return cost_check.phase_problems(doc)
  38. def test_a_valid_phase_map_has_no_problems():
  39. assert problems(approved()) == []
  40. def test_current_ceiling_comes_from_the_current_phase():
  41. doc = approved()
  42. assert cost_check.current_ceiling(doc) == ("stage-1", 30.0, "because")
  43. doc["phases"]["stage-1"]["status"] = "done"
  44. doc["phases"]["stage-3"]["status"] = "current"
  45. doc["current_phase"] = "stage-3"
  46. assert cost_check.current_ceiling(doc)[:2] == ("stage-3", 36.0)
  47. def test_legacy_top_level_ceiling_is_read_when_phases_is_absent():
  48. doc = {"ceiling": 30.0, "providers": {}}
  49. assert cost_check.current_ceiling(doc)[:2] == ("legacy", 30.0)
  50. assert problems(doc) == []
  51. def test_legacy_ceiling_beside_phases_is_refused():
  52. doc = approved(ceiling=30.0)
  53. assert any("top-level ceiling" in p for p in problems(doc))
  54. def test_no_ceiling_at_all_is_an_error():
  55. with pytest.raises((ValueError, KeyError)):
  56. cost_check.current_ceiling({"providers": {}})
  57. def test_current_phase_must_exist():
  58. doc = approved(current_phase="stage-9")
  59. assert any("current_phase stage-9 is not in phases" in p for p in problems(doc))
  60. def test_current_phase_missing_is_refused():
  61. doc = approved()
  62. del doc["current_phase"]
  63. assert any("current_phase" in p for p in problems(doc))
  64. def test_exactly_one_phase_is_current():
  65. doc = approved()
  66. doc["phases"]["stage-3"]["status"] = "current"
  67. assert any("exactly one phase" in p for p in problems(doc))
  68. doc = approved()
  69. doc["phases"]["stage-1"]["status"] = "planned"
  70. assert any("exactly one phase" in p for p in problems(doc))
  71. def test_the_current_status_must_be_the_current_phase():
  72. doc = approved()
  73. doc["phases"]["stage-1"]["status"] = "done"
  74. doc["phases"]["stage-3"]["status"] = "current"
  75. assert any(
  76. "status current but current_phase is stage-1" in p for p in problems(doc)
  77. )
  78. @pytest.mark.parametrize(
  79. "bad", [-1, "nan", float("nan"), float("inf"), "x", None, True]
  80. )
  81. def test_a_bad_ceiling_is_refused(bad):
  82. doc = approved()
  83. doc["phases"]["stage-0"]["ceiling"] = bad # first phase: no neighbor rule applies
  84. assert any("stage-0" in p and "must be a finite number" in p for p in problems(doc))
  85. @pytest.mark.parametrize("bad", ["", " ", None, 5])
  86. def test_a_phase_needs_a_reason(bad):
  87. doc = approved()
  88. doc["phases"]["stage-3"]["reason"] = bad
  89. assert any("stage-3" in p and "reason" in p for p in problems(doc))
  90. @pytest.mark.parametrize(
  91. "bad", ["", "2026-13-01", "2026-02-30", "20261010", "10/10/2026", None, 20261010]
  92. )
  93. def test_a_phase_needs_a_valid_date(bad):
  94. doc = approved()
  95. doc["phases"]["stage-3"]["decided"] = bad
  96. assert any("stage-3" in p and "decided" in p for p in problems(doc))
  97. def test_a_phase_needs_a_known_status():
  98. doc = approved()
  99. doc["phases"]["stage-3"]["status"] = "maybe"
  100. assert any("stage-3" in p and "status" in p for p in problems(doc))
  101. def test_a_phase_that_is_not_an_object_is_refused():
  102. doc = approved()
  103. doc["phases"]["stage-3"] = 36
  104. assert any("stage-3" in p for p in problems(doc))
  105. def test_an_empty_phase_map_is_refused():
  106. assert any("phases" in p for p in problems(approved(phases={})))
  107. def test_a_bad_phase_id_is_refused():
  108. doc = approved()
  109. doc["phases"]["Stage 3!"] = phase(40.0)
  110. assert any("phase id" in p for p in problems(doc))
  111. def test_ceilings_may_rise_and_stay_equal():
  112. doc = approved()
  113. doc["phases"]["stage-3"]["ceiling"] = 30.0
  114. assert problems(doc) == []
  115. doc["phases"]["stage-3"]["ceiling"] = 99.0
  116. assert problems(doc) == []
  117. assert problems(approved(hard_max=98.0)) == [] # 36 < 98
  118. def test_a_quiet_decrease_is_refused():
  119. doc = approved()
  120. doc["phases"]["stage-3"]["ceiling"] = 25.0
  121. assert any("stage-3" in p and "lowers" in p for p in problems(doc))
  122. def test_an_explicit_decrease_passes():
  123. doc = approved()
  124. doc["phases"]["stage-3"] = phase(25.0, lowers=True, reason="cheaper host chosen")
  125. assert problems(doc) == []
  126. def test_lowers_without_a_decrease_is_refused():
  127. doc = approved()
  128. doc["phases"]["stage-3"]["lowers"] = True
  129. assert any("lowers" in p and "does not" in p for p in problems(doc))
  130. @pytest.mark.parametrize("flag", ["yes", 1, "true"])
  131. def test_lowers_must_be_a_real_boolean(flag):
  132. doc = approved()
  133. doc["phases"]["stage-3"] = phase(25.0, lowers=flag)
  134. assert any("lowers" in p for p in problems(doc))
  135. def test_hard_max_caps_every_phase():
  136. doc = approved(hard_max=40.0)
  137. assert problems(doc) == []
  138. doc["phases"]["stage-3"]["ceiling"] = 40.01
  139. assert any("hard_max" in p and "stage-3" in p for p in problems(doc))
  140. def test_hard_max_at_the_limit_passes_and_a_bad_one_fails():
  141. assert problems(approved(hard_max=36.0)) == []
  142. for bad in ("nan", -1, "x", True):
  143. assert any("hard_max" in p for p in problems(approved(hard_max=bad)))
  144. def test_hard_max_also_caps_a_legacy_ceiling():
  145. doc = {"ceiling": 30.0, "hard_max": 20.0, "providers": {}}
  146. assert any("hard_max" in p for p in problems(doc))
  147. # --- the gate itself ---------------------------------------------------------
  148. def test_approvals_are_checked_against_the_current_phase_ceiling():
  149. doc = approved()
  150. doc["providers"]["digitalocean"]["approved_monthly_total"] = 33.0
  151. got = cost_check.approval_problems(doc, {})
  152. assert any("above the ceiling $30.00" in p for p in got)
  153. doc["phases"]["stage-1"]["status"] = "done"
  154. doc["phases"]["stage-3"]["status"] = "current"
  155. doc["current_phase"] = "stage-3"
  156. assert not any("ceiling" in p for p in cost_check.approval_problems(doc, {}))
  157. def test_the_active_sum_uses_the_current_phase_ceiling():
  158. doc = approved()
  159. doc["providers"]["aws"] = {"approved_monthly_total": 21.0, "active": True}
  160. got = cost_check.approval_problems(doc, {})
  161. assert any("add up to $33.00, above the shared ceiling $30.00" in p for p in got)
  162. def test_phase_problems_flow_through_approval_problems():
  163. got = cost_check.approval_problems(approved(current_phase="nope"), {})
  164. assert any("current_phase nope" in p for p in got)
  165. def test_the_real_file_is_valid_and_keeps_todays_behaviour():
  166. doc = json.loads((ROOT / "docs/stages/approved.json").read_text())
  167. assert "ceiling" not in doc
  168. assert problems(doc) == []
  169. pid, ceiling, _ = cost_check.current_ceiling(doc)
  170. assert (pid, ceiling) == ("stage-3", 30.0)
  171. assert doc["providers"]["digitalocean"]["active"] is True
  172. assert doc["providers"]["aws"]["active"] is False
  173. def run_main(root, capsys):
  174. code = cost_check.main(["--root", str(root)])
  175. return code, capsys.readouterr()
  176. def copy_real_repo(tmp_path, mutate=None, frozen=True):
  177. for rel in ("docs/stages/approved.json", "docs/cost-prices.json", "docs/cost-prices"):
  178. src, dst = ROOT / rel, tmp_path / rel
  179. dst.parent.mkdir(parents=True, exist_ok=True)
  180. if src.is_dir():
  181. shutil.copytree(src, dst)
  182. else:
  183. shutil.copy(src, dst)
  184. if frozen:
  185. shutil.copy(FIXTURE_STAGE1, tmp_path / "docs/stages/approved.json")
  186. for rel in ("stacks", "modules", ".spacelift"):
  187. if (ROOT / rel).exists():
  188. shutil.copytree(
  189. ROOT / rel, tmp_path / rel, ignore=shutil.ignore_patterns(".terraform")
  190. )
  191. if mutate:
  192. path = tmp_path / "docs/stages/approved.json"
  193. doc = json.loads(path.read_text())
  194. mutate(doc)
  195. path.write_text(json.dumps(doc))
  196. return tmp_path
  197. def test_the_real_repo_passes_and_names_the_phase(tmp_path, capsys):
  198. code, out = run_main(copy_real_repo(tmp_path, frozen=False), capsys)
  199. assert code == 0, out.err
  200. assert "cost-check: phase stage-3 ceiling $30.00 (reason: " in out.out
  201. assert "shared ceiling $" not in out.out
  202. def test_main_fails_on_a_quiet_decrease(tmp_path, capsys):
  203. def mutate(doc):
  204. doc["phases"]["stage-3"]["ceiling"] = 1.0
  205. code, out = run_main(copy_real_repo(tmp_path, mutate), capsys)
  206. assert code == 1 and "lowers" in out.err
  207. def test_main_fails_when_the_current_phase_is_missing(tmp_path, capsys):
  208. root = copy_real_repo(tmp_path, lambda d: d.update(current_phase="gone"))
  209. code, out = run_main(root, capsys)
  210. assert code == 1 and "current_phase gone" in out.err
  211. def test_main_fails_when_hard_max_is_below_a_ceiling(tmp_path, capsys):
  212. root = copy_real_repo(tmp_path, lambda d: d.update(hard_max=10.0))
  213. code, out = run_main(root, capsys)
  214. assert code == 1 and "hard_max" in out.err
  215. def test_raising_the_current_ceiling_lets_a_bigger_approval_through(tmp_path, capsys):
  216. def mutate(doc):
  217. for ph in doc["phases"].values():
  218. ph["ceiling"] = max(ph["ceiling"], 50.0)
  219. doc["providers"]["digitalocean"]["approved_monthly_total"] = 40.0
  220. code, out = run_main(copy_real_repo(tmp_path, mutate), capsys)
  221. assert code == 0, out.err
  222. assert "ceiling $50.00" in out.out