Package: aws-cdk.integ-tests-alpha
integ-tests---The APIs of higher level constructs in this module are experimental and under active development.
They are subject to non-backward compatible changes or removal in any future version. These are
not subject to theSemantic Versioningmodel and breaking changes will be
announced in the release notes. This means that while you may use them, you may need to update
your source code when upgrading to a newer version of this package.OverviewThis library is meant to be used in combination with theinteg-runnerCLI
to enable users to write and execute integration tests for AWS CDK Constructs.An integration test should be defined as a CDK application, and
there should be a 1:1 relationship between an integration test and a CDK application.So for example, in order to create an integration test calledmy-functionwe would need to create a file to contain our integration test application.test/integ.my-function.tsapp=App()stack=Stack()lambda_.Function(stack,"MyFunction",runtime=lambda_.Runtime.NODEJS_LATEST,handler="index.handler",code=lambda_.Code.from_asset(path.join(__dirname,"lambda-handler")))This is a self contained CDK application which we could deploy by runningcdkdeploy--app'node test/integ.my-function.js'In order to turn this into an integration test, all that is needed is to
use theIntegTestconstruct.# app: App# stack: StackIntegTest(app,"Integ",test_cases=[stack])You will notice that thestackis registered to theIntegTestas a test case.
Each integration test can contain multiple test cases, which are just instances
of a stack. See theUsagesection for more details.UsageIntegTestSuppose you have a simple stack, that only encapsulates a Lambda function with a
certain handler:classStackUnderTest(Stack):def__init__(self,scope,id,*,architecture=None,description=None,env=None,stackName=None,tags=None,synthesizer=None,terminationProtection=None,analyticsReporting=None,crossRegionReferences=None,permissionsBoundary=None,suppressTemplateIndentation=None):super().__init__(scope,id,architecture=architecture,description=description,env=env,stackName=stackName,tags=tags,synthesizer=synthesizer,terminationProtection=terminationProtection,analyticsReporting=analyticsReporting,crossRegionReferences=crossRegionReferences,permissionsBoundary=permissionsBoundary,suppressTemplateIndentation=suppressTemplateIndentation)lambda_.Function(self,"Handler",runtime=lambda_.Runtime.NODEJS_LATEST,handler="index.handler",code=lambda_.Code.from_asset(path.join(__dirname,"lambda-handler")),architecture=architecture)You may want to test this stack under different conditions. For example, we want
this stack to be deployed correctly, regardless of the architecture we choose
for the Lambda function. In particular, it should work for bothARM_64andX86_64. So you can create anIntegTestCasethat exercises both scenarios:classStackUnderTest(Stack):def__init__(self,scope,id,*,architecture=None,description=None,env=None,stackName=None,tags=None,synthesizer=None,terminationProtection=None,analyticsReporting=None,crossRegionReferences=None,permissionsBoundary=None,suppressTemplateIndentation=None):super().__init__(scope,id,architecture=architecture,description=description,env=env,stackName=stackName,tags=tags,synthesizer=synthesizer,terminationProtection=terminationProtection,analyticsReporting=analyticsReporting,crossRegionReferences=crossRegionReferences,permissionsBoundary=permissionsBoundary,suppressTemplateIndentation=suppressTemplateIndentation)lambda_.Function(self,"Handler",runtime=lambda_.Runtime.NODEJS_LATEST,handler="index.handler",code=lambda_.Code.from_asset(path.join(__dirname,"lambda-handler")),architecture=architecture)# Beginning of the test suiteapp=App()IntegTest(app,"DifferentArchitectures",test_cases=[StackUnderTest(app,"Stack1",architecture=lambda_.Architecture.ARM_64),StackUnderTest(app,"Stack2",architecture=lambda_.Architecture.X86_64)])This is all the instruction you need for the integration test runner to know
which stacks to synthesize, deploy and destroy. But you may also need to
customize the behavior of the runner by changing its parameters. For example:app=App()stack_under_test=Stack(app,"StackUnderTest")stack=Stack(app,"stack")test_case=IntegTest(app,"CustomizedDeploymentWorkflow",test_cases=[stack_under_test],diff_assets=True,stack_update_workflow=True,cdk_command_options=CdkCommands(deploy=DeployCommand(args=DeployOptions(require_approval=RequireApproval.NEVER,json=True)),destroy=DestroyCommand(args=DestroyOptions(force=True))))IntegTestCaseStackIn the majority of cases an integration test will contain a singleIntegTestCase.
By default when you create anIntegTestanIntegTestCaseis created for you
and all of your test cases are registered to thisIntegTestCase. TheIntegTestCaseandIntegTestCaseStackconstructs are only needed when it is necessary to
defined different options for individual test cases.For example, you might want to have one test case wherediffAssetsis enabled.# app: App# stack_under_test: Stacktest_case_with_assets=IntegTestCaseStack(app,"TestCaseAssets",diff_assets=True)IntegTest(app,"Integ",test_cases=[stack_under_test,test_case_with_assets])AssertionsThis library also provides a utility to make assertions against the infrastructure that the integration test deploys.There are two main scenarios in which assertions are created.Part of an integration test usinginteg-runnerIn this case you would create an integration test using theIntegTestconstruct and then make assertions using theassertproperty.
You shouldnotutilize the assertion constructs directly, but should instead use themethodsonIntegTest.assertions.# app: App# stack: Stackinteg=IntegTest(app,"Integ",test_cases=[stack])integ.assertions.aws_api_call("S3","getObject")By default an assertions stack is automatically generated for you. You may however provide your own stack to use.# app: App# stack: Stack# assertion_stack: Stackinteg=IntegTest(app,"Integ",test_cases=[stack],assertion_stack=assertion_stack)integ.assertions.aws_api_call("S3","getObject")Part of a  normal CDK deploymentIn this case you may be using assertions as part of a normal CDK deployment in order to make an assertion on the infrastructure
before the deployment is considered successful. In this case you can utilize the assertions constructs directly.# my_app_stack: StackAwsApiCall(my_app_stack,"GetObject",service="S3",api="getObject")DeployAssertAssertions are created by using theDeployAssertconstruct. This construct creates it's ownStackseparate from
any stacks that you create as part of your integration tests. ThisStackis treated differently from other stacks
by theinteg-runnertool. For example, this stack will not be diffed by theinteg-runner.DeployAssertalso provides utilities to register your own assertions.# my_custom_resource: CustomResource# stack: Stack# app: Appinteg=IntegTest(app,"Integ",test_cases=[stack])integ.assertions.expect("CustomAssertion",ExpectedResult.object_like({"foo":"bar"}),ActualResult.from_custom_resource(my_custom_resource,"data"))In the above example an assertion is created that will trigger a user definedCustomResourceand assert that thedataattribute is equal to{ foo: 'bar' }.API CallsA common method to retrieve the "actual" results to compare with what is expected is to make an
API call to receive some data. This library does this by utilizing CloudFormation custom resources
which means that CloudFormation will call out to a Lambda Function which will
make the API call.HttpApiCallUsing theHttpApiCallwill use thenode-fetchJavaScript library to
make the HTTP call.This can be done by using the class directory (in the case of a normal deployment):# stack: StackHttpApiCall(stack,"MyAsssertion",url="https://example-api.com/abc")Or by using thehttpApiCallmethod onDeployAssert(when writing integration tests):# app: App# stack: Stackinteg=IntegTest(app,"Integ",test_cases=[stack])integ.assertions.http_api_call("https://example-api.com/abc")AwsApiCallUsing theAwsApiCallconstruct will use the AWS JavaScript SDK to make the API call.This can be done by using the class directory (in the case of a normal deployment):# stack: StackAwsApiCall(stack,"MyAssertion",service="SQS",api="receiveMessage",parameters={"QueueUrl":"url"})Or by using theawsApiCallmethod onDeployAssert(when writing integration tests):# app: App# stack: Stackinteg=IntegTest(app,"Integ",test_cases=[stack])integ.assertions.aws_api_call("SQS","receiveMessage",{"QueueUrl":"url"})You must specify theserviceand theapiwhen using TheAwsApiCallconstruct.
Theserviceis the name of an AWS service, in one of the following forms:An AWS SDK for JavaScript v3 package name (@aws-sdk/client-api-gateway)An AWS SDK for JavaScript v3 client name (api-gateway)An AWS SDK for JavaScript v2 constructor name (APIGateway)A lowercase AWS SDK for JavaScript v2 constructor name (apigateway)Theapiis the name of an AWS API call, in one of the following forms:An API call name as found in the API Reference documentation (GetObject)The API call name starting with a lowercase letter (getObject)The AWS SDK for JavaScript v3 command class name (GetObjectCommand)By default, theAwsApiCallconstruct will automatically add the correct IAM policies
to allow the Lambda function to make the API call. It does this based on theserviceandapithat is provided. In the above example the service isSQSand the api isreceiveMessageso it will create a policy withAction: 'sqs:ReceiveMessage.There are some cases where the permissions do not exactly match the service/api call, for
example the S3listObjectsV2api. In these cases it is possible to add the correct policy
by accessing theproviderobject.# app: App# stack: Stack# integ: IntegTestapi_call=integ.assertions.aws_api_call("S3","listObjectsV2",{"Bucket":"mybucket"})api_call.provider.add_to_role_policy({"Effect":"Allow","Action":["s3:GetObject","s3:ListBucket"],"Resource":["*"]})Note that addToRolePolicy() uses direct IAM JSON policy blobs, not a iam.PolicyStatement
object like you will see in the rest of the CDK.EqualsAssertionThis library currently provides the ability to assert that two values are equal
to one another by utilizing theEqualsAssertionclass. This utilizes a Lambda
backedCustomResourcewhich in tern uses theMatchutility from the@aws-cdk/assertionslibrary.# app: App# stack: Stack# queue: sqs.Queue# fn: lambda.IFunctioninteg=IntegTest(app,"Integ",test_cases=[stack])integ.assertions.invoke_function(function_name=fn.function_name,invocation_type=InvocationType.EVENT,payload=JSON.stringify({"status":"OK"}))message=integ.assertions.aws_api_call("SQS","receiveMessage",{"QueueUrl":queue.queue_url,"WaitTimeSeconds":20})message.assert_at_path("Messages.0.Body",ExpectedResult.object_like({"request_context":{"condition":"Success"},"request_payload":{"status":"OK"},"response_context":{"status_code":200},"response_payload":"success"}))Matchinteg-testsalso provides aMatchutility similar to the@aws-cdk/assertionsmodule.Matchcan be used to construct theExpectedResult. While the utility is similar, only a subset of methods are currently available on theMatchutility of this module:arrayWith,objectLike,stringLikeRegexpandserializedJson.# message: AwsApiCallmessage.expect(ExpectedResult.object_like({"Messages":Match.array_with([{"Payload":Match.serialized_json({"key":"value"})},{"Body":{"Values":Match.array_with([{"Asdf":3}]),"Message":Match.string_like_regexp("message")}}])}))ExamplesInvoke a Lambda FunctionIn this example there is a Lambda Function that is invoked and
we assert that the payload that is returned is equal to '200'.# lambda_function: lambda.IFunction# app: Appstack=Stack(app,"cdk-integ-lambda-bundling")integ=IntegTest(app,"IntegTest",test_cases=[stack])invoke=integ.assertions.invoke_function(function_name=lambda_function.function_name)invoke.expect(ExpectedResult.object_like({"Payload":"200"}))Make an AWS API CallIn this example there is a StepFunctions state machine that is executed
and then we assert that the result of the execution is successful.# app: App# stack: Stack# sm: IStateMachinetest_case=IntegTest(app,"IntegTest",test_cases=[stack])# Start an executionstart=test_case.assertions.aws_api_call("StepFunctions","startExecution",{"state_machine_arn":sm.state_machine_arn})# describe the results of the executiondescribe=test_case.assertions.aws_api_call("StepFunctions","describeExecution",{"execution_arn":start.get_att_string("executionArn")})# assert the resultsdescribe.expect(ExpectedResult.object_like({"status":"SUCCEEDED"}))Chain ApiCallsSometimes it may be necessary to chain API Calls. Since each API call is its own resource, all you
need to do is add a dependency between the calls. There is an helper methodnextthat can be used.# integ: IntegTestinteg.assertions.aws_api_call("S3","putObject",{"Bucket":"my-bucket","Key":"my-key","Body":"helloWorld"}).next(integ.assertions.aws_api_call("S3","getObject",{"Bucket":"my-bucket","Key":"my-key"}))Wait for resultsA common use case when performing assertions is to wait for a condition to pass. Sometimes the thing
that you are asserting against is not done provisioning by the time the assertion runs. In these
cases it is possible to run the assertion asynchronously by calling thewaitForAssertions()method.Taking the example above of executing a StepFunctions state machine, depending on the complexity of
the state machine, it might take a while for it to complete.# app: App# stack: Stack# sm: IStateMachinetest_case=IntegTest(app,"IntegTest",test_cases=[stack])# Start an executionstart=test_case.assertions.aws_api_call("StepFunctions","startExecution",{"state_machine_arn":sm.state_machine_arn})# describe the results of the executiondescribe=test_case.assertions.aws_api_call("StepFunctions","describeExecution",{"execution_arn":start.get_att_string("executionArn")}).expect(ExpectedResult.object_like({"status":"SUCCEEDED"})).wait_for_assertions()When you callwaitForAssertions()the assertion provider will continuously make theawsApiCalluntil theExpectedResultis met. You can also control the parameters for waiting, for example:# test_case: IntegTest# start: IApiCalldescribe=test_case.assertions.aws_api_call("StepFunctions","describeExecution",{"execution_arn":start.get_att_string("executionArn")}).expect(ExpectedResult.object_like({"status":"SUCCEEDED"})).wait_for_assertions(total_timeout=Duration.minutes(5),interval=Duration.seconds(15),backoff_rate=3)