Search code examples
pythonpytestfixturespytest-mock

Pytest lambda handler passing event and context


I am writing a unit test for my lambda function using pytest. I cannot figure out how should I pass my event parameters to the function call. I learnt that it can be achieved using @pytest.fixture. I am very very new to Python and pytest. Believe I am using fixures in the wrong way. Please help me!!

Below is my lambda handler:

lambda_service.py

def lambda_handler(event, context):   
    logger.info('Event received: ' + json.dumps(event))
    try:
        sort = (event['sort'])
        size = int(event['size'])
        page = int(event['page'])

        list_response = MyService().get_people_list(sort, size, page)
        logger.info(list_response)

    except Exception as e:
        logger.error("Unable to fetch details")
        logger.exception(e)

    return list_response

This is my test class-

class TestServiceHandler:
    @pytest.fixture
    def event(self):
        return {
            "sort": "asc",
            "size": 5,
            "page": 0
        }
    @pytest.fixture
    def context(self):
        return None

    def test_lambda_handler(self):
        result = lambda_service.lambda_handler(self.event, self.context)
        assert_valid_schema(result, 'vendor_list.json')

And I am getting below error when running this test

line 17, in lambda_handler
sort = (event['sort'])\nTypeError: 'method' object is not subscriptable"

Though I am passing event and context in fixtures, it is still referring to event[sort] inside lambda_handler.


Solution

  • You've defined the fixtures correctly, but using them wrong. To fix, add arguments to the test_lambda_handler method named exactly as the fixtures. When running tests, pytest will analyze each argument and insert the fixture return value if it can find a fixture with that name. Example:

    class TestServiceHandler:
        @pytest.fixture
        def event(self):
            ...
        @pytest.fixture
        def context(self):
            ...
    
        def test_lambda_handler(self, event, context):
            result = lambda_service.lambda_handler(event, context)
            assert ...