Testing integration configuration – Testing Serverless Applications

Testing integration configuration

In our example architecture, you are responsible for the configuration of the custom EventBridge event bus and the EventBridge rule, which includes the event pattern and the target.

Using an IaC framework such as the AWS Cloud Development Kit allows you to make assertions about the resources in the underlying CloudFormation template.

This example demonstrates a strategy for testing EventBridge event patterns to ensure the rule will match events as expected:

import { Capture, Template } from “aws-cdk-lib/assertions”; import { EventBridgeClient, TestEventPatternCommand } from

“@aws-sdk/client-eventbridge”;

import OrderCreated from “./schema/[email protected]”;

const eventbridge = new EventBridgeClient({});

test(“OrderCreated rule event pattern matches OrderCreated events”, async () => { const eventPatternCapture = new Capture();

template.hasResourceProperties(“AWS::Events::Rule”, { EventPattern: eventPatternCapture,

});

const testOrderCreatedPatternCommand = new TestEventPatternCommand({ Event: JSON.stringify({

account: stack.account,

“detail-type”: OrderCreated[“x-amazon-events-detail-type”],

source: OrderCreated[“x-amazon-events-source”],

time: new Date(),

region: stack.region,

}),

EventPattern: JSON.stringify(eventPatternCapture.asObject()), });

const testOrderCreatedPattern = await eventbridge.send( testOrderCreatedPatternCommand

);

expect(testOrderCreatedPattern.Result).toEqual(true); });

Testing integration permissions

In the example architecture, you are responsible for applying the necessary permis‐ sions for the event producer function to put events on the event bus and the rule to invoke the target function:

test(“EventProducer function has permission to put events on OrdersBus”, () => { template.hasResourceProperties(“AWS::IAM::Policy”, {

PolicyDocument: {

Statement: [

{

Action: “events:PutEvents”,

Effect: “Allow”,

Resource: {

“Fn::GetAtt”: [getLogicalId(stack, stack.eventBus), “Arn”],

},

},

],

Version: “2012-10-17”,

},

Roles: [

{

Ref: getLogicalId(stack, stack.eventProducer.role),

},

],

});

});

test(“OrderCreated rule has permission to invoke EventConsumer function”, () => { template.hasResourceProperties(“AWS::Lambda::Permission”, {

Action: “lambda:InvokeFunction”,

FunctionName: {

“Fn::GetAtt”: [getLogicalId(stack, stack.eventConsumer), “Arn”],

},

SourceArn: {

“Fn::GetAtt”: [getLogicalId(stack, stack.orderCreatedRule), “Arn”],

},

});

});

Leave a Reply

Your email address will not be published. Required fields are marked *