test_cost_check.py 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084
  1. import json
  2. import sys
  3. from pathlib import Path
  4. import pytest
  5. sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts"))
  6. import cost_check
  7. PRICES = {
  8. "backups_fraction": 0.2,
  9. "backups_fraction_verified": False,
  10. "droplets": {"s-1vcpu-1gb": 6, "s-1vcpu-2gb": 12},
  11. }
  12. CONNECTOR_MODULE = (
  13. 'module "connector" {\n source = "../../modules/twingate-connector"\n'
  14. " size = local.connector.size\n}\n"
  15. )
  16. def make_repo(
  17. tmp_path,
  18. resources,
  19. approved_total=6.0,
  20. tf_files=None,
  21. ceiling=30.0,
  22. prices=None,
  23. connector_modules=None,
  24. allowed=None,
  25. ):
  26. (tmp_path / "docs/stages").mkdir(parents=True)
  27. (tmp_path / "stacks/10-access").mkdir(parents=True)
  28. (tmp_path / "docs/cost-prices.json").write_text(json.dumps(prices or PRICES))
  29. (tmp_path / "docs/stages/approved.json").write_text(
  30. json.dumps(
  31. {
  32. "ceiling": ceiling,
  33. "providers": {
  34. "digitalocean": {
  35. "approved_monthly_total": approved_total,
  36. "active": True,
  37. "allowed_sources": {
  38. "digitalocean_droplet": ["modules/ok/main.tf"],
  39. **(allowed or {}),
  40. },
  41. }
  42. },
  43. }
  44. )
  45. )
  46. (tmp_path / "stacks/10-access/cost.json").write_text(
  47. json.dumps({"stage": 1, "resources": resources})
  48. )
  49. # Fixture helper: the cost gate now reconciles twingate-connector module
  50. # blocks against kind=droplet manifest entries, so write one block per
  51. # droplet unless a test overrides the count.
  52. if connector_modules is None:
  53. connector_modules = sum(1 for r in resources if r.get("kind") == "droplet")
  54. (tmp_path / "stacks/10-access/modules.tf").write_text(
  55. "".join(
  56. CONNECTOR_MODULE.replace('"connector"', f'"connector{i}"')
  57. for i in range(connector_modules)
  58. )
  59. )
  60. for rel, text in (tf_files or {}).items():
  61. p = tmp_path / rel
  62. p.parent.mkdir(parents=True, exist_ok=True)
  63. p.write_text(text)
  64. return tmp_path
  65. def droplet(size="s-1vcpu-1gb", backups=False):
  66. return {"name": "connector", "kind": "droplet", "size": size, "backups": backups}
  67. def test_total_sums_manifests(tmp_path):
  68. root = make_repo(tmp_path, [droplet(), droplet("s-1vcpu-2gb")], approved_total=18)
  69. assert cost_check.total_cost(root, PRICES) == 18.0
  70. def test_unknown_size_fails_closed(tmp_path):
  71. root = make_repo(tmp_path, [droplet("s-99vcpu-1tb")])
  72. with pytest.raises(ValueError, match="no price for size"):
  73. cost_check.total_cost(root, PRICES)
  74. def test_backups_refused_while_fraction_unverified(tmp_path):
  75. res = droplet(backups=True)
  76. res["backup_plan"] = "weekly"
  77. root = make_repo(tmp_path, [res])
  78. with pytest.raises(ValueError, match="unverified"):
  79. cost_check.total_cost(root, PRICES)
  80. def test_backups_priced_once_verified(tmp_path):
  81. prices = {**PRICES, "backups_fraction_verified": True}
  82. res = droplet(backups=True)
  83. res["backup_plan"] = "weekly"
  84. root = make_repo(tmp_path, [res], prices=prices)
  85. assert cost_check.total_cost(root, prices) == 7.2
  86. def test_non_droplet_kind_has_no_price_model(tmp_path):
  87. root = make_repo(tmp_path, [{"name": "lb", "kind": "loadbalancer"}])
  88. with pytest.raises(ValueError, match="no price model"):
  89. cost_check.total_cost(root, PRICES)
  90. def test_costed_resource_outside_allowed_file_is_flagged(tmp_path):
  91. root = make_repo(
  92. tmp_path,
  93. [droplet()],
  94. tf_files={
  95. "modules/ok/main.tf": 'resource "digitalocean_droplet" "a" {}\n',
  96. "stacks/10-access/sneaky.tf": 'resource "digitalocean_volume" "v" {}\n',
  97. },
  98. )
  99. found = cost_check.uncosted_sources(
  100. root, {"digitalocean_droplet": ["modules/ok/main.tf"]}
  101. )
  102. assert found == [
  103. "stacks/10-access/sneaky.tf: digitalocean_volume (the gate has no price model for it)"
  104. ]
  105. def test_provider_cache_directories_are_ignored(tmp_path):
  106. root = make_repo(
  107. tmp_path,
  108. [droplet()],
  109. tf_files={
  110. "stacks/10-access/.terraform/x.tf": 'resource "digitalocean_droplet" "a" {}\n',
  111. },
  112. )
  113. assert cost_check.uncosted_sources(root, {}) == []
  114. def test_main_passes_at_approved_total(tmp_path, capsys):
  115. root = make_repo(
  116. tmp_path,
  117. [droplet()],
  118. tf_files={"modules/ok/main.tf": 'resource "digitalocean_droplet" "a" {}\n'},
  119. )
  120. assert cost_check.main(["--root", str(root)]) == 0
  121. assert "digitalocean: planned $6.00/mo" in capsys.readouterr().out
  122. def test_main_fails_over_approved_total(tmp_path):
  123. root = make_repo(tmp_path, [droplet("s-1vcpu-2gb")], approved_total=6.0)
  124. assert cost_check.main(["--root", str(root)]) == 1
  125. def test_main_fails_when_approval_exceeds_ceiling(tmp_path):
  126. root = make_repo(tmp_path, [droplet()], approved_total=40.0, ceiling=30.0)
  127. assert cost_check.main(["--root", str(root)]) == 1
  128. def test_main_reports_value_errors_as_failure(tmp_path):
  129. root = make_repo(tmp_path, [droplet("s-99vcpu-1tb")])
  130. assert cost_check.main(["--root", str(root)]) == 1
  131. # ---- allowlist, manifest and module reconciliation (probe-style repos) ----
  132. OK_DROPLET = {"modules/ok/main.tf": 'resource "digitalocean_droplet" "a" {}\n'}
  133. def run_main(root, capsys):
  134. code = cost_check.main(["--root", str(root)])
  135. return code, capsys.readouterr().err
  136. @pytest.mark.parametrize(
  137. "rtype",
  138. [
  139. "digitalocean_vpc_nat_gateway",
  140. "digitalocean_app",
  141. "digitalocean_container_registry",
  142. "digitalocean_kubernetes_node_pool",
  143. "digitalocean_cdn",
  144. ],
  145. )
  146. def test_unlisted_digitalocean_type_fails_naming_file_and_type(tmp_path, capsys, rtype):
  147. root = make_repo(
  148. tmp_path,
  149. [droplet()],
  150. tf_files={
  151. **OK_DROPLET,
  152. "stacks/10-access/x.tf": f'resource "{rtype}" "x" {{}}\n',
  153. },
  154. )
  155. code, err = run_main(root, capsys)
  156. assert code == 1
  157. assert "stacks/10-access/x.tf" in err and rtype in err
  158. @pytest.mark.parametrize(
  159. "rtype",
  160. [
  161. "digitalocean_project",
  162. "digitalocean_project_resources",
  163. "digitalocean_tag",
  164. "digitalocean_vpc",
  165. "digitalocean_firewall",
  166. "digitalocean_ssh_key",
  167. ],
  168. )
  169. def test_free_types_pass(tmp_path, capsys, rtype):
  170. root = make_repo(
  171. tmp_path,
  172. [droplet()],
  173. tf_files={
  174. **OK_DROPLET,
  175. "stacks/10-access/x.tf": f'resource "{rtype}" "x" {{}}\n',
  176. },
  177. )
  178. assert run_main(root, capsys)[0] == 0
  179. def test_non_digitalocean_types_are_not_this_gates_business(tmp_path, capsys):
  180. root = make_repo(
  181. tmp_path,
  182. [droplet()],
  183. tf_files={
  184. **OK_DROPLET,
  185. "stacks/10-access/x.tf": 'resource "twingate_group" "g" {}\n',
  186. },
  187. )
  188. assert run_main(root, capsys)[0] == 0
  189. def test_droplet_outside_the_allowed_file_fails(tmp_path, capsys):
  190. root = make_repo(
  191. tmp_path,
  192. [droplet()],
  193. tf_files={
  194. **OK_DROPLET,
  195. "stacks/10-access/d.tf": 'resource "digitalocean_droplet" "b" {}\n',
  196. },
  197. )
  198. code, err = run_main(root, capsys)
  199. assert code == 1 and "stacks/10-access/d.tf" in err
  200. def test_zero_manifests_fails(tmp_path, capsys):
  201. root = make_repo(tmp_path, [])
  202. (root / "stacks/10-access/cost.json").unlink()
  203. code, err = run_main(root, capsys)
  204. assert code == 1 and "manifest" in err
  205. def test_second_connector_module_fails(tmp_path, capsys):
  206. root = make_repo(tmp_path, [droplet()], connector_modules=2, tf_files=OK_DROPLET)
  207. code, err = run_main(root, capsys)
  208. assert code == 1 and "twingate-connector" in err
  209. def test_missing_connector_module_for_manifest_droplet_fails(tmp_path, capsys):
  210. root = make_repo(tmp_path, [droplet()], connector_modules=0, tf_files=OK_DROPLET)
  211. assert run_main(root, capsys)[0] == 1
  212. @pytest.mark.parametrize("meta", ["count = 5", 'for_each = toset(["a", "b"])'])
  213. def test_connector_module_with_count_or_for_each_fails(tmp_path, capsys, meta):
  214. root = make_repo(
  215. tmp_path,
  216. [droplet()],
  217. tf_files={
  218. **OK_DROPLET,
  219. "stacks/10-access/modules.tf": f'module "connector" {{\n source = "../../modules/twingate-connector"\n size = local.c.size\n {meta}\n}}\n',
  220. },
  221. )
  222. code, err = run_main(root, capsys)
  223. assert code == 1 and ("count" in err or "for_each" in err)
  224. @pytest.mark.parametrize(
  225. "source",
  226. [
  227. "git::https://example.invalid/x.git//modules/twingate-connector",
  228. "registry.example.invalid/acme/thing/digitalocean",
  229. "acme/thing/digitalocean",
  230. ],
  231. )
  232. def test_non_local_module_source_fails(tmp_path, capsys, source):
  233. root = make_repo(
  234. tmp_path,
  235. [droplet()],
  236. tf_files={
  237. **OK_DROPLET,
  238. "stacks/10-access/m.tf": f'module "far" {{\n source = "{source}"\n}}\n',
  239. },
  240. )
  241. code, err = run_main(root, capsys)
  242. assert code == 1 and "stacks/10-access/m.tf" in err
  243. def test_local_module_sources_pass(tmp_path, capsys):
  244. root = make_repo(
  245. tmp_path,
  246. [droplet()],
  247. tf_files={
  248. **OK_DROPLET,
  249. "stacks/10-access/m.tf": 'module "a" {\n source = "./x"\n}\nmodule "b" {\n source = "../../modules/vpc"\n}\n',
  250. },
  251. )
  252. assert run_main(root, capsys)[0] == 0
  253. def test_tf_json_files_fail(tmp_path, capsys):
  254. root = make_repo(
  255. tmp_path,
  256. [droplet()],
  257. tf_files={**OK_DROPLET, "stacks/10-access/x.tf.json": "{}"},
  258. )
  259. code, err = run_main(root, capsys)
  260. assert code == 1 and "x.tf.json" in err
  261. def test_tf_json_in_cache_dirs_is_ignored(tmp_path, capsys):
  262. root = make_repo(
  263. tmp_path,
  264. [droplet()],
  265. tf_files={
  266. **OK_DROPLET,
  267. ".venv/lib/x.tf.json": "{}",
  268. "stacks/10-access/.terraform/y.tf.json": "{}",
  269. },
  270. )
  271. assert run_main(root, capsys)[0] == 0
  272. def test_venv_directories_are_skipped(tmp_path):
  273. root = make_repo(
  274. tmp_path,
  275. [droplet()],
  276. tf_files={".venv/lib/x.tf": 'resource "digitalocean_app" "a" {}\n'},
  277. )
  278. assert cost_check.uncosted_sources(root, {}) == []
  279. def test_committed_backups_fraction_is_verified_with_its_source():
  280. # Issue 117: the committed table carries the DigitalOcean basic weekly
  281. # backup fraction as verified, with a source URL and a retrieval date.
  282. table = json.loads((Path(__file__).resolve().parents[1] / "docs/cost-prices.json").read_text())
  283. assert table["backups_fraction"] == 0.2
  284. assert table["backups_fraction_verified"] is True
  285. assert table["backups_source"].startswith("https://docs.digitalocean.com/products/backups/")
  286. assert table["backups_retrieved"] == "2026-10-19"
  287. # ---- backup plans the gate cannot price -------------------------------------
  288. VERIFIED = {**PRICES, "backups_fraction_verified": True}
  289. def planned(plan="weekly", **extra):
  290. res = droplet(backups=True)
  291. if plan is not None:
  292. res["backup_plan"] = plan
  293. res.update(extra)
  294. return res
  295. def test_weekly_backups_still_price_at_twenty_percent(tmp_path):
  296. root = make_repo(tmp_path, [planned("weekly")], prices=VERIFIED)
  297. assert cost_check.total_cost(root, VERIFIED) == 7.2
  298. def test_daily_backups_are_refused(tmp_path):
  299. root = make_repo(tmp_path, [planned("daily")], prices=VERIFIED)
  300. with pytest.raises(ValueError, match="daily"):
  301. cost_check.total_cost(root, VERIFIED)
  302. @pytest.mark.parametrize(
  303. "plan", [None, "", "hourly", "usage", "usage-based", "Weekly", 7, True, ["weekly"]]
  304. )
  305. def test_missing_or_unknown_backup_plan_is_refused(tmp_path, plan):
  306. # With backups on, DigitalOcean defaults to daily when no plan is stated,
  307. # so a missing plan is never read as weekly.
  308. root = make_repo(tmp_path, [planned(plan)], prices=VERIFIED)
  309. with pytest.raises(ValueError, match="backup_plan"):
  310. cost_check.total_cost(root, VERIFIED)
  311. @pytest.mark.parametrize(
  312. "extra",
  313. [
  314. {"backup_policy": {"plan": "weekly"}},
  315. {"backup_usage": {"gib": 10}},
  316. {"backup_hours": 12},
  317. ],
  318. )
  319. def test_usage_based_or_unknown_backup_shapes_are_refused(tmp_path, extra):
  320. root = make_repo(tmp_path, [planned("weekly", **extra)], prices=VERIFIED)
  321. with pytest.raises(ValueError, match="backup"):
  322. cost_check.total_cost(root, VERIFIED)
  323. @pytest.mark.parametrize("flag", ["true", "yes", 1, None, "false"])
  324. def test_backups_flag_must_be_a_boolean(tmp_path, flag):
  325. res = droplet()
  326. res["backups"] = flag
  327. root = make_repo(tmp_path, [res], prices=VERIFIED)
  328. with pytest.raises(ValueError, match="backups"):
  329. cost_check.total_cost(root, VERIFIED)
  330. def test_backup_plan_with_backups_off_is_refused(tmp_path):
  331. res = droplet()
  332. res["backup_plan"] = "daily"
  333. root = make_repo(tmp_path, [res], prices=VERIFIED)
  334. with pytest.raises(ValueError, match="backup"):
  335. cost_check.total_cost(root, VERIFIED)
  336. def droplet_tf(body):
  337. return {
  338. "modules/twingate-connector/main.tf": 'resource "digitalocean_droplet" "connector" {\n'
  339. + body
  340. + "}\n"
  341. }
  342. @pytest.mark.parametrize(
  343. "body",
  344. [
  345. " backups = true\n",
  346. " backups = var.backups\n",
  347. ' backup_policy {\n plan = "daily"\n }\n',
  348. ' backups = false\n backup_policy {\n plan = "weekly"\n }\n',
  349. ],
  350. )
  351. def test_source_enabling_backups_is_refused(tmp_path, body):
  352. root = make_repo(tmp_path, [droplet()], tf_files=droplet_tf(body))
  353. found = cost_check.block_problems(root)
  354. assert any("backup" in p for p in found), found
  355. @pytest.mark.parametrize("body", [" backups = false\n", ' size = "s-1vcpu-1gb"\n'])
  356. def test_source_with_backups_off_or_unset_is_not_flagged(tmp_path, body):
  357. root = make_repo(tmp_path, [droplet()], tf_files=droplet_tf(body))
  358. assert [p for p in cost_check.block_problems(root) if "backup" in p] == []
  359. # ---- source scan matches HCL syntax, not text -------------------------------
  360. HEREDOC_WORD = ' user_data = <<-EOT\n backup_policy {\n backups = true\n EOT\n'
  361. @pytest.mark.parametrize(
  362. "body",
  363. [
  364. ' tags = ["backup_policy"]\n backups = false\n',
  365. ' name = "backup_policy"\n',
  366. ' description = "uses backup_policy { plan = daily } and backups = true"\n',
  367. ' name = "x-${var.backup_policy}"\n',
  368. HEREDOC_WORD,
  369. " # backup_policy { plan = \"daily\" }\n // backups = true\n /* backup_policy */\n",
  370. " backups_enabled = true\n backups = false\n",
  371. ' tags = { backups = "true", backup_policy = "x" }\n',
  372. ' tags = [\n "backup_policy",\n ]\n',
  373. ],
  374. )
  375. def test_backup_words_in_strings_comments_heredocs_are_not_flagged(tmp_path, body):
  376. root = make_repo(tmp_path, [droplet()], tf_files=droplet_tf(body))
  377. assert [p for p in cost_check.block_problems(root) if "backup" in p] == []
  378. def test_backup_names_in_a_non_droplet_block_are_not_flagged(tmp_path):
  379. files = droplet_tf(" backups = false\n")
  380. files["modules/other/main.tf"] = (
  381. 'resource "twingate_resource" "r" {\n backups = true\n'
  382. " backup_policy {\n plan = \"daily\"\n }\n}\n"
  383. )
  384. root = make_repo(tmp_path, [droplet()], tf_files=files)
  385. assert [p for p in cost_check.block_problems(root) if "backup" in p] == []
  386. @pytest.mark.parametrize(
  387. "body",
  388. [
  389. ' backup_policy {\n plan = "weekly"\n }\n',
  390. ' backup_policy{\n plan = "weekly"\n }\n',
  391. ' tags = ["a"]\n\n backup_policy {\n plan = "daily"\n }\n',
  392. ' backup_policy = { plan = "daily" }\n',
  393. ' backup_policy = {}\n',
  394. " backups = true\n",
  395. " backups=true\n",
  396. " backups = (\n true\n )\n",
  397. " backups = var.x\n",
  398. " backups = \"true\"\n",
  399. ],
  400. )
  401. def test_real_backup_syntax_is_still_refused(tmp_path, body):
  402. root = make_repo(tmp_path, [droplet()], tf_files=droplet_tf(body))
  403. found = cost_check.block_problems(root)
  404. assert any("backup" in p for p in found), found
  405. # ---- Spaces: a flat, manifest-priced bucket behind a stack switch (#113) ----
  406. SPACES_PRICES = {**PRICES, "spaces": {"monthly": 5.0}}
  407. SPACES_ALLOWED = {"digitalocean_spaces_bucket": ["modules/spaces-bucket/main.tf"]}
  408. SPACES_MODULE_TF = {
  409. "modules/ok/main.tf": 'resource "digitalocean_droplet" "a" {}\n',
  410. "modules/spaces-bucket/main.tf": (
  411. 'resource "digitalocean_spaces_bucket" "this" {\n name = "x"\n}\n'
  412. 'resource "digitalocean_spaces_key" "this" {\n name = "k"\n}\n'
  413. ),
  414. }
  415. SPACES_LOCALS = (
  416. "locals {\n on = var.spaces_enabled ? 1 : 0\n"
  417. ' cost = jsondecode(file("${path.module}/cost.json"))\n}\n'
  418. )
  419. SPACES_OUT = (
  420. 'output "spaces_enabled" {\n value = var.spaces_enabled\n precondition {\n'
  421. " condition = !var.spaces_enabled || (\n"
  422. ' length([for r in local.cost.resources : r if r.kind == "spaces"]) == 1\n )\n'
  423. ' error_message = "price it"\n }\n}\n'
  424. )
  425. SPACES_CALL = 'module "state" {\n source = "../../modules/spaces-bucket"\n%s}\n'
  426. SPACES_ENTRY = {"name": "state-bucket", "kind": "spaces"}
  427. def spaces_repo(tmp_path, entries=(), body=" count = local.on\n", locals_=SPACES_LOCALS,
  428. out=SPACES_OUT, approved_total=6.0, extra=None,
  429. source="../../modules/spaces-bucket"):
  430. files = {
  431. **SPACES_MODULE_TF,
  432. "stacks/10-access/spaces.tf": locals_ + (SPACES_CALL % body).replace(
  433. "../../modules/spaces-bucket", source
  434. ),
  435. "stacks/10-access/spaces_out.tf": out,
  436. **(extra or {}),
  437. }
  438. return make_repo(
  439. tmp_path, [droplet(), *entries], approved_total=approved_total,
  440. tf_files=files, prices=SPACES_PRICES, allowed=SPACES_ALLOWED,
  441. )
  442. def test_a_spaces_entry_is_priced_flat_from_the_price_table(tmp_path):
  443. root = make_repo(tmp_path, [droplet(), SPACES_ENTRY], prices=SPACES_PRICES)
  444. assert cost_check.total_cost(root, SPACES_PRICES) == 11.0
  445. def test_a_spaces_entry_cannot_set_its_own_price(tmp_path):
  446. root = make_repo(
  447. tmp_path, [{**SPACES_ENTRY, "monthly": 0.01, "price": 0}], prices=SPACES_PRICES
  448. )
  449. assert cost_check.total_cost(root, SPACES_PRICES) == 5.0
  450. def test_a_spaces_entry_without_a_table_price_fails_closed(tmp_path):
  451. root = make_repo(tmp_path, [SPACES_ENTRY])
  452. with pytest.raises(ValueError, match="no price for spaces"):
  453. cost_check.total_cost(root, PRICES)
  454. @pytest.mark.parametrize("bad", [-1, "five", None, float("nan"), True])
  455. def test_a_malformed_spaces_price_fails_closed(tmp_path, bad):
  456. prices = {**PRICES, "spaces": {"monthly": bad}}
  457. root = make_repo(tmp_path, [SPACES_ENTRY], prices=prices)
  458. with pytest.raises(ValueError):
  459. cost_check.total_cost(root, prices)
  460. def test_spaces_is_not_priced_on_another_cloud(tmp_path):
  461. with pytest.raises(ValueError, match="no price model"):
  462. cost_check.resource_cost(SPACES_ENTRY, SPACES_PRICES, provider="aws")
  463. def test_spaces_key_is_a_free_type(tmp_path, capsys):
  464. root = make_repo(
  465. tmp_path, [droplet()],
  466. tf_files={**OK_DROPLET, "stacks/10-access/x.tf": 'resource "digitalocean_spaces_key" "x" {}\n'},
  467. )
  468. code, err = run_main(root, capsys)
  469. assert code == 0, err
  470. def test_spaces_bucket_outside_the_allowed_file_fails(tmp_path, capsys):
  471. root = make_repo(
  472. tmp_path, [droplet()],
  473. tf_files={**OK_DROPLET, "stacks/10-access/x.tf": 'resource "digitalocean_spaces_bucket" "x" {}\n'},
  474. allowed=SPACES_ALLOWED,
  475. )
  476. code, err = run_main(root, capsys)
  477. assert code == 1
  478. assert "stacks/10-access/x.tf" in err and "digitalocean_spaces_bucket" in err
  479. def test_spaces_bucket_with_no_allowed_file_at_all_fails(tmp_path, capsys):
  480. root = make_repo(
  481. tmp_path, [droplet()],
  482. tf_files={**OK_DROPLET, "modules/spaces-bucket/main.tf": 'resource "digitalocean_spaces_bucket" "x" {}\n'},
  483. )
  484. code, err = run_main(root, capsys)
  485. assert code == 1 and "digitalocean_spaces_bucket" in err
  486. @pytest.mark.parametrize("meta", ["count = 1", "count = var.n", 'for_each = toset(["a"])'])
  487. def test_count_or_for_each_on_the_bucket_resource_is_refused(tmp_path, capsys, meta):
  488. root = make_repo(
  489. tmp_path, [droplet()],
  490. tf_files={
  491. **OK_DROPLET,
  492. "modules/spaces-bucket/main.tf": f'resource "digitalocean_spaces_bucket" "this" {{\n {meta}\n}}\n',
  493. },
  494. allowed=SPACES_ALLOWED,
  495. )
  496. code, err = run_main(root, capsys)
  497. assert code == 1 and "digitalocean_spaces_bucket" in err and ("count" in err or "for_each" in err)
  498. def test_an_inactive_bucket_module_adds_nothing(tmp_path, capsys):
  499. root = spaces_repo(tmp_path)
  500. assert cost_check.total_cost(root, SPACES_PRICES) == 6.0
  501. code, err = run_main(root, capsys)
  502. assert code == 0, err
  503. def test_an_active_bucket_module_is_priced_and_held_to_the_approved_total(tmp_path, capsys):
  504. root = spaces_repo(tmp_path, entries=[SPACES_ENTRY], approved_total=6.0)
  505. code, err = run_main(root, capsys)
  506. assert code == 1 and "approved" in err
  507. root = spaces_repo(tmp_path / "ok", entries=[SPACES_ENTRY], approved_total=11.0)
  508. code, err = run_main(root, capsys)
  509. assert code == 0, err
  510. @pytest.mark.parametrize(
  511. "body",
  512. [
  513. " count = 2\n",
  514. " count = var.n\n",
  515. ' for_each = toset(["a"])\n',
  516. "",
  517. ],
  518. )
  519. def test_a_bucket_module_call_must_use_the_stack_switch(tmp_path, capsys, body):
  520. root = spaces_repo(tmp_path, body=body)
  521. code, err = run_main(root, capsys)
  522. assert code == 1 and ("spaces-bucket" in err or "state" in err)
  523. def test_the_switch_must_be_a_variable_ternary(tmp_path, capsys):
  524. root = spaces_repo(tmp_path, locals_=SPACES_LOCALS.replace("var.spaces_enabled ? 1 : 0", "1"))
  525. code, err = run_main(root, capsys)
  526. assert code == 1 and "0 spaces" in err
  527. def test_the_switch_needs_the_manifest_precondition(tmp_path, capsys):
  528. root = spaces_repo(tmp_path, out=SPACES_OUT.replace("!var.spaces_enabled ||", "true ||"))
  529. code, err = run_main(root, capsys)
  530. assert code == 1 and "0 spaces" in err
  531. def test_spaces_entries_must_match_the_module_calls(tmp_path, capsys):
  532. root = spaces_repo(
  533. tmp_path, entries=[SPACES_ENTRY, {**SPACES_ENTRY, "name": "b"}], approved_total=16.0
  534. )
  535. code, err = run_main(root, capsys)
  536. assert code == 1 and "2 spaces manifest entr" in err
  537. @pytest.mark.parametrize(
  538. "source",
  539. [
  540. "../../modules/./spaces-bucket",
  541. "../../modules//spaces-bucket",
  542. "../../modules/spaces-bucket/",
  543. "../../modules/spaces-bucket/.",
  544. "../../modules/x/../spaces-bucket",
  545. "./../../modules/spaces-bucket",
  546. "../../modules/copy/spaces-bucket",
  547. "../10-access/../../modules/other/spaces-bucket",
  548. ],
  549. )
  550. def test_a_bucket_module_source_must_be_the_one_canonical_path(tmp_path, capsys, source):
  551. root = spaces_repo(tmp_path, source=source)
  552. assert cost_check.spaces_module_problems(root), source
  553. code, err = run_main(root, capsys)
  554. assert code == 1 and "modules/spaces-bucket" in err
  555. def test_the_canonical_source_still_passes(tmp_path):
  556. assert cost_check.spaces_module_problems(spaces_repo(tmp_path)) == []
  557. def test_a_bucket_call_in_a_wrapper_module_without_a_manifest_is_refused(tmp_path, capsys):
  558. wrapper = {
  559. "modules/wrapper/main.tf": (
  560. 'module "state" {\n source = "../spaces-bucket"\n count = local.on\n}\n'
  561. )
  562. }
  563. root = spaces_repo(tmp_path, extra=wrapper)
  564. problems = cost_check.spaces_module_problems(root)
  565. assert any("modules/wrapper" in p and "no cost.json" in p for p in problems), problems
  566. code, err = run_main(root, capsys)
  567. assert code == 1 and "modules/wrapper" in err
  568. def test_a_switch_proved_for_the_edge_kind_does_not_satisfy_spaces(tmp_path):
  569. edge_out = SPACES_OUT.replace('r.kind == "spaces"', 'r.kind == "droplet"')
  570. root = spaces_repo(tmp_path, out=edge_out)
  571. assert any("0 spaces" in p for p in cost_check.spaces_module_problems(root))
  572. assert cost_check.edge_switch_verified(root, "stacks/10-access")
  573. assert not cost_check.edge_switch_verified(root, "stacks/10-access", kind="spaces")
  574. # ---- the committed files carry the Spaces price and approval (#113) ----
  575. REPO = Path(__file__).resolve().parents[1]
  576. def test_committed_spaces_price_is_five_dollars_with_a_source_and_date():
  577. spaces = json.loads((REPO / "docs/cost-prices.json").read_text())["spaces"]
  578. assert spaces["monthly"] == 5.0
  579. assert spaces["source"].startswith("https://docs.digitalocean.com/products/spaces/")
  580. assert len(spaces["retrieved"]) == 10 and spaces["retrieved"].startswith("2026-")
  581. def test_committed_approval_allows_only_the_bucket_module_for_spaces():
  582. do = json.loads((REPO / "docs/stages/approved.json").read_text())["providers"]["digitalocean"]
  583. assert do["allowed_sources"]["digitalocean_spaces_bucket"] == ["modules/spaces-bucket/main.tf"]
  584. assert "digitalocean_spaces_key" not in do["allowed_sources"]
  585. assert do["approved_monthly_total"] <= 29.0
  586. # ---- docker-host: the workload droplet behind a stack switch (#111) ----------
  587. DOCKER_PRICES = {**PRICES, "droplets": {**PRICES["droplets"]}}
  588. DOCKER_ALLOWED = {
  589. "digitalocean_droplet": ["modules/ok/main.tf", "modules/docker-host/main.tf"],
  590. }
  591. DOCKER_MODULE_TF = {
  592. "modules/ok/main.tf": 'resource "digitalocean_droplet" "a" {}\n',
  593. "modules/docker-host/main.tf": 'resource "digitalocean_droplet" "workload" {\n name = "x"\n}\n',
  594. }
  595. DOCKER_FILTER = '[for r in local.cost.resources : r if r.name == "workload" && r.kind == "droplet"]'
  596. DOCKER_SIZE_EXPR = (
  597. "length(local.priced_workload) == 1 ? local.priced_workload[0].size"
  598. " : local.cost.planned.workload.size"
  599. )
  600. DOCKER_LOCALS = (
  601. "locals {\n on = var.workload_enabled ? 1 : 0\n"
  602. ' cost = jsondecode(file("${path.module}/cost.json"))\n'
  603. f" priced_workload = {DOCKER_FILTER}\n"
  604. f" workload_size = {DOCKER_SIZE_EXPR}\n}}\n"
  605. )
  606. DOCKER_OUT = (
  607. 'output "workload_enabled" {\n value = var.workload_enabled\n precondition {\n'
  608. " condition = !var.workload_enabled || (\n"
  609. ' length([for r in local.cost.resources : r if r.name == "workload" && r.kind == "droplet"]) == 1\n'
  610. " )\n"
  611. ' error_message = "price it"\n }\n}\n'
  612. )
  613. DOCKER_CALL = (
  614. 'module "workload" {\n source = "../../modules/docker-host"\n%s'
  615. " size = local.workload_size\n}\n"
  616. )
  617. DOCKER_ENTRY = {"name": "workload", "kind": "droplet", "size": "s-1vcpu-2gb", "backups": False}
  618. def docker_repo(tmp_path, entries=(), body=" count = local.on\n", locals_=DOCKER_LOCALS,
  619. out=DOCKER_OUT, approved_total=6.0, extra=None,
  620. source="../../modules/docker-host", call=DOCKER_CALL):
  621. files = {
  622. **DOCKER_MODULE_TF,
  623. "stacks/10-access/docker.tf": locals_ + (call % body).replace(
  624. "../../modules/docker-host", source
  625. ),
  626. "stacks/10-access/docker_out.tf": out,
  627. **(extra or {}),
  628. }
  629. return make_repo(
  630. tmp_path, [droplet(), *entries], approved_total=approved_total,
  631. tf_files=files, prices=DOCKER_PRICES, allowed=DOCKER_ALLOWED, connector_modules=1,
  632. )
  633. def test_an_inactive_docker_host_adds_nothing(tmp_path, capsys):
  634. root = docker_repo(tmp_path)
  635. assert cost_check.total_cost(root, DOCKER_PRICES) == 6.0
  636. assert cost_check.docker_module_problems(root)[0] == []
  637. code, err = run_main(root, capsys)
  638. assert code == 0, err
  639. def test_an_active_docker_host_is_priced_from_the_table_and_held_to_the_total(tmp_path, capsys):
  640. root = docker_repo(tmp_path, entries=[DOCKER_ENTRY])
  641. assert cost_check.total_cost(root, DOCKER_PRICES) == 18.0
  642. code, err = run_main(root, capsys)
  643. assert code == 1 and "approved" in err
  644. root = docker_repo(tmp_path / "ok", entries=[DOCKER_ENTRY], approved_total=18.0)
  645. code, err = run_main(root, capsys)
  646. assert code == 0, err
  647. @pytest.mark.parametrize(
  648. "body",
  649. [" count = 2\n", " count = var.n\n", ' for_each = toset(["a"])\n', ""],
  650. )
  651. def test_a_docker_host_call_must_use_the_stack_switch(tmp_path, capsys, body):
  652. root = docker_repo(tmp_path, body=body)
  653. assert cost_check.docker_module_problems(root)[0]
  654. code, err = run_main(root, capsys)
  655. assert code == 1 and ("docker-host" in err or "workload" in err)
  656. @pytest.mark.parametrize("size", ['size = "s-1vcpu-1gb"', "size = var.size", "size = local.a.b.size"])
  657. def test_a_docker_host_size_must_be_a_plain_local_reference(tmp_path, capsys, size):
  658. call = DOCKER_CALL.replace("size = local.workload_size", size)
  659. root = docker_repo(tmp_path, call=call)
  660. assert any("size" in p for p in cost_check.docker_module_problems(root)[0]), size
  661. code, err = run_main(root, capsys)
  662. assert code == 1 and "docker-host" in err
  663. def test_a_docker_host_without_a_size_is_refused(tmp_path):
  664. root = docker_repo(tmp_path, call=DOCKER_CALL.replace(" size = local.workload_size\n", ""))
  665. assert any("size" in p for p in cost_check.docker_module_problems(root)[0])
  666. def test_the_docker_switch_must_be_a_variable_ternary(tmp_path, capsys):
  667. root = docker_repo(tmp_path, locals_=DOCKER_LOCALS.replace("var.workload_enabled ? 1 : 0", "1"))
  668. code, err = run_main(root, capsys)
  669. assert code == 1 and "0 workload" in err
  670. def test_the_docker_switch_needs_the_manifest_precondition(tmp_path, capsys):
  671. root = docker_repo(tmp_path, out=DOCKER_OUT.replace("!var.workload_enabled ||", "true ||"))
  672. code, err = run_main(root, capsys)
  673. assert code == 1 and "0 workload" in err
  674. @pytest.mark.parametrize(
  675. "swap",
  676. [
  677. ('r.name == "workload" && r.kind == "droplet"', 'r.kind == "spaces"'),
  678. ('r.name == "workload" && r.kind == "droplet"', "true"),
  679. ('r.name == "workload" && r.kind == "droplet"', 'r.kind == "droplet"'),
  680. ('r.name == "workload" && r.kind == "droplet"', 'r.name == "workload"'),
  681. ],
  682. )
  683. def test_a_switch_proved_for_another_kind_does_not_satisfy_docker(tmp_path, swap):
  684. root = docker_repo(tmp_path, out=DOCKER_OUT.replace(*swap))
  685. assert any("0 workload" in p for p in cost_check.docker_module_problems(root)[0])
  686. assert not cost_check.edge_switch_verified(root, "stacks/10-access", kind="docker")
  687. def test_the_docker_proof_is_specific_to_docker_not_to_the_edge_check(tmp_path):
  688. root = docker_repo(tmp_path)
  689. assert cost_check.edge_switch_verified(root, "stacks/10-access", kind="docker")
  690. spaces_out = DOCKER_OUT.replace(
  691. 'r.name == "workload" && r.kind == "droplet"', 'r.kind == "spaces"'
  692. )
  693. root = docker_repo(tmp_path / "s", out=spaces_out)
  694. assert cost_check.edge_switch_verified(root, "stacks/10-access")
  695. assert not cost_check.edge_switch_verified(root, "stacks/10-access", kind="docker")
  696. def test_docker_entries_must_match_the_module_calls(tmp_path, capsys):
  697. root = docker_repo(
  698. tmp_path, entries=[DOCKER_ENTRY, {**DOCKER_ENTRY, "name": "workload"}], approved_total=30.0
  699. )
  700. problems = cost_check.docker_module_problems(root)[0]
  701. assert any("2 workload" in p for p in problems), problems
  702. @pytest.mark.parametrize(
  703. "source",
  704. [
  705. "../../modules/./docker-host",
  706. "../../modules//docker-host",
  707. "../../modules/docker-host/",
  708. "../../modules/docker-host/.",
  709. "../../modules/x/../docker-host",
  710. "./../../modules/docker-host",
  711. "../../modules/copy/docker-host",
  712. "../10-access/../../modules/other/docker-host",
  713. ],
  714. )
  715. def test_a_docker_host_source_must_be_the_one_canonical_path(tmp_path, capsys, source):
  716. root = docker_repo(tmp_path, source=source)
  717. assert cost_check.docker_module_problems(root)[0], source
  718. code, err = run_main(root, capsys)
  719. assert code == 1 and "modules/docker-host" in err
  720. def test_the_canonical_docker_source_still_passes(tmp_path):
  721. assert cost_check.docker_module_problems(docker_repo(tmp_path))[0] == []
  722. def test_a_docker_host_call_in_a_wrapper_module_without_a_manifest_is_refused(tmp_path, capsys):
  723. wrapper = {
  724. "modules/wrapper/main.tf": (
  725. 'module "workload" {\n source = "../docker-host"\n count = local.on\n'
  726. " size = local.workload_size\n}\n"
  727. )
  728. }
  729. root = docker_repo(tmp_path, extra=wrapper)
  730. problems = cost_check.docker_module_problems(root)[0]
  731. assert any("modules/wrapper" in p and "no cost.json" in p for p in problems), problems
  732. code, err = run_main(root, capsys)
  733. assert code == 1 and "modules/wrapper" in err
  734. def test_the_docker_droplet_is_not_a_connector_machine(tmp_path, capsys):
  735. # One connector module and one connector entry plus the workload entry:
  736. # the workload droplet is reconciled by docker_module_problems, not as a connector.
  737. root = docker_repo(tmp_path, entries=[DOCKER_ENTRY], approved_total=18.0)
  738. code, err = run_main(root, capsys)
  739. assert code == 0, err
  740. # With no docker-host call, the same workload entry would need a connector block.
  741. root = make_repo(
  742. tmp_path / "x", [droplet(), DOCKER_ENTRY], approved_total=18.0,
  743. tf_files=DOCKER_MODULE_TF, prices=DOCKER_PRICES, allowed=DOCKER_ALLOWED,
  744. connector_modules=1,
  745. )
  746. code, err = run_main(root, capsys)
  747. assert code == 1 and "twingate-connector module block" in err
  748. def test_committed_approval_allows_the_docker_host_droplet_source():
  749. do = json.loads((REPO / "docs/stages/approved.json").read_text())["providers"]["digitalocean"]
  750. assert do["allowed_sources"]["digitalocean_droplet"] == [
  751. "modules/twingate-connector/main.tf",
  752. "modules/edge-host/main.tf",
  753. "modules/docker-host/main.tf",
  754. ]
  755. assert do["approved_monthly_total"] == 12.0
  756. def test_the_committed_workload_stack_is_off_and_adds_nothing():
  757. prices = json.loads((REPO / "docs/cost-prices.json").read_text())
  758. assert prices["droplets"]["s-1vcpu-2gb"] == 12
  759. assert cost_check.docker_module_problems(REPO)[0] == []
  760. assert cost_check.edge_switch_verified(REPO, "stacks/30-workloads", kind="docker")
  761. # ---- docker-host review fixes: size from the manifest, exact precondition ----
  762. def _with_locals(**changes):
  763. text = DOCKER_LOCALS
  764. for old, new in changes.items():
  765. text = text.replace(DOCKER_FILTER if old == "filter" else DOCKER_SIZE_EXPR, new, 1)
  766. return text
  767. @pytest.mark.parametrize(
  768. "locals_",
  769. [
  770. # a literal
  771. DOCKER_LOCALS.replace(DOCKER_SIZE_EXPR, '"s-1vcpu-2gb"'),
  772. # a variable
  773. DOCKER_LOCALS.replace(DOCKER_SIZE_EXPR, "var.size"),
  774. # derived from the manifest's planned block only (never the priced entry)
  775. DOCKER_LOCALS.replace(DOCKER_SIZE_EXPR, "local.cost.planned.workload.size"),
  776. # a literal fallback
  777. DOCKER_LOCALS.replace("local.cost.planned.workload.size", '"s-1vcpu-2gb"'),
  778. # wrong entry index or attribute
  779. DOCKER_LOCALS.replace("priced_workload[0].size", "priced_workload[0].name"),
  780. # a different local than the filtered manifest list
  781. DOCKER_LOCALS.replace("length(local.priced_workload) == 1", "length(local.other) == 1"),
  782. # the filter does not select the workload droplet
  783. DOCKER_LOCALS.replace('r.name == "workload" && r.kind == "droplet"', "true"),
  784. DOCKER_LOCALS.replace('r.kind == "droplet"', 'r.kind == "spaces"'),
  785. # the filter list is not derived from the manifest
  786. DOCKER_LOCALS.replace("local.cost.resources", "var.resources"),
  787. ],
  788. )
  789. def test_the_docker_size_must_derive_from_the_manifest_entry(tmp_path, capsys, locals_):
  790. root = docker_repo(tmp_path, locals_=locals_)
  791. problems = cost_check.docker_module_problems(root)[0]
  792. assert any("size" in p and "manifest" in p for p in problems), problems
  793. code, err = run_main(root, capsys)
  794. assert code == 1 and "docker-host" in err
  795. def test_a_size_local_defined_only_in_a_comment_does_not_count(tmp_path):
  796. locals_ = DOCKER_LOCALS.replace(
  797. f" workload_size = {DOCKER_SIZE_EXPR}\n",
  798. f' workload_size = "s-1vcpu-2gb"\n # workload_size = {DOCKER_SIZE_EXPR}\n',
  799. )
  800. root = docker_repo(tmp_path, locals_=locals_)
  801. assert any("size" in p for p in cost_check.docker_module_problems(root)[0])
  802. def test_a_size_local_defined_twice_is_refused(tmp_path):
  803. locals_ = DOCKER_LOCALS + 'locals {\n workload_size = "s-1vcpu-1gb"\n}\n'
  804. root = docker_repo(tmp_path, locals_=locals_)
  805. assert any("size" in p for p in cost_check.docker_module_problems(root)[0])
  806. def test_a_planned_size_missing_from_the_price_table_is_refused(tmp_path, capsys):
  807. root = docker_repo(tmp_path)
  808. manifest = root / "stacks/10-access/cost.json"
  809. data = json.loads(manifest.read_text())
  810. data["planned"] = {"workload": {"size": "s-99vcpu-1tb"}}
  811. manifest.write_text(json.dumps(data))
  812. problems = cost_check.docker_module_problems(root)[0]
  813. assert any("planned" in p and "s-99vcpu-1tb" in p for p in problems), problems
  814. def test_a_planned_size_in_the_price_table_passes(tmp_path):
  815. root = docker_repo(tmp_path)
  816. manifest = root / "stacks/10-access/cost.json"
  817. data = json.loads(manifest.read_text())
  818. data["planned"] = {"workload": {"size": "s-1vcpu-2gb"}}
  819. manifest.write_text(json.dumps(data))
  820. assert cost_check.docker_module_problems(root)[0] == []
  821. def _out(condition, extra="", where="output"):
  822. return (
  823. f'{where} "workload_enabled" {{\n value = var.workload_enabled\n{extra}'
  824. f" precondition {{\n condition = {condition}\n"
  825. ' error_message = "price it"\n }\n}\n'
  826. )
  827. GOOD_COND = f"!var.workload_enabled || length({DOCKER_FILTER}) == 1"
  828. def test_the_exact_condition_forms_are_accepted(tmp_path):
  829. for cond in (
  830. GOOD_COND,
  831. f"!var.workload_enabled || (\n length({DOCKER_FILTER}) == 1\n )",
  832. (
  833. '!var.workload_enabled||length( [ for q in local.cost.resources : q if q.name == "workload" '
  834. '&& q.kind == "droplet" ] )==1'
  835. ),
  836. ):
  837. root = docker_repo(tmp_path / str(abs(hash(cond))), out=_out(cond))
  838. assert cost_check.docker_module_problems(root)[0] == [], cond
  839. @pytest.mark.parametrize(
  840. "out",
  841. [
  842. # tokens only in an error message or another attribute; condition is true
  843. _out("true").replace('"price it"', f'"length({DOCKER_FILTER}) == 1 !var.workload_enabled ||"'),
  844. # tokens only in a comment
  845. _out("true").replace("value =", f"# !var.workload_enabled || length({DOCKER_FILTER}) == 1\n value ="),
  846. # tokens in the value attribute of the output
  847. _out("true", extra=f" description = \"!var.workload_enabled || length({DOCKER_FILTER}) == 1\"\n"),
  848. # the right text, but in a resource lifecycle precondition, not an output
  849. _out(GOOD_COND, where="resource \"terraform_data\"").replace(
  850. 'resource "terraform_data" "workload_enabled"', 'resource "terraform_data" "x"'
  851. ),
  852. # the condition is weakened or reshaped
  853. _out(GOOD_COND + " || true"),
  854. _out("true && " + GOOD_COND),
  855. _out(GOOD_COND.replace("== 1", "== 2")),
  856. _out(GOOD_COND.replace("== 1", ">= 0")),
  857. _out(GOOD_COND.replace("!var.workload_enabled", "var.workload_enabled")),
  858. _out(GOOD_COND.replace("||", "&&")),
  859. _out(GOOD_COND.replace("!var.workload_enabled", "!var.other")),
  860. _out(GOOD_COND.replace('&& r.kind == "droplet"', '|| r.kind == "droplet"')),
  861. _out(GOOD_COND.replace("local.cost.resources", "local.priced_workload")),
  862. _out(GOOD_COND.replace("[for r in", "[for q in")),
  863. ],
  864. )
  865. def test_the_docker_precondition_must_be_the_exact_condition(tmp_path, out):
  866. root = docker_repo(tmp_path, out=out)
  867. assert any("0 workload" in p for p in cost_check.docker_module_problems(root)[0])
  868. assert not cost_check.edge_switch_verified(root, "stacks/10-access", kind="docker")
  869. def test_the_precondition_of_another_output_does_not_count_for_the_switch_output(tmp_path):
  870. other = _out(GOOD_COND).replace('"workload_enabled"', '"somewhere_else"')
  871. root = docker_repo(tmp_path, out=other)
  872. # The condition is exact but guards another output, which is still a plan-time check on the
  873. # same switch variable, so it counts; a condition on a different variable does not.
  874. assert cost_check.docker_module_problems(root)[0] == []
  875. bad = other.replace("!var.workload_enabled", "!var.other_flag")
  876. root = docker_repo(tmp_path / "b", out=bad)
  877. assert cost_check.docker_module_problems(root)[0]