最近我在工作项目中添加了一个Lambda层,虽然在几乎所有方面都取得了巨大的成功,但现在我在运行测试时遇到了问题。以下是我的简化目录结构:
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)
所有的功能都很好用。在我运行sam build之后,我可以本地运行和触发hw_handler,然后也可以部署并触发它,一切都没有问题。但当我运行pytest并触发test_hello_world.py时,问题就出现了。我会收到以下错误信息:
(Traceback)
src/hello_world/hello_world.py:1: in <module>
ImportError: cannot import name 'db_conn' from 'dependencies' (unknown location)
因此,错误在于当pytest导入要测试的lambda时,它无法从已导入的lambda中导入来自我的lambda层的函数。显然,pytest找不到我的依赖文件夹,所以我的问题是,将Lambda层合并到我的pytest代码中的最佳方法是什么?