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.

Medium Python 3.9+ Aug 9, 2026 Cloud + Python 12 views 0 copies

Python code

34 lines
Python 3.9+
import 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

stdout
{
  "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

  1. Use `unittest.mock.patch` to mock a real CDK `App` object in a pytest unit test
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Cloud + Python

Related tutorials and quizzes for this topic.