运行poetry run pytest时遇web_app模块NotFoundError求助
问题:FastAPI项目pytest执行时出现ModuleNotFoundError
我在学习《Scalable FastAPI on AWS》课程时,执行以下命令:
talk-booking/services/talk_booking $ poetry run pytest tests/integration
出现如下错误:
=============================================== test session starts ================================================ platform darwin -- Python 3.11.1, pytest-6.2.5, py-1.11.0, pluggy-1.0.0 rootdir: /Users/blarblar/Workspace/talk-booking/services/talk_booking plugins: cov-4.0.0, anyio-3.6.2 collected 1 item / 1 error ====================================================== ERRORS ====================================================== ___________________________ ERROR collecting tests/integration/test_web_app/test_main.py ___________________________ ImportError while importing test module '/Users/blarblar/Workspace/talk-booking/services/talk_booking/tests/integration/test_web_app/test_main.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/Cellar/python@3.11/3.11.1/Frameworks/Python.framework/Versions/3.11/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/integration/test_web_app/test_main.py:4: in <module> from web_app.main import app E ModuleNotFoundError: No module named 'web_app' ============================================= short test summary info ============================================== ERROR tests/integration/test_web_app/test_main.py !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ================================================= 1 error in 0.29s =================================================
我的目录结构如下:
. ├── README.md └── services └── talk_booking ├── poetry.lock ├── pyproject.toml ├── tests │ ├── __init__.py │ └── integration │ └── test_web_app │ ├── __init__.py │ └── test_main.py └── web_app ├── __init__.py └── main.py
健康检查API(127.0.0.1:8000)运行正常,直接在main.py中编写测试代码也能正常工作,请问如何解决该模块导入问题?
解决方案
方法1:临时添加项目路径到Python环境变量
在talk-booking/services/talk_booking目录下,先将当前路径加入PYTHONPATH,再执行pytest:
export PYTHONPATH=$PWD poetry run pytest tests/integration
方法2:通过Poetry配置将web_app设为可导入包
修改pyproject.toml文件,添加packages配置项,让Poetry识别web_app作为项目的一部分:
[tool.poetry] # 保留原有配置,新增以下内容 packages = [ { include = "web_app" } ]
执行poetry install重新安装依赖后,再运行pytest命令即可。
方法3:修改测试文件为相对导入
调整tests/integration/test_web_app/test_main.py中的导入语句为相对路径:
from ...web_app.main import app
注意:此方法依赖测试目录为合法Python包(已存在__init__.py),但相对导入在部分pytest场景下可能需要额外配置,优先推荐前两种方法。
内容的提问来源于stack exchange,提问作者jc Jang
相关产品推荐
相关产品推荐

