【发布时间】:2021-12-04 02:14:47
【问题描述】:
我有一个具有以下文件夹结构的 AWS SAM 项目:
account/
__init__.py
layers/
__init__.py
config/
settings.py
utils/
logger.py
get_accounts/
app.py
requirements.txt
tests/
requirements.txt
integration/
test_api_gateway.py
unit/
test_handler.py
当我从项目根目录运行python3 -m pytest tests/unit/ 时,出现以下错误:
导入测试模块时出现ImportError '/Users/johnsmith/dev/myproject/account/tests/unit/test_handler.py'。暗示: 确保您的测试模块/包具有有效的 Python 名称。
追溯: /usr/local/Cellar/python@3.9/3.9.7/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/init.py:127: 在 import_module return _bootstrap._gcd_import(name[level:], package, level) tests/unit/test_handler.py:3: in 从 get_accounts 导入应用程序 get_accounts/app.py:14: 在 从 layers.utils.logger 导入 get_logger 层/utils/logger.py:1:在 from config.settings import ApplicationConfig E ModuleNotFoundError: No module named 'config'
问题是当测试文件导入主应用程序时,主应用程序的依赖项位于“layers”文件夹中;由于某种原因,它无法导入这些文件。当我使用sam local 命令启动应用程序时,它可以工作,但是当我运行 pytest 时它会失败。
我试过了
- 将
__init__.py添加到“layers”文件夹下的所有文件夹中。 - 创建 setup.py 并指定“config”作为包名,然后运行
pip install -e .based on pytest's documentation - 在
get_accounts/app.py中,在导入这些项目时在config.settings和utils.logger之前指定“层” - 从测试文件夹中删除
__init__.py
这些都是 stackoverflow 中提到的所有可能的解决方案,但没有一个对我有用。
get_accounts/app.py 中的导入如下所示:
import json
import requests
from config.settings import ApplicationConfig
from utils.logger import get_logger
from pprint import pprint
有人对我做错了什么以及如何让它发挥作用有任何想法吗?
【问题讨论】:
标签: python python-module