python
module_error
ai_generated
true
ModuleNotFoundError: 没有名为 'myapp' 的模块
ModuleNotFoundError: No module named 'myapp'
ID: python/pytest-import-mode-src-not-found
80%修复率
87%置信度
0证据数
2024-05-21首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 7.x | active | — | — | — |
| 8.x | active | — | — | — |
根因分析
pytest 默认 import 模式(prepend)将测试目录插入 sys.path,而非项目根目录。src/ 布局的包在未安装或未配置路径时无法从 tests 导入。
English
pytest's default import mode (prepend) inserts test directories into sys.path, not the project root. A src/ layout package isn't importable from tests without installation or path configuration.
解决方案
-
95% 成功率
pip install -e . # or with pyproject.toml [build-system] set, uv pip install -e .
-
90% 成功率
# pyproject.toml [tool.pytest.ini_options] pythonpath = ["src"] addopts = "--import-mode=importlib"
无效尝试
常见但无效的做法:
-
70% 失败
Relative paths break depending on CWD; also pollutes sys.path and hides packaging issues.
-
60% 失败
Works locally but isn't reproducible in CI; pytest may still use prepend mode and shadow the path.