ModuleNotFoundError:没有名为 'myapp' 的模块 文件 "/app/tests/test_api.py",第 3 行,在 <module> 中 from myapp.api import create_app
ModuleNotFoundError: No module named 'myapp' File "/app/tests/test_api.py", line 3, in <module> from myapp.api import create_app
ID: python/pytest-import-mode-sys-path
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 7.x | active | — | — | — |
| 8.x | active | — | — | — |
根因分析
pytest 运行时项目根目录不在 sys.path 上。当从项目根目录以外的目录调用测试,或者包未安装(pip install -e .)且项目根目录没有 conftest.py 来锚定 rootdir 时,就会发生这种情况。
English
The project root is not on sys.path when pytest runs. This happens when tests are invoked from a directory other than the project root, or when the package is not installed (pip install -e .) and there is no conftest.py at the project root to anchor rootdir.
解决方案
-
97% 成功率
pip install -e . pytest tests/
-
90% 成功率
# project/conftest.py (empty is enough) touch conftest.py pytest tests/
-
93% 成功率
# pyproject.toml [tool.pytest.ini_options] pythonpath = ["."]
无效尝试
常见但无效的做法:
-
80% 失败
Depends on CWD at runtime; breaks in CI when pytest is invoked from a different directory, and pollutes each test file.
-
75% 失败
Works interactively but not in CI or IDE test runners; teammates hit the same error.