python
module_error
ai_generated
true
ModuleNotFoundError: 没有名为 'myapp' 的模块
ModuleNotFoundError: No module named 'myapp'
ID: python/pytest-import-mismatch-module-not-found
80%修复率
90%置信度
0证据数
2024-02-01首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 7.x | active | — | — | — |
| 8.x | active | — | — | — |
根因分析
pytest 在项目根目录不在 sys.path 上的目录中运行。这通常发生在测试位于子目录且包未安装,或使用 src 布局但未正确配置时。
English
pytest is run from a directory where the project root is not on sys.path. This often happens when tests are in a subdirectory and the package is not installed, or when using src layout without proper configuration.
解决方案
-
90% 成功率
Create conftest.py in the project root (even empty). pytest adds the rootdir to sys.path when it finds conftest.py.
-
98% 成功率
Run: pip install -e . Ensure setup.py or pyproject.toml is present with proper package discovery.
-
95% 成功率
Run: python -m pytest tests/ This adds the current directory to sys.path.
无效尝试
常见但无效的做法:
-
70% 失败
The current working directory may not be the project root, and this is fragile.
-
80% 失败
This makes the parent directory not importable and often breaks relative imports.