Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unit test lambda logic which uses layer methods?

Hi I have my AWS Lambda and I wanted to add a layer to it. I would like to be able to just test single methods of lambda. However many of them use layer logic and because of that it doesn't seem to me to be easy. What is the best approach to do this ?

One approach would be to package layer, host is somewhere and use it as dependency. In that case why even bother to use layers ?

The other idea I have is to deploy lambda locally with sam-cli. I know how to use it to test the whole lambda logic but I can't see how to unit test methods separately ;/ What are your experiences ? KR

EDIT. My solution

  • Add pytest

  • Place all the tests in test directory

  • Add test lambda handler which invokes tests

import pytest def lambda_handler(event, _): res = pytest.main(['-x', './tests']) return res

  • Add template.yml which points to previously created lambda handler

Resources: MyFunction: Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction Properties: CodeUri: src/ Handler: test.lambda_handler Runtime: python3.6 Events: MyInfo: Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api Properties: Path: /my-service/test Method: get Environment: Variables: ELASTICSEARCH_DOC_TYPE: "article" ELASTICSEARCH_INDEX: "artilces" ELASTICSEARCH_HOST: "elastic" ELASTICSEARCH_PORT: "9200" ELASTICSEARCH_URL: "http://my_elastic.com:9200" Layers: - arn:aws:lambda:eu-west-1:XXXXXXXXXXXXX:layer:lambda_layer:37

  • Run sam local invoke --no-event
like image 725
Clyde Barrow Avatar asked Feb 15 '19 08:02

Clyde Barrow


Video Answer


1 Answers

For my case, I was using the moto library to mock AWS Services so using sam local was not an option. I just added the path of my lambda layer to my sys path in my test files and it did the trick for me.

like image 69
Ghamgui Khaled Avatar answered Oct 11 '22 13:10

Ghamgui Khaled