| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324 |
- """Cost gate across providers: manifests, plans, approval and the shared ceiling."""
- import json
- import sys
- from pathlib import Path
- import pytest
- sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts"))
- import cost_check
- DO_PRICES = {
- "backups_fraction": 0.2,
- "backups_fraction_verified": False,
- "droplets": {"s-1vcpu-1gb": 6},
- }
- AWS_PRICES = json.loads(
- (Path(__file__).resolve().parents[1] / "docs/cost-prices/aws.json").read_text()
- )
- CONNECTOR = (
- 'module "c{i}" {{\n source = "../../../modules/aws/twingate-connector"\n'
- " instance_type = local.c.type\n}}\n"
- )
- DO_CONNECTOR = (
- 'module "c{i}" {{\n source = "../../modules/twingate-connector"\n'
- " size = local.c.size\n}}\n"
- )
- def instance(name="connector-a", itype="t4g.micro", root_gb=8, public_ip=True):
- return {
- "name": name,
- "kind": "instance",
- "type": itype,
- "root_gb": root_gb,
- "public_ip": public_ip,
- }
- def build(
- tmp_path, *, aws=None, do_droplets=1, aws_cap=21.0, aws_active=False, ceiling=30.0
- ):
- """A repo with a DigitalOcean stack and (optionally) an AWS stack."""
- (tmp_path / "docs/stages").mkdir(parents=True)
- (tmp_path / "docs/cost-prices").mkdir(parents=True)
- (tmp_path / "docs/cost-prices.json").write_text(json.dumps(DO_PRICES))
- (tmp_path / "docs/cost-prices/aws.json").write_text(json.dumps(AWS_PRICES))
- providers = {
- "digitalocean": {
- "approved_monthly_total": 6.0 * do_droplets,
- "active": True,
- "allowed_sources": {
- "digitalocean_droplet": ["modules/twingate-connector/main.tf"]
- },
- }
- }
- if aws is not None:
- providers["aws"] = {
- "approved_monthly_total": aws_cap,
- "active": aws_active,
- "allowed_sources": {
- "aws_instance": ["modules/aws/twingate-connector/main.tf"]
- },
- }
- (tmp_path / "docs/stages/approved.json").write_text(
- json.dumps({"stage": 1, "ceiling": ceiling, "providers": providers})
- )
- do = tmp_path / "stacks/10-access"
- do.mkdir(parents=True)
- do.joinpath("cost.json").write_text(
- json.dumps(
- {
- "resources": [
- {
- "name": f"d{i}",
- "kind": "droplet",
- "size": "s-1vcpu-1gb",
- "backups": False,
- }
- for i in range(do_droplets)
- ]
- }
- )
- )
- do.joinpath("m.tf").write_text(
- "".join(DO_CONNECTOR.format(i=i) for i in range(do_droplets))
- )
- for rel in (
- "modules/twingate-connector/main.tf",
- "modules/aws/twingate-connector/main.tf",
- ):
- p = tmp_path / rel
- p.parent.mkdir(parents=True, exist_ok=True)
- p.write_text(
- 'resource "digitalocean_droplet" "a" {}\n'
- if "aws" not in rel
- else 'resource "aws_instance" "a" {}\n'
- )
- if aws is not None:
- stack = tmp_path / "stacks/aws/10-access"
- stack.mkdir(parents=True)
- stack.joinpath("cost.json").write_text(json.dumps({"resources": aws}))
- stack.joinpath("m.tf").write_text(
- "".join(
- CONNECTOR.format(i=i)
- for i in range(sum(1 for r in aws if r["kind"] == "instance"))
- )
- )
- return tmp_path
- def run(root, capsys, *args):
- code = cost_check.main(["--root", str(root), *args])
- return code, capsys.readouterr()
- TWO = [instance("connector-a"), instance("connector-b")]
- def test_the_two_connector_aws_stack_costs_the_phase_zero_figure(tmp_path):
- root = build(tmp_path, aws=TWO)
- assert cost_check.provider_totals(root)["aws"] == 20.84
- def test_aws_stack_in_a_provider_directory_is_found_and_counted(tmp_path, capsys):
- root = build(tmp_path, aws=TWO)
- code, out = run(root, capsys)
- assert code == 0, out.err
- assert "aws: planned $20.84/mo" in out.out
- def test_aws_manifest_over_its_approved_figure_fails(tmp_path, capsys):
- root = build(tmp_path, aws=TWO, aws_cap=15.0)
- code, out = run(root, capsys)
- assert code == 1 and "aws: planned $20.84 is above approved $15.00" in out.err
- def test_aws_approval_above_the_ceiling_fails(tmp_path, capsys):
- root = build(tmp_path, aws=TWO, aws_cap=35.0)
- code, out = run(root, capsys)
- assert code == 1 and "above the ceiling" in out.err
- def test_two_active_providers_together_above_the_ceiling_fail(tmp_path, capsys):
- root = build(tmp_path, aws=TWO, do_droplets=2, aws_cap=21.0, aws_active=True)
- code, out = run(root, capsys)
- assert code == 1 and "active providers add up to $33.00" in out.err
- def test_the_same_providers_pass_when_aws_is_inactive(tmp_path, capsys):
- root = build(tmp_path, aws=TWO, do_droplets=2, aws_cap=21.0, aws_active=False)
- assert run(root, capsys)[0] == 0
- def test_a_stack_directory_without_a_manifest_fails(tmp_path, capsys):
- root = build(tmp_path, aws=TWO)
- (root / "stacks/aws/10-access/cost.json").unlink()
- code, out = run(root, capsys)
- assert (
- code == 1
- and "stacks/aws/10-access: has OpenTofu files but no cost.json" in out.err
- )
- def test_an_unapproved_provider_with_paid_types_fails(tmp_path, capsys):
- root = build(tmp_path, aws=None)
- (root / "stacks/10-access/x.tf").write_text('resource "aws_instance" "x" {}\n')
- code, out = run(root, capsys)
- assert code == 1 and "provider aws is not in approved.json" in out.err
- def test_a_provider_with_a_manifest_but_no_approval_fails(tmp_path, capsys):
- root = build(tmp_path, aws=TWO)
- approved = json.loads((root / "docs/stages/approved.json").read_text())
- del approved["providers"]["aws"]
- (root / "docs/stages/approved.json").write_text(json.dumps(approved))
- code, out = run(root, capsys)
- assert code == 1 and "no entry in approved.json" in out.err
- def test_a_nat_gateway_is_rejected_even_if_approved_sources_names_it(tmp_path, capsys):
- root = build(tmp_path, aws=TWO)
- (root / "modules/aws/nat.tf").write_text('resource "aws_nat_gateway" "n" {}\n')
- approved = json.loads((root / "docs/stages/approved.json").read_text())
- approved["providers"]["aws"]["allowed_sources"]["aws_nat_gateway"] = [
- "modules/aws/nat.tf"
- ]
- (root / "docs/stages/approved.json").write_text(json.dumps(approved))
- code, out = run(root, capsys)
- assert code == 1 and "aws_nat_gateway is rejected" in out.err
- @pytest.mark.parametrize(
- "rtype",
- [
- "aws_vpc",
- "aws_subnet",
- "aws_internet_gateway",
- "aws_security_group",
- "aws_default_security_group",
- ],
- )
- def test_free_aws_types_pass(tmp_path, capsys, rtype):
- root = build(tmp_path, aws=TWO)
- (root / "stacks/aws/10-access/x.tf").write_text(f'resource "{rtype}" "x" {{}}\n')
- assert run(root, capsys)[0] == 0
- @pytest.mark.parametrize(
- "rtype", ["aws_eip", "aws_lb", "aws_db_instance", "aws_vpc_endpoint"]
- )
- def test_other_aws_types_fail_unless_listed(tmp_path, capsys, rtype):
- root = build(tmp_path, aws=TWO)
- (root / "stacks/aws/10-access/x.tf").write_text(f'resource "{rtype}" "x" {{}}\n')
- code, out = run(root, capsys)
- assert code == 1 and rtype in out.err
- def test_connector_reconciliation_is_per_stack_not_repository_wide(tmp_path, capsys):
- root = build(tmp_path, aws=TWO, do_droplets=2)
- assert run(root, capsys)[0] == 0
- # one extra AWS connector block must fail in the AWS stack and not be hidden
- # by the DigitalOcean stack's blocks
- (root / "stacks/aws/10-access/extra.tf").write_text(CONNECTOR.format(i=9))
- code, out = run(root, capsys)
- assert code == 1 and "stacks/aws/10-access: 3 twingate-connector" in out.err
- def test_an_instance_must_state_its_disk_and_address(tmp_path):
- bad = [{"name": "a", "kind": "instance", "type": "t4g.micro"}]
- root = build(tmp_path, aws=bad)
- with pytest.raises(ValueError, match="root_gb and public_ip"):
- cost_check.provider_totals(root)
- def test_an_unknown_instance_type_has_no_price(tmp_path):
- root = build(tmp_path, aws=[instance(itype="m7g.16xlarge")])
- with pytest.raises(ValueError, match="no price for instance type"):
- cost_check.provider_totals(root)
- # ---- plan JSON --------------------------------------------------------------
- def change(rtype, name, after, unknown=None, actions=("create",)):
- return {
- "address": f"{rtype}.{name}",
- "type": rtype,
- "change": {
- "actions": list(actions),
- "after": after,
- "after_unknown": unknown or {},
- },
- }
- def inst(name="a", itype="t4g.micro", gb=8, public=True, **extra):
- extra.setdefault("credit_specification", [{"cpu_credits": "standard"}])
- if extra["credit_specification"] is None:
- del extra["credit_specification"]
- after = {
- "instance_type": itype,
- "root_block_device": [{"volume_size": gb}],
- **extra,
- }
- if public is not None:
- after["associate_public_ip_address"] = public
- return change("aws_instance", name, after)
- def plan(*changes):
- return {"resource_changes": list(changes)}
- def test_a_plan_of_the_two_connectors_matches_the_manifest():
- total, problems = cost_check.plan_cost(plan(inst("a"), inst("b")), AWS_PRICES)
- assert (total, problems) == (20.84, [])
- def test_an_instance_with_the_address_unset_is_priced_as_public():
- total, _ = cost_check.plan_cost(plan(inst(public=None)), AWS_PRICES)
- assert total == round(0.0084 * 730 + 0.005 * 730 + 8 * 0.08, 2)
- def test_an_instance_with_the_address_explicitly_off_is_not_charged_for_it():
- total, _ = cost_check.plan_cost(plan(inst(public=False)), AWS_PRICES)
- assert total == round(0.0084 * 730 + 8 * 0.08, 2)
- def test_a_large_root_volume_is_priced():
- total, _ = cost_check.plan_cost(plan(inst(gb=500)), AWS_PRICES)
- assert total == round(0.0084 * 730 + 0.005 * 730 + 500 * 0.08, 2)
- def test_an_extra_ebs_block_device_is_priced():
- total, _ = cost_check.plan_cost(
- plan(inst(ebs_block_device=[{"volume_size": 100}])), AWS_PRICES
- )
- assert total == round(0.0084 * 730 + 0.005 * 730 + 108 * 0.08, 2)
- def test_an_explicit_elastic_address_is_priced():
- total, _ = cost_check.plan_cost(
- plan(inst(public=False), change("aws_eip", "e", {})), AWS_PRICES
- )
- assert total == round(0.0084 * 730 + 8 * 0.08 + 0.005 * 730, 2)
- def test_a_nat_gateway_in_a_plan_is_rejected():
- _, problems = cost_check.plan_cost(
- plan(change("aws_nat_gateway", "n", {})), AWS_PRICES
- )
- assert problems and "rejected" in problems[0]
- def test_for_each_expands_to_one_change_per_instance():
- plan_json = plan(*(inst(f"web[{k!r}]") for k in ("a", "b", "c")))
- total, _ = cost_check.plan_cost(plan_json, AWS_PRICES)
- assert total == round(3 * (0.0084 * 730 + 0.005 * 730 + 8 * 0.08), 2)
- def test_a_destroyed_instance_is_not_charged():
- gone = inst()
- gone["change"]["actions"] = ["delete"]
- assert cost_check.plan_cost(plan(gone), AWS_PRICES) == (0.0, [])
- def test_an_unknown_type_is_a_problem_not_a_zero():
- _, problems = cost_check.plan_cost(plan(change("aws_lb", "l", {})), AWS_PRICES)
- assert problems and "no price" in problems[0]
- def test_a_missing_root_volume_is_a_problem():
- bare = change("aws_instance", "a", {"instance_type": "t4g.micro"})
- _, problems = cost_check.plan_cost(plan(bare), AWS_PRICES)
- assert problems and "root_block_device" in problems[0]
- def test_an_unknown_instance_type_in_the_plan_is_a_problem():
- unk = change("aws_instance", "a", {"instance_type": None}, {"instance_type": True})
- _, problems = cost_check.plan_cost(plan(unk), AWS_PRICES)
- assert problems and "instance_type" in problems[0]
- def test_non_aws_resources_in_the_plan_are_ignored():
- assert cost_check.plan_cost(
- plan(change("twingate_group", "g", {})), AWS_PRICES
- ) == (0.0, [])
- def test_main_checks_a_plan_against_the_manifest(tmp_path, capsys):
- root = build(tmp_path, aws=TWO)
- good = tmp_path / "good.json"
- good.write_text(json.dumps(plan(inst("a"), inst("b"))))
- assert (
- run(root, capsys, "--plan", str(good), "--stack", "stacks/aws/10-access")[0]
- == 0
- )
- # the plan has a third instance the manifest does not declare
- bad = tmp_path / "bad.json"
- bad.write_text(json.dumps(plan(inst("a"), inst("b"), inst("c"))))
- code, out = run(root, capsys, "--plan", str(bad), "--stack", "stacks/aws/10-access")
- assert code == 1 and "plan costs $31.27 but cost.json declares $20.84" in out.err
- def test_main_fails_when_the_plan_has_a_nat_gateway(tmp_path, capsys):
- root = build(tmp_path, aws=TWO)
- bad = tmp_path / "nat.json"
- bad.write_text(
- json.dumps(plan(inst("a"), inst("b"), change("aws_nat_gateway", "n", {})))
- )
- code, out = run(root, capsys, "--plan", str(bad), "--stack", "stacks/aws/10-access")
- assert code == 1 and "rejected" in out.err
- def test_plan_needs_a_stack(tmp_path, capsys):
- root = build(tmp_path, aws=TWO)
- p = tmp_path / "p.json"
- p.write_text("{}")
- code, out = run(root, capsys, "--plan", str(p))
- assert code == 1 and "--plan needs --stack" in out.err
- # ---- review findings: each was a way to pass the gate -----------------------
- def test_a_commented_local_source_does_not_hide_a_remote_one(tmp_path, capsys):
- root = build(tmp_path, aws=TWO)
- (root / "stacks/aws/10-access/db.tf").write_text(
- 'module "db" {\n /*\n source = "./looks-local"\n */\n # source = "./also-local"\n source = "terraform-aws-modules/rds/aws"\n}\n'
- )
- code, out = run(root, capsys)
- assert code == 1 and "non-local source" in out.err
- def test_a_brace_in_a_string_or_comment_does_not_end_a_connector_block(
- tmp_path, capsys
- ):
- root = build(tmp_path, aws=TWO)
- (root / "stacks/aws/10-access/m.tf").write_text(
- 'module "c" {\n source = "../../../modules/aws/twingate-connector"\n instance_type = local.c.type\n note = "}"\n # }\n count = 100\n}\n'
- + CONNECTOR.format(i=7)
- )
- code, out = run(root, capsys)
- assert code == 1 and "uses count" in out.err
- def test_a_commented_out_resource_is_not_flagged(tmp_path, capsys):
- root = build(tmp_path, aws=TWO)
- (root / "stacks/aws/10-access/x.tf").write_text('# resource "aws_lb" "x" {}\n')
- assert run(root, capsys)[0] == 0
- def test_approved_json_cannot_approve_a_type_with_no_price_model(tmp_path, capsys):
- root = build(tmp_path, aws=TWO)
- (root / "modules/aws/lb.tf").write_text('resource "aws_lb" "l" {}\n')
- approved = json.loads((root / "docs/stages/approved.json").read_text())
- approved["providers"]["aws"]["allowed_sources"]["aws_lb"] = ["modules/aws/lb.tf"]
- (root / "docs/stages/approved.json").write_text(json.dumps(approved))
- code, out = run(root, capsys)
- assert code == 1 and "no price model" in out.err
- @pytest.mark.parametrize("bad", ["nan", "inf", "-1", "abc", None])
- def test_a_non_finite_or_negative_approval_fails(tmp_path, capsys, bad):
- root = build(tmp_path, aws=TWO)
- approved = json.loads((root / "docs/stages/approved.json").read_text())
- approved["providers"]["aws"]["approved_monthly_total"] = bad
- (root / "docs/stages/approved.json").write_text(json.dumps(approved))
- code, out = run(root, capsys)
- assert code == 1 and "cost-check:" in out.err
- def test_a_nan_ceiling_fails(tmp_path, capsys):
- root = build(tmp_path, aws=TWO)
- approved = json.loads((root / "docs/stages/approved.json").read_text())
- approved["ceiling"] = "nan"
- (root / "docs/stages/approved.json").write_text(json.dumps(approved))
- assert run(root, capsys)[0] == 1
- def test_unknown_extra_disks_are_a_problem_not_zero():
- unk = inst(public=False, ebs_block_device=[])
- unk["change"]["after_unknown"] = {"ebs_block_device": True}
- _, problems = cost_check.plan_cost(plan(unk), AWS_PRICES)
- assert problems and "ebs_block_device" in problems[0]
- def test_a_stack_directly_under_stacks_aws_is_aws(tmp_path):
- assert cost_check.provider_of_stack("stacks/aws") == "aws"
- assert cost_check.provider_of_stack("stacks/aws/10-access") == "aws"
- assert cost_check.provider_of_stack("stacks/10-access") == "digitalocean"
- def test_a_malformed_manifest_exits_nonzero_instead_of_crashing(tmp_path, capsys):
- root = build(tmp_path, aws=TWO)
- (root / "stacks/aws/10-access/cost.json").write_text(
- '{"resources": [{"kind": "instance"}]}'
- )
- code, _ = run(root, capsys)
- assert code == 1
- def test_malformed_plan_shapes_exit_nonzero(tmp_path, capsys):
- root = build(tmp_path, aws=TWO)
- p = tmp_path / "p.json"
- p.write_text(
- json.dumps(
- {
- "resource_changes": [
- {
- "type": "aws_instance",
- "change": {
- "actions": ["create"],
- "after": {
- "instance_type": "t4g.micro",
- "root_block_device": ["x"],
- },
- },
- }
- ]
- }
- )
- )
- assert (
- run(root, capsys, "--plan", str(p), "--stack", "stacks/aws/10-access")[0] == 1
- )
- def test_inactive_providers_are_reported_as_an_attestation(tmp_path, capsys):
- root = build(tmp_path, aws=TWO, aws_active=False)
- out = run(root, capsys)[1].out
- assert "aws: planned $20.84/mo, approved $21.00, inactive" in out
- def test_data_sources_in_the_plan_are_neither_priced_nor_rejected():
- ami = change("aws_ami", "x", {})
- ami["mode"] = "data"
- lookup = inst()
- lookup["mode"] = "data"
- assert cost_check.plan_cost(plan(ami, lookup), AWS_PRICES) == (0.0, [])
- @pytest.mark.parametrize(
- "block",
- [
- {"volume_size": 8, "volume_type": "io2"},
- {"volume_size": 8, "volume_type": "gp2"},
- {"volume_size": 8, "iops": 16000},
- {"volume_size": 8, "throughput": 1000},
- ],
- )
- def test_unpriced_root_volume_shapes_are_a_problem(block):
- bad = inst()
- bad["change"]["after"]["root_block_device"] = [block]
- _, problems = cost_check.plan_cost(plan(bad), AWS_PRICES)
- assert problems
- def test_gp3_at_baseline_is_priced():
- ok = inst()
- ok["change"]["after"]["root_block_device"] = [
- {"volume_size": 8, "volume_type": "gp3", "iops": 3000, "throughput": 125}
- ]
- assert cost_check.plan_cost(plan(ok), AWS_PRICES)[1] == []
- def test_standalone_and_extra_volumes_are_shape_checked():
- vol = change("aws_ebs_volume", "v", {"size": 10, "type": "io1", "iops": 5000})
- assert cost_check.plan_cost(plan(vol), AWS_PRICES)[1]
- extra = inst(ebs_block_device=[{"volume_size": 10, "volume_type": "st1"}])
- assert cost_check.plan_cost(plan(extra), AWS_PRICES)[1]
- # ---- adversarial review: parser-differential bypasses ------------------------
- #
- # Each of these exited 0 before the fix. The baseline `build(aws=TWO)` repo
- # passes, so any failure below comes from the one file the test adds.
- AWS_STACK = "stacks/aws/10-access"
- NAT = 'resource "aws_nat_gateway" "n" {}\n'
- def add(root, rel, text):
- path = root / rel
- path.parent.mkdir(parents=True, exist_ok=True)
- path.write_text(text)
- return path
- def fails(root, capsys, *needles):
- code, out = run(root, capsys)
- assert code == 1, out.err
- for needle in needles:
- assert needle in out.err, out.err
- def test_baseline_repo_for_the_review_tests_passes(tmp_path, capsys):
- assert run(build(tmp_path, aws=TWO), capsys)[0] == 0
- # 1. labels --------------------------------------------------------------------
- @pytest.mark.parametrize(
- "text",
- [
- 'resource aws_nat_gateway "n" {}\n',
- 'resource "aws_nat_gateway" n {}\n',
- "resource aws_nat_gateway n {}\n",
- 'resource\t"aws_nat_gateway"\t"n"\t{}\n',
- ],
- )
- def test_bare_resource_labels_are_read(tmp_path, capsys, text):
- root = build(tmp_path, aws=TWO)
- add(root, f"{AWS_STACK}/x.tf", text)
- fails(root, capsys, "aws_nat_gateway")
- def test_bare_module_label_with_a_remote_source_fails(tmp_path, capsys):
- root = build(tmp_path, aws=TWO)
- add(
- root,
- f"{AWS_STACK}/x.tf",
- 'module r {\n source = "git::https://example.invalid/x.git"\n}\n',
- )
- fails(root, capsys, "non-local source")
- def test_a_bare_labelled_local_module_still_passes(tmp_path, capsys):
- root = build(tmp_path, aws=TWO)
- add(root, f"{AWS_STACK}/x.tf", 'module r {\n source = "./x"\n}\n')
- assert run(root, capsys)[0] == 0
- @pytest.mark.parametrize(
- "text,line",
- [
- ('resource "aws_nat\\u005fgateway" "n" {}\n', 1),
- ('\n\nresource "aws_nat_gateway" "n\\u0041" {}\n', 3),
- ('resource "aws_nat\\x" "n" {}\n', 1),
- ('\nmodule "r\\u0041" {\n source = "./x"\n}\n', 2),
- ],
- )
- def test_a_backslash_in_a_label_fails_naming_file_and_line(
- tmp_path, capsys, text, line
- ):
- root = build(tmp_path, aws=TWO)
- add(root, f"{AWS_STACK}/x.tf", text)
- fails(root, capsys, f"{AWS_STACK}/x.tf:{line}", "backslash")
- # 2. OpenTofu file kinds -------------------------------------------------------
- def test_tofu_files_are_scanned_for_resources(tmp_path, capsys):
- root = build(tmp_path, aws=TWO)
- add(root, f"{AWS_STACK}/x.tofu", NAT)
- fails(root, capsys, "aws_nat_gateway", "x.tofu")
- def test_tofu_files_are_scanned_for_modules(tmp_path, capsys):
- root = build(tmp_path, aws=TWO)
- add(root, f"{AWS_STACK}/extra.tofu", CONNECTOR.format(i=9))
- fails(root, capsys, f"{AWS_STACK}: 3 twingate-connector")
- @pytest.mark.parametrize("name", ["x.tofu.json", "x.tf.json"])
- def test_json_configuration_is_refused(tmp_path, capsys, name):
- root = build(tmp_path, aws=TWO)
- add(root, f"{AWS_STACK}/{name}", "{}")
- fails(root, capsys, name)
- def test_a_stack_of_only_tofu_files_needs_a_manifest(tmp_path, capsys):
- root = build(tmp_path, aws=TWO)
- add(root, "stacks/aws/20-new/main.tofu", 'resource "twingate_group" "g" {}\n')
- fails(root, capsys, "stacks/aws/20-new: has OpenTofu files but no cost.json")
- @pytest.mark.parametrize("name", ["override.tf", "main_override.tf", "override.tofu"])
- def test_override_files_are_scanned(tmp_path, capsys, name):
- root = build(tmp_path, aws=TWO)
- add(root, f"{AWS_STACK}/{name}", NAT)
- fails(root, capsys, "aws_nat_gateway", name)
- # 3. hidden directories and stack names ---------------------------------------
- @pytest.mark.parametrize("hidden", [".claude", ".hidden", ".git", ".venv"])
- def test_a_hidden_directory_under_stacks_is_a_failure(tmp_path, capsys, hidden):
- root = build(tmp_path, aws=TWO)
- add(root, f"stacks/10-access/{hidden}/z/main.tf", NAT)
- fails(root, capsys, "hidden directory", f"stacks/10-access/{hidden}")
- def test_a_hidden_directory_under_modules_is_a_failure(tmp_path, capsys):
- root = build(tmp_path, aws=TWO)
- add(root, "modules/.claude/m/main.tf", NAT)
- fails(root, capsys, "hidden directory")
- @pytest.mark.parametrize(
- "source", ["./.claude/m", "../../.claude/m", "./a/.hidden/b", "../.git/x"]
- )
- def test_a_module_source_through_a_dot_directory_fails(tmp_path, capsys, source):
- root = build(tmp_path, aws=TWO)
- add(root, f"{AWS_STACK}/x.tf", f'module "m" {{\n source = "{source}"\n}}\n')
- fails(root, capsys, "hidden directory", f"{AWS_STACK}/x.tf:1")
- def test_a_module_source_that_leaves_the_repository_fails(tmp_path, capsys):
- root = build(tmp_path, aws=TWO)
- add(root, "stacks/10-access/x.tf", 'module "m" {\n source = "../../../x"\n}\n')
- fails(root, capsys, "outside the repository")
- def test_terraform_cache_and_root_tool_directories_are_still_ignored(tmp_path, capsys):
- root = build(tmp_path, aws=TWO)
- add(root, f"{AWS_STACK}/.terraform/modules/x/main.tf", NAT)
- add(root, ".claude/worktrees/w/stacks/10-access/main.tf", NAT)
- add(root, ".git/x.tf", NAT)
- add(root, ".venv/lib/x.tf", NAT)
- assert run(root, capsys)[0] == 0
- @pytest.mark.parametrize(
- "rel",
- [
- "stacks/AWS/10-access/main.tf",
- "stacks/aws-foo/10-access/main.tf",
- "stacks/Azure/10-access/main.tf",
- "stacks/foo/main.tf",
- "stacks/aws/foo/main.tf",
- "stacks/10/main.tf",
- "stacks/-x/main.tf",
- ],
- )
- def test_stack_directory_names_are_exact(tmp_path, capsys, rel):
- root = build(tmp_path, aws=TWO)
- add(root, rel, 'resource "twingate_group" "g" {}\n')
- fails(root, capsys, "stack directory name")
- @pytest.mark.parametrize("rel", ["stacks/gcp/05-x/main.tf", "stacks/azure/99-a-b/m.tf"])
- def test_known_provider_and_numbered_names_are_accepted(tmp_path, capsys, rel):
- root = build(tmp_path, aws=TWO)
- add(root, rel, 'resource "twingate_group" "g" {}\n')
- out = run(root, capsys)[1]
- assert "stack directory name" not in out.err
- # 4. heredocs ------------------------------------------------------------------
- OPEN_C = "locals {\n a = <<EOT\n/*\nEOT\n}\n"
- CLOSE_C = "locals {\n b = <<EOT\n*/\nEOT\n}\n"
- def test_a_comment_opener_inside_a_heredoc_does_not_hide_a_resource(tmp_path, capsys):
- root = build(tmp_path, aws=TWO)
- add(root, f"{AWS_STACK}/x.tf", OPEN_C + NAT + CLOSE_C)
- fails(root, capsys, "aws_nat_gateway")
- def test_the_same_trick_with_an_indented_heredoc(tmp_path, capsys):
- root = build(tmp_path, aws=TWO)
- text = OPEN_C.replace("<<EOT", "<<-EOT") + NAT + CLOSE_C.replace("<<EOT", "<<-EOT")
- add(root, f"{AWS_STACK}/x.tf", text.replace("\nEOT\n", "\n EOT\n"))
- fails(root, capsys, "aws_nat_gateway")
- def test_a_comment_opener_inside_a_heredoc_does_not_hide_a_connector(tmp_path, capsys):
- root = build(tmp_path, aws=TWO)
- add(root, f"{AWS_STACK}/x.tf", OPEN_C + CONNECTOR.format(i=9) + CLOSE_C)
- fails(root, capsys, f"{AWS_STACK}: 3 twingate-connector")
- def test_a_lone_brace_in_a_heredoc_does_not_end_a_connector_block(tmp_path, capsys):
- root = build(tmp_path, aws=TWO)
- add(
- root,
- f"{AWS_STACK}/m.tf",
- 'module "c" {\n source = "../../../modules/aws/twingate-connector"\n'
- " instance_type = local.c.type\n user_data = <<EOT\n}\nEOT\n count = 3\n}\n"
- + CONNECTOR.format(i=7),
- )
- fails(root, capsys, "uses count")
- def test_a_resource_or_module_keyword_inside_a_heredoc_is_text(tmp_path, capsys):
- root = build(tmp_path, aws=TWO)
- add(
- root,
- f"{AWS_STACK}/x.tf",
- "locals {\n doc = <<EOT\n"
- + NAT
- + 'module "m" {\n source = "git::x"\n}\nEOT\n}\n',
- )
- assert run(root, capsys)[0] == 0
- def test_an_unterminated_heredoc_fails_closed(tmp_path, capsys):
- root = build(tmp_path, aws=TWO)
- add(root, f"{AWS_STACK}/x.tf", "locals {\n a = <<EOT\nnever closed\n")
- fails(root, capsys, "unterminated heredoc", f"{AWS_STACK}/x.tf")
- # 5. top-level attributes only -------------------------------------------------
- def test_a_nested_source_does_not_stand_in_for_the_real_one(tmp_path, capsys):
- root = build(tmp_path, aws=TWO)
- add(
- root,
- f"{AWS_STACK}/x.tf",
- 'module "r" {\n tags = { source = "./fake" }\n'
- ' source = "git::https://example.invalid/x.git"\n}\n',
- )
- fails(root, capsys, "non-local source")
- def test_a_nested_source_alone_is_not_a_source(tmp_path, capsys):
- root = build(tmp_path, aws=TWO)
- add(
- root,
- f"{AWS_STACK}/x.tf",
- 'module "r" {\n tags = {\n source = "./fake"\n }\n}\n',
- )
- fails(root, capsys, "non-local source")
- def test_a_nested_count_on_a_connector_is_not_a_top_level_count(tmp_path, capsys):
- root = build(tmp_path, aws=TWO)
- (root / f"{AWS_STACK}/m.tf").write_text(
- 'module "c0" {\n source = "../../../modules/aws/twingate-connector"\n'
- " instance_type = local.c.type\n tags = { count = 1 }\n}\n"
- + CONNECTOR.format(i=1)
- )
- assert run(root, capsys)[0] == 0
- def test_duplicate_top_level_sources_fail(tmp_path, capsys):
- root = build(tmp_path, aws=TWO)
- add(
- root,
- f"{AWS_STACK}/x.tf",
- 'module "r" {\n source = "./a"\n source = "git::x"\n}\n',
- )
- fails(root, capsys, "more than one source")
- # 6. the machine size must come from the manifest -----------------------------
- @pytest.mark.parametrize(
- "line",
- [
- 'size = "s-32vcpu-192gb"',
- "size = var.size",
- "size = local.connector_a.size == null ? local.x.size : local.y.size",
- "size = local.connector_a.cost.size",
- "size = local.connector_a.size_big",
- 'size = "${local.connector_a.size}"',
- ],
- )
- def test_a_do_connector_size_must_be_a_manifest_reference(tmp_path, capsys, line):
- root = build(tmp_path, aws=TWO)
- (root / "stacks/10-access/m.tf").write_text(
- f'module "c0" {{\n source = "../../modules/twingate-connector"\n {line}\n}}\n'
- )
- fails(root, capsys, "stacks/10-access/m.tf:1", "docs/cost.md")
- def test_a_connector_with_no_size_at_all_fails(tmp_path, capsys):
- root = build(tmp_path, aws=TWO)
- (root / "stacks/10-access/m.tf").write_text(
- 'module "c0" {\n source = "../../modules/twingate-connector"\n}\n'
- )
- fails(root, capsys, "docs/cost.md")
- def test_an_aws_connector_literal_instance_type_fails(tmp_path, capsys):
- root = build(tmp_path, aws=TWO)
- (root / f"{AWS_STACK}/m.tf").write_text(
- 'module "c0" {\n source = "../../../modules/aws/twingate-connector"\n'
- ' instance_type = "m7g.16xlarge"\n}\n' + CONNECTOR.format(i=1)
- )
- fails(root, capsys, "docs/cost.md")
- def test_a_size_in_a_nested_object_does_not_satisfy_the_rule(tmp_path, capsys):
- root = build(tmp_path, aws=TWO)
- (root / "stacks/10-access/m.tf").write_text(
- 'module "c0" {\n source = "../../modules/twingate-connector"\n'
- " other = { size = local.c.size }\n}\n"
- )
- fails(root, capsys, "docs/cost.md")
- def test_the_repo_connectors_pass_the_size_rule():
- root = Path(__file__).resolve().parents[1]
- problems, _ = cost_check.module_problems(root)
- assert problems == []
- # 7. unknown provider prefixes ------------------------------------------------
- @pytest.mark.parametrize(
- "rtype",
- [
- "linode_instance",
- "hcloud_server",
- "vultr_instance",
- "oci_core_instance",
- "kubernetes_namespace",
- "scaleway_instance_server",
- "foo",
- ],
- )
- def test_an_unknown_provider_prefix_fails(tmp_path, capsys, rtype):
- root = build(tmp_path, aws=TWO)
- add(root, f"{AWS_STACK}/x.tf", f'resource "{rtype}" "x" {{}}\n')
- fails(root, capsys, rtype, "is not known to the gate", f"{AWS_STACK}/x.tf")
- @pytest.mark.parametrize(
- "rtype",
- [
- "twingate_group",
- "terraform_data",
- "null_resource",
- "random_id",
- "time_sleep",
- "tls_private_key",
- "local_file",
- ],
- )
- def test_safe_non_cloud_prefixes_pass(tmp_path, capsys, rtype):
- root = build(tmp_path, aws=TWO)
- add(root, f"{AWS_STACK}/x.tf", f'resource "{rtype}" "x" {{}}\n')
- assert run(root, capsys)[0] == 0
- def test_the_repository_itself_uses_only_known_prefixes():
- root = Path(__file__).resolve().parents[1]
- approved = json.loads((root / "docs/stages/approved.json").read_text())
- found = cost_check.uncosted_sources(
- root, cost_check.allowed_sources(approved), set(approved["providers"])
- )
- assert found == []
- # 8. count / for_each on a costed resource ------------------------------------
- @pytest.mark.parametrize(
- "rel,rtype,meta",
- [
- ("modules/aws/twingate-connector/main.tf", "aws_instance", "count = 50"),
- ("modules/aws/twingate-connector/main.tf", "aws_instance", "for_each = var.x"),
- ("modules/twingate-connector/main.tf", "digitalocean_droplet", "count = 9"),
- ("modules/twingate-connector/main.tf", "digitalocean_droplet", "for_each = {}"),
- ],
- )
- def test_a_costed_resource_with_count_or_for_each_fails(
- tmp_path, capsys, rel, rtype, meta
- ):
- root = build(tmp_path, aws=TWO)
- add(root, rel, f'resource "{rtype}" "a" {{\n ami = "x"\n {meta}\n}}\n')
- fails(root, capsys, f"{rel}:1", "without a plan")
- def test_costed_resource_in_a_bare_labelled_block_with_count_fails(tmp_path, capsys):
- root = build(tmp_path, aws=TWO)
- add(
- root,
- "modules/aws/twingate-connector/main.tf",
- "resource aws_instance a {\n count = 50\n}\n",
- )
- fails(root, capsys, "without a plan")
- def test_nested_count_or_a_free_resource_with_count_is_fine(tmp_path, capsys):
- root = build(tmp_path, aws=TWO)
- add(
- root,
- "modules/aws/twingate-connector/main.tf",
- 'resource "aws_instance" "a" {\n tags = { count = 5 }\n}\n',
- )
- add(root, f"{AWS_STACK}/x.tf", 'resource "aws_subnet" "s" {\n count = 3\n}\n')
- assert run(root, capsys)[0] == 0
- def test_count_behind_a_heredoc_brace_in_a_costed_resource_fails(tmp_path, capsys):
- root = build(tmp_path, aws=TWO)
- add(
- root,
- "modules/aws/twingate-connector/main.tf",
- 'resource "aws_instance" "a" {\n user_data = <<EOT\n}\nEOT\n count = 50\n}\n',
- )
- fails(root, capsys, "without a plan")
- # 9. plan: attributes the gate does not price ---------------------------------
- @pytest.mark.parametrize(
- "extra",
- [
- {"tenancy": "dedicated"},
- {"tenancy": "host"},
- {"credit_specification": [{"cpu_credits": "unlimited"}]},
- {"instance_market_options": [{"market_type": "spot"}]},
- {"placement_group": "pg-1"},
- {"host_id": "h-123"},
- {"monitoring": True},
- {"network_interface": [{"device_index": 0}]},
- {"launch_template": [{"id": "lt-1"}]},
- {"license_specification": [{"license_configuration_arn": "arn:x"}]},
- {"host_resource_group_arn": "arn:x"},
- ],
- )
- def test_an_unpriced_instance_attribute_is_a_problem(extra):
- problems = cost_check.plan_cost(plan(inst("a", **extra)), AWS_PRICES)[1]
- assert any("unpriced attribute" in p for p in problems), problems
- @pytest.mark.parametrize(
- "extra",
- [
- {"tenancy": "default"},
- {"tenancy": None},
- {"credit_specification": [{"cpu_credits": "standard"}]},
- {"instance_market_options": []},
- {"placement_group": ""},
- {"monitoring": False},
- ],
- )
- def test_priced_shapes_of_those_attributes_pass(extra):
- problems = cost_check.plan_cost(plan(inst("a", **extra)), AWS_PRICES)[1]
- assert problems == []
- def test_main_fails_a_plan_with_a_dedicated_instance(tmp_path, capsys):
- root = build(tmp_path, aws=TWO)
- p = tmp_path / "plan.json"
- p.write_text(json.dumps(plan(inst("a", tenancy="dedicated"), inst("b"))))
- code, out = run(root, capsys, "--plan", str(p), "--stack", AWS_STACK)
- assert code == 1 and "unpriced attribute" in out.err
- # ---- second review round -----------------------------------------------------
- def test_a_utf8_bom_does_not_hide_the_first_block(tmp_path, capsys):
- root = build(tmp_path, aws=TWO)
- (root / f"{AWS_STACK}/bom.tf").write_bytes(b"\xef\xbb\xbf" + NAT.encode())
- fails(root, capsys, "aws_nat_gateway")
- def test_a_bom_before_a_module_is_read(tmp_path, capsys):
- root = build(tmp_path, aws=TWO)
- (root / f"{AWS_STACK}/bom.tf").write_bytes(
- b'\xef\xbb\xbfmodule "r" {\n source = "git::x"\n}\n'
- )
- fails(root, capsys, "non-local source")
- def test_crlf_files_are_read(tmp_path, capsys):
- root = build(tmp_path, aws=TWO)
- text = (
- (
- 'module "c" {\r\n source = "../../../modules/aws/twingate-connector"\r\n'
- " instance_type = local.c.type\r\n count = 4\r\n}\r\n" + NAT
- )
- .replace("\n", "\r\n")
- .replace("\r\r", "\r")
- )
- (root / f"{AWS_STACK}/crlf.tf").write_bytes(text.encode())
- fails(root, capsys, "uses count", "aws_nat_gateway")
- def test_a_crlf_connector_size_reference_passes(tmp_path, capsys):
- root = build(tmp_path, aws=TWO)
- (root / f"{AWS_STACK}/m.tf").write_bytes(
- b'module "c0" {\r\n source = "../../../modules/aws/twingate-connector"\r\n'
- b" instance_type = local.c.type\r\n}\r\n" + CONNECTOR.format(i=1).encode()
- )
- assert run(root, capsys)[0] == 0
- def test_a_root_level_directory_symlink_is_refused(tmp_path, capsys):
- root = build(tmp_path, aws=TWO)
- outside = tmp_path.parent / (tmp_path.name + "-ext")
- (outside / "twingate-connector").mkdir(parents=True)
- (outside / "twingate-connector/main.tf").write_text(
- 'resource "digitalocean_kubernetes_cluster" "x" {}\n'
- )
- (root / "vendor").symlink_to(outside)
- add(
- root,
- f"{AWS_STACK}/x.tf",
- 'module "v" {\n source = "../../../vendor/twingate-connector"\n size = local.c.size\n}\n',
- )
- fails(root, capsys, "vendor: symlinked directory is refused")
- def test_a_symlinked_module_target_escaping_the_root_is_refused(tmp_path, capsys):
- root = build(tmp_path, aws=TWO)
- outside = tmp_path.parent / (tmp_path.name + "-ext2")
- outside.mkdir()
- link = root / "stacks/10-access/ln"
- link.symlink_to(outside)
- add(
- root,
- f"{AWS_STACK}/x.tf",
- 'module "v" {\n source = "../../../stacks/10-access/ln"\n}\n',
- )
- fails(root, capsys, "outside the repository")
- def test_a_symlinked_tf_file_is_refused(tmp_path, capsys):
- root = build(tmp_path, aws=TWO)
- target = tmp_path.parent / (tmp_path.name + "-f.tf")
- target.write_text(NAT)
- (root / f"{AWS_STACK}/link.tf").symlink_to(target)
- fails(root, capsys, "symlink")
- @pytest.mark.parametrize(
- "text",
- [
- 'locals {\n x = "${1 /* } " <<FAKE */ + 2}"\n}\n',
- 'locals {\n x = "${(1 # } " <<FAKE\n + 2)}"\n}\n',
- 'locals {\n x = "${(1 // } " <<FAKE\n + 2)}"\n}\n',
- ],
- )
- def test_comments_inside_interpolation_are_comments(tmp_path, capsys, text):
- root = build(tmp_path, aws=TWO)
- add(root, f"{AWS_STACK}/x.tf", text)
- assert run(root, capsys)[0] == 0
- def test_a_connector_in_an_ordinary_module_directory_is_not_a_stack(tmp_path, capsys):
- root = build(tmp_path, aws=TWO)
- add(
- root,
- "modules/wrapper/main.tf",
- 'locals {\n c = { size = "s-1vcpu-1gb" }\n}\n\n'
- 'module "inner" {\n source = "../twingate-connector"\n size = local.c.size\n}\n',
- )
- assert run(root, capsys)[0] == 0
- def test_a_connector_in_a_module_directory_still_has_its_source_and_size_checked(
- tmp_path, capsys
- ):
- root = build(tmp_path, aws=TWO)
- add(
- root,
- "modules/wrapper/main.tf",
- 'module "inner" {\n source = "../twingate-connector"\n size = "s-32vcpu-192gb"\n}\n',
- )
- fails(root, capsys, "docs/cost.md")
- # ---- third review round -------------------------------------------------------
- @pytest.mark.parametrize("target", ["outside", ".claude/payload"])
- def test_any_root_level_directory_symlink_is_refused(tmp_path, capsys, target):
- root = build(tmp_path, aws=TWO)
- if target == "outside":
- dest = tmp_path.parent / (tmp_path.name + "-shared")
- else:
- dest = root / target
- (dest / "twingate-connector").mkdir(parents=True)
- (dest / "twingate-connector/main.tf").write_text(NAT)
- (root / "shared").symlink_to(dest)
- add(
- root,
- f"{AWS_STACK}/x.tf",
- 'module "v" {\n source = "../../../shared/twingate-connector"\n size = local.c.size\n}\n',
- )
- fails(root, capsys, "shared: symlinked directory is refused")
- def test_a_symlink_nested_deep_in_the_tree_is_refused(tmp_path, capsys):
- root = build(tmp_path, aws=TWO)
- (root / "docs/deep").mkdir()
- (root / "docs/deep/ln").symlink_to(root / "modules")
- fails(root, capsys, "docs/deep/ln: symlinked directory is refused")
- # ordinary object attributes named like block keywords
- @pytest.mark.parametrize(
- "text",
- [
- "locals {\n module = { enabled = true }\n}\n",
- "locals {\n resource = { enabled = true }\n}\n",
- "locals {\n cfg = {\n module = {\n a = 1\n }\n resource = {\n b = 2\n }\n data = {}\n }\n}\n",
- 'variable "x" {\n default = {\n module = { on = true }\n resource = { on = false }\n }\n}\n',
- "locals {\n module = {\n on = true\n }\n}\n",
- ],
- )
- def test_object_attributes_named_module_or_resource_are_not_blocks(
- tmp_path, capsys, text
- ):
- root = build(tmp_path, aws=TWO)
- add(root, f"{AWS_STACK}/x.tf", text)
- code, out = run(root, capsys)
- assert code == 0, out.err
- @pytest.mark.parametrize(
- "text",
- [
- "resource = aws_nat_gateway n {}\n",
- "resource aws_nat_gateway = {}\n",
- "module r = {\n}\n",
- ],
- )
- def test_a_label_cannot_contain_an_equals_sign(text):
- assert cost_check.find_blocks(text) == []
- # unknown plan values
- def with_config(pl, expressions):
- """Attach a `configuration` block shaped like `tofu show -json`: a resource's
- config lists only the attributes the configuration sets."""
- pl["configuration"] = {
- "root_module": {
- "resources": [
- {
- "address": address,
- "mode": "managed",
- "type": "aws_instance",
- "name": address.split(".")[-1],
- "expressions": exprs,
- }
- for address, exprs in expressions.items()
- ]
- }
- }
- return pl
- def inst_unknown(unknown, **after_extra):
- change_ = inst("a", **after_extra)
- change_["change"]["after_unknown"] = unknown
- return change_
- UNKNOWN_CASES = [
- ("monitoring", {"monitoring": True}, {"monitoring": None}),
- ("tenancy", {"tenancy": True}, {}),
- (
- "credit_specification",
- {"credit_specification": [{"cpu_credits": True}]},
- {"credit_specification": [{"cpu_credits": "standard"}]},
- ),
- ("instance_market_options", {"instance_market_options": True}, {}),
- ("placement_group", {"placement_group": True}, {}),
- ("host_id", {"host_id": True}, {}),
- ("host_resource_group_arn", {"host_resource_group_arn": True}, {}),
- ("license_specification", {"license_specification": True}, {}),
- ("network_interface", {"network_interface": True}, {}),
- ("launch_template", {"launch_template": [{"id": True}]}, {}),
- ]
- @pytest.mark.parametrize("attr,unknown,after", UNKNOWN_CASES)
- def test_an_unknown_value_the_config_sets_is_a_problem(attr, unknown, after):
- pl = plan(inst_unknown(unknown, **after))
- with_config(
- pl, {"aws_instance.a": {attr: {"references": ["terraform_data.x.output"]}}}
- )
- problems = cost_check.plan_cost(pl, AWS_PRICES)[1]
- assert any("unpriced attribute" in p and attr in p for p in problems), problems
- @pytest.mark.parametrize("attr,unknown,after", UNKNOWN_CASES)
- def test_an_unknown_computed_default_the_config_does_not_set_passes(
- attr, unknown, after
- ):
- pl = plan(inst_unknown(unknown, **after))
- with_config(
- pl, {"aws_instance.a": {"instance_type": {"constant_value": "t4g.micro"}}}
- )
- assert cost_check.plan_cost(pl, AWS_PRICES)[1] == []
- @pytest.mark.parametrize("attr,unknown,after", UNKNOWN_CASES)
- def test_an_unknown_value_with_no_configuration_fails_closed(attr, unknown, after):
- pl = plan(inst_unknown(unknown, **after))
- problems = cost_check.plan_cost(pl, AWS_PRICES)[1]
- assert any("unpriced attribute" in p and attr in p for p in problems), problems
- def module_plan(expressions):
- change_ = inst_unknown({"tenancy": True})
- change_["address"] = "module.m.aws_instance.a[0]"
- change_["module_address"] = "module.m"
- pl = plan(change_)
- pl["configuration"] = {
- "root_module": {
- "module_calls": {
- "m": {
- "module": {
- "resources": [
- {
- "mode": "managed",
- "type": "aws_instance",
- "name": "a",
- "expressions": expressions,
- }
- ]
- }
- }
- }
- }
- }
- return pl
- def test_an_unknown_value_in_a_module_instance_is_found_through_module_calls():
- pl = module_plan({"tenancy": {"references": ["var.t"]}})
- problems = cost_check.plan_cost(pl, AWS_PRICES)[1]
- assert any("unpriced attribute" in p and "tenancy" in p for p in problems)
- def test_a_module_instance_whose_config_does_not_set_it_passes():
- assert cost_check.plan_cost(module_plan({}), AWS_PRICES)[1] == []
- @pytest.mark.parametrize("itype", ["t3.micro", "t4g.micro", "t3a.small", "t2.micro"])
- def test_a_burstable_instance_without_standard_credits_fails_closed(itype):
- prices = dict(AWS_PRICES)
- prices["instances"] = {**AWS_PRICES["instances"], itype: 0.01}
- for spec in (None, [], [{"cpu_credits": ""}]):
- _, problems = cost_check.plan_cost(
- plan(inst(itype=itype, credit_specification=spec)), prices
- )
- assert problems and "credit_specification" in problems[0], (itype, spec)
- def test_a_burstable_instance_with_standard_credits_is_priced():
- total, problems = cost_check.plan_cost(plan(inst("a"), inst("b")), AWS_PRICES)
- assert (total, problems) == (20.84, [])
- def test_a_non_burstable_type_does_not_need_credit_specification():
- prices = dict(AWS_PRICES)
- prices["instances"] = {**AWS_PRICES["instances"], "m7g.large": 0.0816}
- _, problems = cost_check.plan_cost(
- plan(inst(itype="m7g.large", credit_specification=None)), prices
- )
- assert problems == []
|