Skip to content

Testing

Ben Kehoe edited this page Feb 8, 2018 · 3 revisions

The utils module provides utilities to make testing of custom resources easier.

Failure

It's a good idea to set CloudFormationCustomResource.RAISE_ON_FAILURE=True for testing. Normally, if anything goes wrong anywhere, the failure is caught and passed back to CloudFormation, and the Lambda itself does not record an error. For testing, this makes it harder to ensure that a test will fail if something is wrong. Setting the given field means that if the response to CloudFormation would be failure, an exception is raised instead.

Requests

The variable EXAMPLE_REQUEST provides a simple request for reference. To create your own request, use the generate_request function. You must provide:

  • request_type
  • resource_type
  • properties (and old_properties if request_type is Update)
  • response_url, which can be set to CloudFormationCustomResource.DUMMY_RESPONSE_URL_PRINT to prettyprint the response to stdout, or CloudFormationCustomResource.DUMMY_RESPONSE_URL_SILENT to silent swallow the response, or your own actual URL if so desired.

Other inputs are optional, and self-explanatory: stack_id, request_id, logical_resource_id, and physical_resource_id will get generated if not provided.

Responses

To check that your custom resource responses are correct, use the ResponseCapturer class. It gets used like so:

properties = {'Foo': 'bar'}
event = cfn_custom_resource.utils.generate_request(
    'create', 'Custom::MyCustomResource', properties, CloudFormationCustomResource.DUMMY_RESPONSE_URL_SILENT)

obj = MyCustomResource()       
capturer = cfn_custom_resource.utils.ResponseCapturer()
capturer.set(obj)
obj.handle(event, cfn_custom_resource.utils.MockLambdaContext())

# validate capturer.response_content

Lambda context

A MockLambdaContext class is provided that mimics the context object provided to Lambda, in case this is needed during testing.

Clone this wiki locally