Blog

AWS Lambda unit testing with Python

10 Nov, 2018
Xebia Background Header Wave

A Lambda function should be tested before being deployed to AWS. Python makes it easy to test your lambda function with
the pytest library. In this blog we will show you how to test your lambda functions.

Testing

Testing code is a great way to determine whether units of code are fit for use. By invoking code and asserting the result
you get a general idea how to code is performing, functional wise.

Project setup

The example project has the following structure. The
lambdas are placed in the lambdas folder and the test files are placed in the tests folder. Notice that both
the lambdas and tests folder contain the dunder-init files <strong>init</strong>.py. This file is necessary so that Python can
resolve packages. The tests for the lambda lambdas/python_function.py is called tests/test_python_function.py.
Tests can be executed by typing pipenv run pytest -v -s tests which will execute all tests.

├── LICENSE
├── Makefile
├── Pipfile
├── README.md
├── config
│   ├── config.yaml
│   └── inlined
│       └── api-gateway.yaml
├── lambdas
│   ├── __init__.py
│   └── python_function.py
├── templates
│   └── api-gateway.yaml
└── tests
    ├── __init__.py
    └── test_python_function.py

An example test

The file tests/test_python_function.py contains a single test that asserts the response of the lambda. The function
called handler is first imported in the symbol table. There is a single test called test_python_function() that
asserts the response of the lambda when it is invoked. The response conforms to a correct ApiGatewayProxyResponse data structure.

from lambdas.python_function import *
from tests import *

def test_python_function():
    resp = handler(api_gateway_event({}), None)
    assert resp == {‘statusCode‘: 200, ‘body‘: ‘“Hello Python“‘}

Testing, merging and deploying

The example project shows how to build, merge and deploy
a lambda to AWS. The project makes use of inlined lambdas and is explained in my previous blog
AWS Lambda Inlined in CloudFormation.
I assume you have a mac with python, pipenv, sceptre installed. To test, merge and deploy the example type make deploy.
To get the url of the api gateway, type make info. To remove the example type make delete.

Conclusion

Python makes it easy to test AWS Lambda code by means of the pytest library.
By invoking code and asserting the result you get a general idea how to code is performing, functional wise. I advice
testing all your Lambda code before deploying them to AWS.

Questions?

Get in touch with us to learn more about the subject and related solutions

Explore related posts