DEV Community

Cover image for Python AWS Lambda unit testing

Posted on • Updated on

Python AWS Lambda unit testing

Unit testing computational AWS Lambda

Consider a lambda handler retrieving two values from an event and returns the sum. (no interaction with other AWS Services).

def lambda_handler(event, context):
    result = int(event['first_number']) + int(event['second_number'])  
    return { 
        'sum' : result
Enter fullscreen mode Exit fullscreen mode

Below is one option of unit testing using Python "unittest"

import unittest
import index
class TestSumOfTwoNumbers(unittest.TestCase):
    def test_sum(self):
        input = {
            "first_number": "1",
            "second_number": "2"
        output = index.lambda_handler(input,{})
        self.assertEqual(3, output['sum'])
Enter fullscreen mode Exit fullscreen mode

Unit testing AWS Lambda interacting with other AWS Services/APIs

The handler code given below calling AWS Service API (get_function() of boto3 lambda client) fetching a lambda functions metadata.

import boto3

def lambda_handler(event, context):
    lambda_client = boto3.client('lambda')
    response = lambda_client.get_function(
    return response
Enter fullscreen mode Exit fullscreen mode

Below code shows how we performed Unit testing boto3 calls using Stubber. (Go through the in-line comments for brief explanation)

import boto3
from botocore.stub import Stubber
import index # source file
import unittest
from unittest.mock import patch

class TestLambdaMetadata(unittest.TestCase):
    def tests_Metadata_for_lambda_function(self):
        client = boto3.client('lambda')
        stubber = Stubber(client) # stubbed lambda client

        # expected response from boto3 lambda client's get_function call 
        expected_response = {u"Configuration": {"FunctionName": "for-blog", "Runtime": "python3.8"}}

        # stubbed lambda client (with specific parameter) call to get_function results in expected_response. 
        stubber.add_response('get_function', expected_response, {'FunctionName': 'for-blog'})

        # patching boto3 attribute of with stubber
        with patch('index.boto3') as mock_boto3:
            with stubber:
                mock_boto3.client.return_value = client

                # call to lambda_handler in 
                lambda_response = index.lambda_handler({}, 'context')
                self.assertEqual(lambda_response, expected_response)
Enter fullscreen mode Exit fullscreen mode

Image by Gerd Altmann from Pixabay

Top comments (0)