Testing Lambdas locally with aws-sam-cli

Benefits of AWS SAM CLI

SAM stands for AWS Serverless Application Model, it is an open-source framework that you can use to build serverless applications on AWS.

AWS SAM Consists of the following components

AWS SAM template specification. This defines your serverless application. It is used to describe the functions, APIs, permissions, configurations, and events that make up a serverless application. You use an AWS SAM template file to operate on a single, deployable, versioned entity that’s your serverless application. See AWS Serverless Application Model Specification.

AWS SAM command line interface (AWS SAM CLI). This tool is used to build serverless applications defined by the AWS SAM templates. The CLI provides commands that enable you to verify your templates and to invoke and debug Lambda functions locally. You can also deploy serverless applications to the AWS Cloud via CloudFormation. See AWS SAM CLI.

Invoking Function with event file

Invoking Function with event file via stdin

Invoking Function Output

Running API Gateway Locally

Use the sam local start-api command to start a local instance of API Gateway that you will use to test HTTP request/response functionality. This functionality features hot reloading to enable you to quickly develop and iterate over your functions.

sam local start-api

Image by AWS

Emulate AWS Lambda invoke endpoint (Automated Tests)

sam local start-lambda

This command starts a local endpoint at http://127.0.0.1:3001 that emulates AWS Lambda. You can run your automated tests against this local Lambda endpoint. When you invoke this endpoint using the AWS CLI or SDK, it locally executes the Lambda function that’s specified in the request, and returns a response.

Debugging Lambda Functions Locally

Both commands sam local invoke and sam local start-api support local step-through debugging. You must specify --debug-port or -d on the command line.