[英]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.我最近在我的一个工作项目中添加了一个 Lambda 层,虽然它在几乎所有方面都取得了巨大的成功,但我现在在运行测试时遇到了问题。 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:依赖项.py:
import boto3
def db_conn():
db = boto3.resource("dynamodb")
return db
hello_world.py你好世界.py
from dependencies import db_conn
def hw_handler():
(unimportant functionality)
test_hello_world.py 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.
运行 sam build 后,我可以在本地运行并触发 hw_handler,然后部署并触发它,一切都没有问题。 The trouble arises when I run pytest and test_hello_world.py gets triggered.
当我运行 pytest 并触发 test_hello_world.py 时,问题就出现了。 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?所以错误是当 pytest 导入 lambda 进行测试时,它无法从我的 lambda 层中导入 lambda 中的 function。显然 pytest 无法找到合并我的依赖项的最佳方式,所以我的问题是什么Lambda层变成我的pytest码?
Inside your __init__.py
for the root directory of your folder which contains tests to the lambda layer add another path.在你的
__init__.py
文件夹的根目录中,其中包含对 lambda 层的测试,添加另一个路径。
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")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.