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
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
sam local invoke --no-event
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With