python
module_error
ai_generated
true
ModuleNotFoundError: No module named 'myapp'
ID: python/pytest-import-mode-src-not-found
80%Fix Rate
87%Confidence
0Evidence
2024-05-21First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 7.x | active | — | — | — |
| 8.x | active | — | — | — |
Root Cause
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.
generic中文
pytest 默认 import 模式(prepend)将测试目录插入 sys.path,而非项目根目录。src/ 布局的包在未安装或未配置路径时无法从 tests 导入。
Workarounds
-
95% success
pip install -e . # or with pyproject.toml [build-system] set, uv pip install -e .
-
90% success
# pyproject.toml [tool.pytest.ini_options] pythonpath = ["src"] addopts = "--import-mode=importlib"
Dead Ends
Common approaches that don't work:
-
70% fail
Relative paths break depending on CWD; also pollutes sys.path and hides packaging issues.
-
60% fail
Works locally but isn't reproducible in CI; pytest may still use prepend mode and shadow the path.