Skip to main content

Simple python test helper for AWS CDK

Project description

Python Test Helper for AWS CDK

Python Version GitHub Workflow Status (with branch) GitHub PyPI PRs Welcome

This simple helper facilitates testing CDK constructs from Python unit tests, by wrapping the CDK executable and exposing convenience methods to set up fixtures, execute CDK commands, and parse their output.

It allows for different types of tests: lightweight tests that only use CDK synthesize to ensure code is syntactically correct and the right number and type of resources should be created, or full-fledged tests that run the full deploy cycle, and can then be used to test the actual created resources.

This tool is heavily inspired by this project: terraform-python-testing-helper.

Example Usage

The tests folder contains simple examples on how to write tests for both synth and deploy.

This is a test that uses synth output on an actual module:

import pytest
import cdktest
import json


@pytest.fixture
def output(fixtures_dir):
    cdk = cdktest.CDKTest("custom", fixtures_dir, binary="npx cdk")
    return cdk.synthesize()


def test_vpc_count(output):
    assert len(output.resources["AWS::EC2::VPC"]) == 1

def test_subnet_type(output):
    subnet_output = output.resources["AWS::EC2::Subnet"]
    tag_list = map(lambda x: x["Tags"], subnet_output)
    type_count = Counter(
        [
            item["Value"]
            for sublist in tag_list
            for item in sublist
            if item["Key"] == "aws-cdk:subnet-type"
        ]
    )
    assert (
        type_count["Private"] == 2
    ), f'Expected number of Private subnet is 2, got {type_count["Private"]}'
    assert (
        type_count["Public"] == 2
    ), f'Expected number of Public subnet is 2, got {type_count["Public"]}'

Caching

The CDKTest synthesize and deploy methods have the ability to cache its associate output to a local .cdktest-cache directory. This cache directory will work as a flag. For subsequent calls of the method, the cached folder will be recognized and avoid calling the actual underlying cdk command again and again. Using the cache flag can be significantly faster than running the cdk command again especially if the command is time-intensive.

The benefits of the caching feature include:

  • Faster setup time for testing cdk constructs that don't change between testing sessions

Please see the following example for how to use it:

import pytest
import cdktest


@pytest.fixture(scope="session")
def cdk(request, fixtures_dir):
    cdk = cdktest.CDKTest(
        appdir="no_change",
        basedir=fixtures_dir,
        binary="npx cdk",
        enable_cache=request.param,
    )
    yield cdk

    _LOGGER.debug("Removing cache dir")
    try:
        shutil.rmtree(cdk.cache_dir)
    except FileNotFoundError:
        _LOGGER.debug("%s does not exists", cdk.cache_dir)


@pytest.mark.parametrize("cdk", [True], indirect=True)
def test_use_cache(cdk):
    """
    Ensures cache is used and runs the execute_command() for first call of the
    method only
    """
    for method in cache_methods:
        with patch.object(
            cdk, "execute_command", wraps=cdk.execute_command
        ) as mock_execute_command:
            for _ in range(2):
                getattr(cdk, method)(use_cache=True)
            assert mock_execute_command.call_count == 1

Testing

Tests use the pytest framework and have no other dependency except on the Python cdk library.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

cdktest-0.0.1.tar.gz (12.3 kB view details)

Uploaded Source

Built Distribution

cdktest-0.0.1-py3-none-any.whl (10.9 kB view details)

Uploaded Python 3

File details

Details for the file cdktest-0.0.1.tar.gz.

File metadata

  • Download URL: cdktest-0.0.1.tar.gz
  • Upload date:
  • Size: 12.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.2 CPython/3.11.1

File hashes

Hashes for cdktest-0.0.1.tar.gz
Algorithm Hash digest
SHA256 beecbd13eda370c160d366eac533d4426d9439a77dd74839a428051c396efc39
MD5 3a9c0ea9ea84853238f101fc0aea683e
BLAKE2b-256 463afb91c95dcdb1314b66ebfffdbc93d4abec4d6e54f9347181777f5dac319e

See more details on using hashes here.

File details

Details for the file cdktest-0.0.1-py3-none-any.whl.

File metadata

  • Download URL: cdktest-0.0.1-py3-none-any.whl
  • Upload date:
  • Size: 10.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.2 CPython/3.11.1

File hashes

Hashes for cdktest-0.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 54c4c2dabe489a66be3be5496991dc3523605ff7f6ee2dc6d0c36432269d20f0
MD5 1fcda121d21aacdde795e0cadc152015
BLAKE2b-256 747982741fdb4863470363bbcafefe8ea4f57407f0b69adf5c11ec22a0cf975e

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page