python
module_error
ai_generated
true
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
80%Fix Rate
90%Confidence
0Evidence
2024-01-08First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 7.x | active | — | — | — |
| 8.x | active | — | — | — |
Root Cause
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.
generic中文
pytest 运行时项目根目录不在 sys.path 上。当从项目根目录以外的目录调用测试,或者包未安装(pip install -e .)且项目根目录没有 conftest.py 来锚定 rootdir 时,就会发生这种情况。
Workarounds
-
97% success
pip install -e . pytest tests/
-
90% success
# project/conftest.py (empty is enough) touch conftest.py pytest tests/
-
93% success
# pyproject.toml [tool.pytest.ini_options] pythonpath = ["."]
Dead Ends
Common approaches that don't work:
-
80% fail
Depends on CWD at runtime; breaks in CI when pytest is invoked from a different directory, and pollutes each test file.
-
75% fail
Works interactively but not in CI or IDE test runners; teammates hit the same error.