Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unittest on AWS Lambda

I have a python script that I run on AWS. The script contains the lambda_handler(event, context) function that is called by AWS. Now, I'd like to create a new lambda function that acts as unit test. A typical unit test schema is defined as:

import unittest

def my_function(a):
    return a + 1

class Test(unittest.TestCase):

    def test_correct(self):
        self.assertEqual( my_function(1), 2)

if __name__ == '__main__':
    unittest.main()

In AWS, the lambda_handler(event, context) function is called. How can I make the unittest_lambda_handler(event, context) to perform the unit test?

So I am guessing my code (in the unit test script) should look like:

import main_lambda_function
import unittest

    def unittest_lambda_handler(event, context):
         #what should this function do?

    class MyTest(unittest.TestCase):
         def return_type(self,event, context):
            self.assertTrue(isinstance(main_lambda_function.lambda_handler(event, context),int))

Is this the correct approach?If so, what should unittest_lambda_handler do?

like image 282
Titus Pullo Avatar asked Jan 16 '18 17:01

Titus Pullo


2 Answers

Not sure how many people are aware that in most cases you don't even need a 3rd part library to stub boto3 calls. Botocore provides stubber out of the box Reference

This class will allow you to stub out requests so you don't have to hit an endpoint to write tests. Responses are returned first in, first out. If operations are called out of order, or are called with no remaining queued responses, an error will be raised.

like image 132
b.b3rn4rd Avatar answered Oct 17 '22 21:10

b.b3rn4rd


localstack may be of interest here.

LocalStack provides an easy-to-use test/mocking framework for developing Cloud applications. Currently, the focus is primarily on supporting the AWS cloud stack.

like image 26
Nathan Vērzemnieks Avatar answered Oct 17 '22 20:10

Nathan Vērzemnieks