life is too short for a diary

Unit Test AWS Lambda Function in Python

Tags: aws python

Project Structure

└── test
    └── are empty files that mark the directories as python package so that they can be imported.

We will create a simple that simply returns id as response.

We have a test corresponding to the test file MyLambda/test/

We will use pytest to run our test:

$ pytest -v -s --cov=.
MyLambda/test/ PASSED

--------- coverage: platform darwin, python 3.10.10-final-0 ----------
Name                                                   Stmts   Miss  Cover
MyLambda/                                       0      0   100%
MyLambda/                                4      0   100%
MyLambda/test/                                  0      0   100%
MyLambda/test/       7      0   100%
TOTAL                                                     11      0   100%

Using patch

As our lambda function gets complex, we must explore additional functionality to test our lambda function. We can use patch to mock resources like environment variables, etc

Our updated test becomes

Pytest fixtures

A fixture is a function that returns a test resource to supply a mock context object to our lambda function. Let's rewrite our test function

In our example, we define a event fixture that return dictionary. We then pass this fixture as an argument to our test function.

comments powered by Disqus