'Pytest cannot find function defined in Lambda Layer
I recently added a Lambda Layer to one of my work projects and while it's been a huge success in almost every way, I'm having issues running my tests now. This is my trimmed down directory structure:
root
- dependencies-layer
- python
- __init__.py
- boto3
- (list of other modules)
- dependencies.py
- requirements.txt
- src
- hello_world
- __init__.py
- hello_world.py
- requirements.txt
- tests
- hello_world
- unit
- test_hello_world.py
- pytest.ini
- template.yaml
dependencies.py:
import boto3
def db_conn():
db = boto3.resource("dynamodb")
return db
hello_world.py
from dependencies import db_conn
def hw_handler():
(unimportant functionality)
test_hello_world.py
from src.hello_world import hello_world
(unimportant unit tests)
All of the functionality works great. After I run sam build, I can run and trigger the hw_handler locally and then deploy and trigger it as well, all with no issues. The trouble arises when I run pytest and test_hello_world.py gets triggered. I get the following error:
(Traceback)
src/hello_world/hello_world.py:1: in <module>
ImportError: cannot import name 'db_conn' from 'dependencies' (unknown location)
So the error is that when pytest imports the lambda to test, it can't import the function from my lambda layer within that imported lambda. Obviously pytest can't find my dependencies folder so my question is, what's the best way to incorporate a Lambda Layer into my pytest code?
Solution 1:[1]
Inside your __init__.py
for the root directory of your folder which contains tests to the lambda layer add another path.
See Below - Find the current directory and file's directory
I ended up doing the following to get my tests running:
import sys, os
dir_path = os.path.dirname(os.path.realpath(__file__))
sys.path.append(dir_path + "/../../hubspot_cdk/code/layers/hubspotDeps/python")
sys.path.append(dir_path + "/../../hubspot_cdk/code/layers/hubspotUtils/python")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Zachariah Cavazos |