Skip to content

Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.

fix: CloudFormation post-merge fixes — asyncio deprecation, Lambda ZipFile, CI deps, test cleanup (v1.1.13) (#53)

Nahuel Nucerad8931cc5841f
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 201fc5e2..67062439 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -31,7 +31,7 @@ jobs:
cache: "pip"
- name: Install dependencies
- run: pip install -r requirements.txt boto3 pytest duckdb docker cbor2
+ run: pip install -r requirements.txt boto3 pytest duckdb docker cbor2 pyyaml
- name: Start MiniStack
run: |
diff --git a/.gitignore b/.gitignore
index bb3be9bf..ce335615 100644
--- a/.gitignore
+++ b/.gitignore
@@ -50,14 +50,3 @@ data/
# Logs
*.log
-
-# Research artifacts
-localstack/
-
-# Lock files
-uv.lock
-
-# WFC plans (local)
-plans/
-.hypothesis/
-.claude/
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e806dfa5..03043552 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,20 @@ Versioning follows [Semantic Versioning](https://semver.org/).
---
+## [1.1.13] — 2026-04-01
+
+### Added
+- **CloudFormation** — full stack lifecycle: `CreateStack`, `UpdateStack`, `DeleteStack`, `DescribeStacks`, `ListStacks`, `DescribeStackEvents`, `DescribeStackResource`, `DescribeStackResources`, `GetTemplate`, `ValidateTemplate`, `GetTemplateSummary`, `ListExports`; change sets (`CreateChangeSet`, `DescribeChangeSet`, `ExecuteChangeSet`, `DeleteChangeSet`, `ListChangeSets`); JSON and YAML template support including `!Ref`, `!Sub`, `!GetAtt` shorthand; full intrinsic function resolution (`Ref`, `Fn::GetAtt`, `Fn::Join`, `Fn::Sub`, `Fn::Select`, `Fn::Split`, `Fn::If`, `Fn::Base64`, `Fn::FindInMap`, `Fn::ImportValue`, `Fn::GetAZs`, `Fn::Cidr`); conditions (`Fn::Equals`, `Fn::And`, `Fn::Or`, `Fn::Not`); parameters with `AllowedValues`, `Default`, `NoEcho`; rollback on failure with reverse-order cleanup; cross-stack exports via `Fn::ImportValue`; 12 resource types provisioned directly into service state (`AWS::S3::Bucket`, `AWS::SQS::Queue`, `AWS::SNS::Topic`, `AWS::SNS::Subscription`, `AWS::DynamoDB::Table`, `AWS::Lambda::Function`, `AWS::IAM::Role`, `AWS::IAM::Policy`, `AWS::IAM::InstanceProfile`, `AWS::SSM::Parameter`, `AWS::Logs::LogGroup`, `AWS::Events::Rule`). Contributed by @sam-fakhreddine
+
+### Fixed
+- **CloudFormation Lambda `ZipFile`** — inline `Code.ZipFile` source is now correctly packaged into a zip archive, making CFN-deployed Lambda functions invokable
+- **CloudFormation async task** — replaced deprecated `asyncio.ensure_future()` with `asyncio.get_event_loop().create_task()` in stack deploy, delete, and change set execution
+
+### Tests
+- 788 tests total, all passing
+
+---
+
## [1.1.12] — 2026-03-31
### Changed
@@ -35,7 +49,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [1.1.10] — 2026-03-31
### Fixed
-- **ECS Docker network detection** — ECS containers now automatically join the same Docker network that MiniStack is running on, so containers can reach sibling services (S3, SQS, etc.) without manual network configuration
+- **ECS Docker network detection** — ECS containers now automatically join the same Docker network that MiniStack is running on, so containers can reach sibling services (S3, SQS, etc.) without manual network configuration. Contributed by @mickabd
- **Internal naming cleanup** — replaced all internal `localstack-*` references (logger name, default data dir `/tmp/localstack-data/s3` → `/tmp/ministack-data/s3`, healthcheck URLs, CI config) with `ministack` equivalents; `LOCALSTACK_PERSISTENCE` / `LOCALSTACK_HOSTNAME` env vars kept for migration compatibility
- **DynamoDB GSI capacity accounting** — `PutItem`, `DeleteItem`, `UpdateItem`, `GetItem`, `Query`, `Scan`, and `BatchWriteItem` now return correct `ConsumedCapacity.CapacityUnits` when a table has Global Secondary Indexes: `1 + gsi_count` per write (matching real AWS); `INDEXES` mode also returns per-GSI breakdown. Contributed by @jespinoza-shippo.
- **S3 `CreateBucket` idempotency** — creating a bucket you already own now returns 200 instead of 409 `BucketAlreadyOwnedByYou`, matching real AWS and fixing Terraform re-apply failures
@@ -58,6 +72,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
- `PutObjectRetention` / `GetObjectRetention` — per-object retention with `COMPLIANCE` (always blocks delete) and `GOVERNANCE` (`x-amz-bypass-governance-retention` header bypasses)
- `PutObjectLegalHold` / `GetObjectLegalHold` — `ON` status unconditionally blocks deletion regardless of retention mode
- Default retention auto-applied on `PutObject` when bucket lock configuration is present
+ @Contributed by @mickabd
- **S3 Replication** — bucket-level replication configuration CRUD
- `PutBucketReplication` / `GetBucketReplication` / `DeleteBucketReplication`
- **S3 Tagging improvements** — URL-encoded tagging header parsing now correctly handles `x-amz-tagging` on `PutObject` and `CopyObject`
@@ -95,7 +110,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
- **Flow Logs**: `CreateFlowLogs`, `DescribeFlowLogs`, `DeleteFlowLogs` — supports VPC/subnet/ENI resource targets, CloudWatch Logs and S3 destinations, `resource-id` filter
- **VPC Peering**: `CreateVpcPeeringConnection`, `AcceptVpcPeeringConnection`, `DescribeVpcPeeringConnections`, `DeleteVpcPeeringConnection` — full lifecycle from `pending-acceptance` → `active` → `deleted`, cross-account/cross-region params accepted
- **DHCP Options**: `CreateDhcpOptions`, `AssociateDhcpOptions`, `DescribeDhcpOptions`, `DeleteDhcpOptions` — arbitrary key/value configurations, association updates `VpcId.DhcpOptionsId`
- - **Egress-Only Internet Gateways**: `CreateEgressOnlyInternetGateway`, `DescribeEgressOnlyInternetGateways`, `DeleteEgressOnlyInternetGateway` — IPv6 egress-only IGW for VPCs
+ - **Egress-Only Internet Gateways**: `CreateEgressOnlyInternetGateway`, `DescribeEgressOnlyInternetGateways`, `DeleteEgressOnlyInternetGateway` — IPv6 egress-only IGW for VPCs. Contributed by @mickabd
### Fixed
- **SQS `awsQueryCompatible` header** — all SQS JSON error responses now include the `x-amzn-query-error: <legacy_code>;<fault>` header required by the `awsQueryCompatible` service trait. botocore reads this header and overrides `Error.Code` with the legacy `AWS.SimpleQueueService.*` namespaced code (e.g. `AWS.SimpleQueueService.NonExistentQueue` instead of `QueueDoesNotExist`). Without this header, any SDK code that matched against the legacy string worked against real AWS but silently failed against MiniStack. Full mapping of all 28 SQS error shapes sourced from `aws-sdk-go` ErrCode constants. Contributed by @jespinoza-shippo.
diff --git a/README.md b/README.md
index 4af64ddf..e671f744 100644
--- a/README.md
+++ b/README.md
@@ -21,7 +21,7 @@
LocalStack recently moved its core services behind a paid plan. If you relied on LocalStack Community for local development and CI/CD pipelines, MiniStack is your free alternative.
-- **31 AWS services** emulated on a single port (4566)
+- **34 AWS services** emulated on a single port (4566)
- **Drop-in compatible** — works with `boto3`, AWS CLI, Terraform, CDK, Pulumi, any SDK
- **Real infrastructure** — RDS spins up actual Postgres/MySQL containers, ElastiCache spins up real Redis, Athena runs real SQL via DuckDB, ECS runs real Docker containers
- **Tiny footprint** — ~150MB image, ~30MB RAM at idle vs LocalStack's ~1GB image and ~500MB RAM
@@ -504,7 +504,7 @@ pip install boto3 pytest duckdb docker cbor2
# Start MiniStack
docker compose up -d
-# Run the full test suite (760 tests across all 33 services)
+# Run the full test suite (788 tests across all 34 services)
pytest tests/ -v
```
@@ -622,7 +622,7 @@ config:
| **ACM** | ✅ | ✅ | ✅ |
| **SES v2** | ✅ | ✅ | ✅ |
| **WAF v2** | ✅ | Paid | ✅ |
-| **CloudFormation** | **partial** | partial | ✅ |
+| **CloudFormation** | **partial** | partial | ✅ Free |
| Cost | **Free** | Was free, now paid | $35+/mo |
| Docker image size | ~150MB | ~1GB | ~1GB |
| Memory at idle | ~30MB | ~500MB | ~500MB |
diff --git a/ministack/services/cloudformation/changesets.py b/ministack/services/cloudformation/changesets.py
index 878dc2f6..cc2279d3 100644
--- a/ministack/services/cloudformation/changesets.py
+++ b/ministack/services/cloudformation/changesets.py
@@ -261,7 +261,7 @@ def _execute_change_set(params):
"AWS::CloudFormation::Stack", f"{status_prefix}_IN_PROGRESS",
physical_id=stack_id)
- asyncio.ensure_future(
+ asyncio.get_event_loop().create_task(
_deploy_stack_async(real_stack_name, stack_id, template,
param_values, False, tags,
is_update=is_update,
diff --git a/ministack/services/cloudformation/handlers.py b/ministack/services/cloudformation/handlers.py
index 2ed29f13..e415b80b 100644
--- a/ministack/services/cloudformation/handlers.py
+++ b/ministack/services/cloudformation/handlers.py
@@ -100,7 +100,7 @@ def _create_stack(params):
"AWS::CloudFormation::Stack", "CREATE_IN_PROGRESS",
physical_id=stack_id)
- asyncio.ensure_future(
+ asyncio.get_event_loop().create_task(
_deploy_stack_async(stack_name, stack_id, template,
param_values, disable_rollback, tags)
)
@@ -387,7 +387,7 @@ def _delete_stack(params):
f"Export {export_name} is imported by stack {other_name}")
stack_id = stack["StackId"]
- asyncio.ensure_future(_delete_stack_async(stack_name, stack_id))
+ asyncio.get_event_loop().create_task(_delete_stack_async(stack_name, stack_id))
return _xml(200, "DeleteStackResponse", "")
@@ -461,7 +461,7 @@ def _update_stack(params):
"AWS::CloudFormation::Stack", "UPDATE_IN_PROGRESS",
physical_id=stack_id)
- asyncio.ensure_future(
+ asyncio.get_event_loop().create_task(
_deploy_stack_async(stack_name, stack_id, template,
param_values, disable_rollback, tags,
is_update=True, previous_stack=previous_stack)
diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.py
index 5c5fe516..1cceb08a 100644
--- a/ministack/services/cloudformation/provisioners.py
+++ b/ministack/services/cloudformation/provisioners.py
@@ -2,9 +2,11 @@
CloudFormation provisioners — resource create/delete handlers for each AWS resource type.
"""
+import io
import json
import logging
import time
+import zipfile
from collections import defaultdict
from ministack.core.responses import new_uuid, now_iso
@@ -308,6 +310,17 @@ def _ddb_delete(physical_id, props):
# --- Lambda Function ---
+def _zip_inline(source: str | None, handler: str) -> bytes | None:
+ """Wrap inline ZipFile source code into a real zip archive."""
+ if not source:
+ return None
+ module = handler.split(".")[0] if handler and "." in handler else "index"
+ buf = io.BytesIO()
+ with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
+ zf.writestr(f"{module}.py", source)
+ return buf.getvalue()
+
+
def _lambda_create(logical_id, props, stack_name):
name = props.get("FunctionName") or f"{stack_name}-{logical_id}-{new_uuid()[:8]}"
arn = f"arn:aws:lambda:{REGION}:{ACCOUNT_ID}:function:{name}"
@@ -344,7 +357,7 @@ def _lambda_create(logical_id, props, stack_name):
"TracingConfig": props.get("TracingConfig", {"Mode": "PassThrough"}),
"RevisionId": new_uuid(),
},
- "code_zip": None,
+ "code_zip": _zip_inline(code.get("ZipFile"), handler),
"code_s3_bucket": code.get("S3Bucket"),
"code_s3_key": code.get("S3Key"),
"versions": {},
diff --git a/pyproject.toml b/pyproject.toml
index a396ad9e..ac44ac3f 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -39,7 +39,6 @@ dev = [
"duckdb>=0.10.0",
"docker>=7.0.0",
"ruff>=0.4",
- "hypothesis>=6.0",
]
[project.urls]
diff --git a/tests/test_cfn_integration_properties.py b/tests/test_cfn_integration_properties.py
deleted file mode 100644
index 018ec646..00000000
--- a/tests/test_cfn_integration_properties.py
+++ /dev/null
@@ -1,384 +0,0 @@
-"""Hypothesis-based integration tests for the CloudFormation service.
-
-These tests run against a LIVE ministack server via boto3. They generate
-random CloudFormation templates and verify deployment invariants.
-"""
-
-import json
-import os
-import string
-import time
-import urllib.request
-
-import boto3
-import pytest
-from botocore.config import Config
-from botocore.exceptions import ClientError
-from hypothesis import given, settings, assume, HealthCheck
-import hypothesis.strategies as st
-
-from ministack.services.cloudformation import _parse_template
-
-ENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")
-
-_kwargs = dict(
- endpoint_url=ENDPOINT,
- aws_access_key_id="test",
- aws_secret_access_key="test",
- region_name="us-east-1",
- config=Config(region_name="us-east-1", retries={"max_attempts": 0}),
-)
-
-
-def _make_client(service):
- return boto3.client(service, **_kwargs)
-
-
-def _wait_stack(cfn, name, timeout=25):
- deadline = time.time() + timeout
- while time.time() < deadline:
- stacks = cfn.describe_stacks(StackName=name)["Stacks"]
- status = stacks[0]["StackStatus"]
- if not status.endswith("_IN_PROGRESS"):
- return stacks[0]
- time.sleep(0.5)
- raise TimeoutError(f"Stack {name} stuck at {status}")
-
-
-def _reset_server():
- req = urllib.request.Request(
- f"{ENDPOINT}/_ministack/reset", data=b"", method="POST"
- )
- try:
- urllib.request.urlopen(req, timeout=5)
- except Exception:
- pass
-
-
[email protected](autouse=True)
-def reset_between_tests():
- _reset_server()
-
-
-# ---------------------------------------------------------------------------
-# Resource types and minimal properties
-# ---------------------------------------------------------------------------
-
-RESOURCE_TYPES = [
- "AWS::S3::Bucket",
- "AWS::SQS::Queue",
- "AWS::SNS::Topic",
- "AWS::DynamoDB::Table",
- "AWS::Lambda::Function",
- "AWS::IAM::Role",
- "AWS::SSM::Parameter",
- "AWS::Logs::LogGroup",
- "AWS::Events::Rule",
-]
-
-TYPES_WITH_ARN = {
- "AWS::S3::Bucket",
- "AWS::SQS::Queue",
- "AWS::SNS::Topic",
- "AWS::DynamoDB::Table",
- "AWS::Lambda::Function",
- "AWS::IAM::Role",
- "AWS::Logs::LogGroup",
- "AWS::Events::Rule",
-}
-
-
-def _props_for_type(rtype, name):
- if rtype == "AWS::S3::Bucket":
- return {"BucketName": name}
- elif rtype == "AWS::SQS::Queue":
- return {"QueueName": name}
- elif rtype == "AWS::SNS::Topic":
- return {"TopicName": name}
- elif rtype == "AWS::DynamoDB::Table":
- return {
- "TableName": name,
- "KeySchema": [{"AttributeName": "id", "KeyType": "HASH"}],
- "AttributeDefinitions": [
- {"AttributeName": "id", "AttributeType": "S"}
- ],
- }
- elif rtype == "AWS::Lambda::Function":
- return {
- "FunctionName": name,
- "Runtime": "python3.12",
- "Handler": "index.handler",
- "Role": "arn:aws:iam::000000000000:role/fake",
- "Code": {"ZipFile": "def handler(e,c): pass"},
- }
- elif rtype == "AWS::IAM::Role":
- return {
- "RoleName": name,
- "AssumeRolePolicyDocument": {
- "Version": "2012-10-17",
- "Statement": [
- {
- "Effect": "Allow",
- "Principal": {"Service": "lambda.amazonaws.com"},
- "Action": "sts:AssumeRole",
- }
- ],
- },
- }
- elif rtype == "AWS::SSM::Parameter":
- return {"Name": f"/{name}", "Type": "String", "Value": "test"}
- elif rtype == "AWS::Logs::LogGroup":
- return {"LogGroupName": f"/{name}"}
- elif rtype == "AWS::Events::Rule":
- return {
- "Name": name,
- "ScheduleExpression": "rate(1 hour)",
- "State": "ENABLED",
- }
- return {}
-
-
-# ---------------------------------------------------------------------------
-# Hypothesis strategies
-# ---------------------------------------------------------------------------
-
-
-def random_cfn_template(draw):
- slug = draw(
- st.text(alphabet=string.ascii_lowercase, min_size=4, max_size=6)
- )
- count = draw(st.integers(min_value=1, max_value=6))
- resources = {}
- for i in range(count):
- rtype = draw(st.sampled_from(RESOURCE_TYPES))
- name = f"hyp-{slug}-{i}"
- resources[f"Res{i}"] = {
- "Type": rtype,
- "Properties": _props_for_type(rtype, name),
- }
- template = {
- "AWSTemplateFormatVersion": "2010-09-09",
- "Resources": resources,
- }
- return (f"hyp-{slug}", template)
-
-
-def random_cfn_template_with_outputs(draw):
- stack_name, template = draw(random_cfn_template())
- outputs = {}
- for logical_id, res in template["Resources"].items():
- idx = logical_id.replace("Res", "")
- outputs[f"Out{idx}Ref"] = {"Value": {"Ref": logical_id}}
- if res["Type"] in TYPES_WITH_ARN:
- outputs[f"Out{idx}Arn"] = {
- "Value": {"Fn::GetAtt": [logical_id, "Arn"]}
- }
- template["Outputs"] = outputs
- return (stack_name, template)
-
-
-def broken_cfn_template(draw):
- kind = draw(st.sampled_from(["bad_type", "not_json"]))
- slug = draw(
- st.text(alphabet=string.ascii_lowercase, min_size=4, max_size=6)
- )
- stack_name = f"hyp-brk-{slug}"
- if kind == "bad_type":
- template = {
- "AWSTemplateFormatVersion": "2010-09-09",
- "Resources": {
- "Bad0": {
- "Type": "AWS::Fake::DoesNotExist",
- "Properties": {},
- }
- },
- }
- return (kind, stack_name, json.dumps(template))
- else:
- raw = draw(
- st.text(
- alphabet=string.ascii_letters + string.digits,
- min_size=5,
- max_size=30,
- )
- )
- return (kind, stack_name, raw)
-
-
-# ---------------------------------------------------------------------------
-# Snapshot helper for cleanup verification
-# ---------------------------------------------------------------------------
-
-
-def _snapshot():
- s3 = _make_client("s3")
- sqs = _make_client("sqs")
- sns = _make_client("sns")
- ddb = _make_client("dynamodb")
- lam = _make_client("lambda")
- iam = _make_client("iam")
- ssm = _make_client("ssm")
- logs = _make_client("logs")
- events = _make_client("events")
- return {
- "s3": len(s3.list_buckets()["Buckets"]),
- "sqs": len(sqs.list_queues().get("QueueUrls", [])),
- "sns": len(sns.list_topics()["Topics"]),
- "dynamodb": len(ddb.list_tables()["TableNames"]),
- "lambda": len(lam.list_functions()["Functions"]),
- "iam_roles": len(
- [
- r
- for r in iam.list_roles()["Roles"]
- if r["RoleName"].startswith("hyp-")
- ]
- ),
- "ssm": len(ssm.describe_parameters()["Parameters"]),
- "logs": len(logs.describe_log_groups()["logGroups"]),
- "events": len(events.list_rules()["Rules"]),
- }
-
-
-# ---------------------------------------------------------------------------
-# Tests
-# ---------------------------------------------------------------------------
-
-
-@given(random_cfn_template())
-@settings(max_examples=100)
-def test_generator_produces_valid_templates(data):
- """Generator produces structurally valid templates (no server)."""
- stack_name, template = data
- assert "Resources" in template
- assert len(template["Resources"]) >= 1
- for res in template["Resources"].values():
- assert res["Type"] in RESOURCE_TYPES
- parsed = _parse_template(json.dumps(template))
- assert "Resources" in parsed
-
-
-@given(random_cfn_template())
-@settings(
- max_examples=20,
- deadline=45000,
- suppress_health_check=[HealthCheck.too_slow],
-)
-def test_all_resources_tracked_in_stack(data):
- """Every template resource appears in describe_stack_resources."""
- cfn = _make_client("cloudformation")
- stack_name, template = data
- cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(template))
- stack = _wait_stack(cfn, stack_name)
- assume(stack["StackStatus"] == "CREATE_COMPLETE")
- resources = cfn.describe_stack_resources(StackName=stack_name)[
- "StackResources"
- ]
- template_ids = set(template["Resources"].keys())
- stack_ids = {r["LogicalResourceId"] for r in resources}
- assert template_ids == stack_ids
- cfn.delete_stack(StackName=stack_name)
- _wait_stack(cfn, stack_name)
-
-
-@given(random_cfn_template())
-@settings(
- max_examples=15,
- deadline=60000,
- suppress_health_check=[HealthCheck.too_slow],
-)
-def test_delete_cleans_up_all_resources(data):
- """Deleting a stack leaves service state unchanged."""
- cfn = _make_client("cloudformation")
- stack_name, template = data
- before = _snapshot()
- cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(template))
- stack = _wait_stack(cfn, stack_name)
- assume(stack["StackStatus"] == "CREATE_COMPLETE")
- cfn.delete_stack(StackName=stack_name)
- _wait_stack(cfn, stack_name)
- after = _snapshot()
- assert before == after, (
- f"Resource leak detected: before={before}, after={after}"
- )
-
-
-@given(random_cfn_template_with_outputs())
-@settings(
- max_examples=20,
- deadline=45000,
- suppress_health_check=[HealthCheck.too_slow],
-)
-def test_outputs_resolve_to_nonempty(data):
- """All declared Outputs resolve to non-empty values."""
- cfn = _make_client("cloudformation")
- stack_name, template = data
- cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(template))
- stack = _wait_stack(cfn, stack_name)
- assume(stack["StackStatus"] == "CREATE_COMPLETE")
- outputs = {o["OutputKey"]: o["OutputValue"] for o in stack.get("Outputs", [])}
- expected_keys = set(template["Outputs"].keys())
- assert expected_keys == set(outputs.keys()), (
- f"Missing outputs: {expected_keys - set(outputs.keys())}"
- )
- for key, value in outputs.items():
- assert value, f"Output {key} resolved to empty"
- assert "${" not in value, f"Output {key} contains unresolved placeholder: {value}"
- if key.endswith("Arn"):
- assert value.startswith("arn:aws:"), (
- f"Output {key} should be an ARN, got: {value}"
- )
- cfn.delete_stack(StackName=stack_name)
- _wait_stack(cfn, stack_name)
-
-
-@given(random_cfn_template())
-@settings(
- max_examples=20,
- deadline=45000,
- suppress_health_check=[HealthCheck.too_slow],
-)
-def test_stack_events_cover_all_resources(data):
- """Every template resource has a CREATE_COMPLETE event."""
- cfn = _make_client("cloudformation")
- stack_name, template = data
- cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(template))
- stack = _wait_stack(cfn, stack_name)
- assume(stack["StackStatus"] == "CREATE_COMPLETE")
- events = cfn.describe_stack_events(StackName=stack_name)["StackEvents"]
- create_complete_ids = {
- e["LogicalResourceId"]
- for e in events
- if e.get("ResourceStatus") == "CREATE_COMPLETE"
- }
- template_ids = set(template["Resources"].keys())
- assert template_ids.issubset(create_complete_ids), (
- f"Resources missing CREATE_COMPLETE event: {template_ids - create_complete_ids}"
- )
- stack_name_in_events = {e.get("StackName") for e in events}
- assert stack_name in stack_name_in_events
- cfn.delete_stack(StackName=stack_name)
- _wait_stack(cfn, stack_name)
-
-
-@given(broken_cfn_template())
-@settings(
- max_examples=20,
- deadline=45000,
- suppress_health_check=[HealthCheck.too_slow],
-)
-def test_invalid_templates_return_structured_errors(data):
- """Invalid templates produce errors, not hangs."""
- kind, stack_name, body = data
- cfn = _make_client("cloudformation")
- if kind == "not_json":
- with pytest.raises(ClientError):
- cfn.create_stack(StackName=stack_name, TemplateBody=body)
- elif kind == "bad_type":
- cfn.create_stack(StackName=stack_name, TemplateBody=body)
- stack = _wait_stack(cfn, stack_name)
- assert stack["StackStatus"] in ("CREATE_FAILED", "ROLLBACK_COMPLETE"), (
- f"Expected terminal failure status, got: {stack['StackStatus']}"
- )
diff --git a/tests/test_cfn_properties.py b/tests/test_cfn_properties.py
deleted file mode 100644
index eaaa1165..00000000
--- a/tests/test_cfn_properties.py
+++ /dev/null
@@ -1,268 +0,0 @@
-"""Hypothesis property-based tests for CloudFormation engine pure functions."""
-
-import json
-import string
-import re
-
-import pytest
-from hypothesis import given, settings, assume
-import hypothesis.strategies as st
-
-from ministack.services.cloudformation import (
- _parse_template,
- _validate_template,
- _resolve_parameters,
- _evaluate_conditions,
- _resolve_refs,
- _extract_deps,
- _topological_sort,
- _NO_VALUE,
-)
-
-# ---------------------------------------------------------------------------
-# Shared constants
-# ---------------------------------------------------------------------------
-STACK_NAME = "test"
-STACK_ID = "arn:aws:cloudformation:us-east-1:000000000000:stack/test/uuid"
-EMPTY_RESOURCES: dict = {}
-EMPTY_PARAMS: dict = {}
-EMPTY_CONDITIONS: dict = {}
-EMPTY_MAPPINGS: dict = {}
-
-# Intrinsic function key prefixes to filter out
-_INTRINSIC_PREFIXES = ("Ref", "Fn::Join", "Fn::Sub", "Fn::Select", "Fn::Split",
- "Fn::If", "Fn::Base64", "Fn::FindInMap", "Fn::GetAtt",
- "Fn::GetAZs", "Fn::Cidr", "Fn::ImportValue", "Fn::Equals",
- "Fn::And", "Fn::Or", "Fn::Not", "Condition")
-
-def _has_intrinsic_keys(obj):
- """Return True if obj (or any nested value) contains intrinsic function keys."""
- if isinstance(obj, dict):
- for key in obj:
- if key in _INTRINSIC_PREFIXES or key.startswith("Fn::"):
- return True
- if _has_intrinsic_keys(obj[key]):
- return True
- elif isinstance(obj, list):
- return any(_has_intrinsic_keys(item) for item in obj)
- return False
-
-# ---------------------------------------------------------------------------
-# Shared strategies
-# ---------------------------------------------------------------------------
-_json_values = st.recursive(
- st.text(min_size=0, max_size=20) | st.integers(-1000, 1000) | st.booleans(),
- lambda children: (
- st.lists(children, max_size=5)
- | st.dictionaries(
- st.text(alphabet=string.ascii_letters, min_size=1, max_size=8),
- children,
- max_size=5,
- )
- ),
- max_leaves=20,
-)
-
-def random_dag(draw):
- """Generate a random DAG as a CloudFormation resources dict.
-
- Resources are named R0..R(N-1). Edges go from higher-index to lower-index
- only (j depends on i where i < j), guaranteeing acyclicity.
- """
- n = draw(st.integers(min_value=2, max_value=15))
- resources = {}
- for j in range(n):
- deps = []
- for i in range(j):
- if draw(st.booleans()):
- deps.append(f"R{i}")
- defn = {"Type": "AWS::CloudFormation::WaitConditionHandle"}
- if deps:
- defn["DependsOn"] = deps
- resources[f"R{j}"] = defn
- return resources
-
-def cyclic_resources(draw):
- """Generate resources with a guaranteed circular dependency (ring)."""
- n = draw(st.integers(min_value=3, max_value=8))
- resources = {}
- for i in range(n):
- dep_index = (i - 1) % n
- resources[f"R{i}"] = {
- "Type": "AWS::CloudFormation::WaitConditionHandle",
- "DependsOn": [f"R{dep_index}"],
- }
- return resources
-
-@given(
- st.dictionaries(
- st.text(alphabet=string.ascii_letters, min_size=1, max_size=8),
- _json_values,
- min_size=1,
- max_size=5,
- )
-)
-@settings(max_examples=100)
-def test_ht001_parse_template_json_roundtrip(d):
- d["Resources"] = {}
- raw = json.dumps(d)
- parsed = _parse_template(raw)
- for key in d:
- assert key in parsed, f"Key {key!r} missing after parse"
-
-@given(_json_values)
-@settings(max_examples=100)
-def test_ht002_resolve_refs_identity_on_plain_values(value):
- assume(not _has_intrinsic_keys(value))
- result = _resolve_refs(
- value, EMPTY_RESOURCES, EMPTY_PARAMS, EMPTY_CONDITIONS,
- EMPTY_MAPPINGS, STACK_NAME, STACK_ID,
- )
- assert result == value
-
-@given(random_dag())
-@settings(max_examples=100)
-def test_ht003_topo_sort_all_resources_present(resources):
- order = _topological_sort(resources, {})
- assert set(order) == set(resources.keys())
-
-@given(random_dag())
-@settings(max_examples=100)
-def test_ht004_topo_sort_deps_respected(resources):
- order = _topological_sort(resources, {})
- for name, defn in resources.items():
- deps = defn.get("DependsOn", [])
- if isinstance(deps, str):
- deps = [deps]
- for dep in deps:
- assert order.index(dep) < order.index(name), (
- f"{dep} should come before {name} in topological order"
- )
-
-@given(random_dag())
-@settings(max_examples=100)
-def test_ht005_topo_sort_deterministic(resources):
- order1 = _topological_sort(resources, {})
- order2 = _topological_sort(resources, {})
- assert order1 == order2
-
-@given(cyclic_resources())
-@settings(max_examples=100)
-def test_ht006_topo_sort_circular_detection(resources):
- with pytest.raises(ValueError, match=r"(?i)circular"):
- _topological_sort(resources, {})
-
-@given(
- st.lists(
- st.tuples(
- st.text(alphabet=string.ascii_letters, min_size=1, max_size=10),
- st.text(min_size=0, max_size=10),
- st.text(min_size=0, max_size=10),
- ),
- min_size=1,
- max_size=5,
- )
-)
-@settings(max_examples=100)
-def test_ht007_condition_evaluator_is_pure(cond_specs):
- conditions = {}
- for name, left, right in cond_specs:
- conditions[name] = {"Fn::Equals": [left, right]}
- template = {"Conditions": conditions}
- params: dict = {}
- result1 = _evaluate_conditions(template, params)
- result2 = _evaluate_conditions(template, params)
- assert result1 == result2
-
-@given(
- st.text(alphabet=string.ascii_letters + string.digits, min_size=1, max_size=3),
- st.lists(
- st.text(alphabet=string.ascii_letters + string.digits, min_size=1, max_size=10),
- min_size=1,
- max_size=10,
- ),
-)
-@settings(max_examples=100)
-def test_ht008_join_split_roundtrip(delimiter, parts):
- # Ensure no part contains the delimiter
- assume(all(delimiter not in part for part in parts))
-
- joined = _resolve_refs(
- {"Fn::Join": [delimiter, parts]},
- EMPTY_RESOURCES, EMPTY_PARAMS, EMPTY_CONDITIONS,
- EMPTY_MAPPINGS, STACK_NAME, STACK_ID,
- )
- split_back = _resolve_refs(
- {"Fn::Split": [delimiter, joined]},
- EMPTY_RESOURCES, EMPTY_PARAMS, EMPTY_CONDITIONS,
- EMPTY_MAPPINGS, STACK_NAME, STACK_ID,
- )
- assert split_back == parts
-
-@given(
- st.lists(
- st.text(alphabet=string.ascii_letters, min_size=1, max_size=10),
- min_size=1,
- max_size=20,
- ),
- st.data(),
-)
-@settings(max_examples=100)
-def test_ht009_fn_select_valid_index(items, data):
- idx = data.draw(st.integers(min_value=0, max_value=len(items) - 1))
- result = _resolve_refs(
- {"Fn::Select": [idx, items]},
- EMPTY_RESOURCES, EMPTY_PARAMS, EMPTY_CONDITIONS,
- EMPTY_MAPPINGS, STACK_NAME, STACK_ID,
- )
- assert result == items[idx]
-
-@given(
- st.lists(
- st.text(alphabet=string.ascii_letters + string.digits, min_size=1, max_size=10),
- min_size=2,
- max_size=5,
- unique=True,
- ),
- st.text(alphabet=string.ascii_letters + string.digits, min_size=1, max_size=10),
-)
-@settings(max_examples=100)
-def test_ht010_parameter_allowed_values(allowed, test_value):
- template = {
- "Parameters": {
- "Param1": {
- "Type": "String",
- "AllowedValues": allowed,
- }
- }
- }
- provided = [{"Key": "Param1", "Value": test_value}]
- if test_value in allowed:
- result = _resolve_parameters(template, provided)
- assert result["Param1"]["Value"] == test_value
- else:
- with pytest.raises(ValueError, match="AllowedValues"):
- _resolve_parameters(template, provided)
-
-@given(
- st.lists(
- st.text(alphabet=string.ascii_letters, min_size=1, max_size=8),
- min_size=1,
- max_size=5,
- unique=True,
- ),
-)
-@settings(max_examples=100)
-def test_ht011_fn_sub_completeness(var_names):
- template_str = " ".join(f"${{{name}}}" for name in var_names)
- mapping = {name: f"val_{name}" for name in var_names}
- result = _resolve_refs(
- {"Fn::Sub": [template_str, mapping]},
- EMPTY_RESOURCES, EMPTY_PARAMS, EMPTY_CONDITIONS,
- EMPTY_MAPPINGS, STACK_NAME, STACK_ID,
- )
- assert "${" not in result, (
- f"Unresolved substitution in result: {result!r}"
- )
diff --git a/tests/test_services.py b/tests/test_services.py
index 3d018e38..5fc6a6aa 100644
--- a/tests/test_services.py
+++ b/tests/test_services.py
@@ -15374,7 +15374,7 @@ def test_cfn_fn_sub(cfn, ssm):
assert val == "cfn-t06-src-replica"
-def test_cfn_multi_resource_dependencies(cfn):
+def test_cfn_multi_resource_dependencies(cfn, iam, lam):
template = {
"AWSTemplateFormatVersion": "2010-09-09",
"Resources": {
@@ -15408,10 +15408,6 @@ def test_cfn_multi_resource_dependencies(cfn):
}
cfn.create_stack(StackName="cfn-t07", TemplateBody=json.dumps(template))
_wait_stack(cfn, "cfn-t07")
-
- from tests.conftest import make_client
- iam = make_client("iam")
- lam = make_client("lambda")
role = iam.get_role(RoleName="cfn-t07-role")["Role"]
func = lam.get_function(FunctionName="cfn-t07-func")["Configuration"]
assert func["Role"] == role["Arn"]