I use pycharm to develop my lambdas locally. It turns out that by default the IDE doesn’t recognize the handler function to start, so I have to comment out the code whenever I test locally. And when it goes up to AWS, remove the comments and indent again. For example:
#Local testing
#def lambda_handler(event, context):
print(f"test")
while true:
print(f"test")
#Code formatted to run in the cloud
def lambda_handler(event, context):
print(f"test")
while true:
print(f"test")
It turns out that doing this always takes time and is error-prone. It has already happened to send the code that I tested locally to the cloud and vice versa.
Is there any way for pycharm to recognize the handler function and start the code from there?
2
Answers
This is what I do to test my Python Lambda functions locally:
When you run the script locally, it will detect it is not deployed on AWS, and trigger the handler function with some test context/event data. When you deploy this to AWS Lambda it will detect it is running on Lambda and do nothing, letting AWS to trigger the handler function.
The best practice for this is break lambda into some callable functions, separate the test script, and write some
shell scripts
to do the testing.Write a bash/powershell script and that will call run the test program(s) when you run the scripts only. The test code will import your lambda code and use it. That way you can pass event, context as arguments too.
This will also help you implement CI/CD pipeline, if the test script does not throw any errors it will continue deploying. This will eventually save your time.
Best wishes.