Mock CDK Synth Output in Python for Template Testing
Simulate AWS CDK synth output with MagicMock to test or preview CloudFormation templates without running a real CDK app.
Python code
34 linesimport json
from unittest.mock import MagicMock
def mock_cdk_synth() -> dict:
"""Simulate AWS CDK synth output for a simple S3 bucket."""
cdk_app = MagicMock()
cdk_app.synth.return_value.template = {
"Resources": {
"MyBucket": {
"Type": "AWS::S3::Bucket",
"Properties": {
"BucketName": "mock-cdk-bucket",
"VersioningConfiguration": {"Status": "Enabled"}
}
}
},
"Outputs": {
"BucketArn": {
"Value": {"Fn::GetAtt": ["MyBucket", "Arn"]}
}
}
}
template = cdk_app.synth().template
return {
"Resources": template["Resources"],
"Outputs": template["Outputs"]
}
if __name__ == "__main__":
result = mock_cdk_synth()
print(json.dumps(result, indent=2))
print(f"\nResource count: {len(result['Resources'])}")
Output
{
"Resources": {
"MyBucket": {
"Type": "AWS::S3::Bucket",
"Properties": {
"BucketName": "mock-cdk-bucket",
"VersioningConfiguration": {
"Status": "Enabled"
}
}
}
},
"Outputs": {
"BucketArn": {
"Value": {
"Fn::GetAtt": [
"MyBucket",
"Arn"
]
}
}
}
}
Resource count: 1
How it works
The MagicMock object simulates a CDK app by configuring synth().template to return a hardcoded CloudFormation template dictionary. When cdk_app.synth() is called, the mock returns a MagicMock whose .template attribute holds the template, matching CDK's actual synth chain. Extracting Resources and Outputs mirrors how you'd inspect a real synthesized template in tests. This approach decouples template verification from the CDK runtime, making unit tests fast and deterministic. The json.dumps call in __main__ renders the result exactly as AWS would when exporting a template.
Common mistakes
- Forgetting that `synth()` returns a mock whose `.template` is set, not the template itself
- Using `return_value` on the wrong part of the chained mock (e.g., on `template` instead of `synth`)
- Assuming the mock template reflects your real CDK resources when it's only static test data
Variations
- Use `unittest.mock.patch` to mock a real CDK `App` object in a pytest unit test
- Load the template from a local JSON file instead of a hardcoded dict for larger stacks
Real-world use cases
- Unit testing CloudFormation assertions in CI without needing the CDK CLI installed.
- Previewing resource shapes and outputs before deployment for team review in PRs.
- Generating golden-file templates for infrastructure regression testing.
Sponsored
More from Cloud + Python
- Build a URL Shortener Client with Python medium
- Create a Cloud Storage Helper Class in Python easy
- Create a Data Helper Class for Beginners in Python easy
- Cross Account Role Chaining Mock Credentials in Python medium
- Exponential Backoff with Jitter for Cloud API Calls in Python medium
- Generate Mock CloudFormation Stack Events in Python easy
Keep learning
Related tutorials and quizzes for this topic.