python
module_error
ai_generated
true
ERROR collecting tests/test_app.py ImportError: attempted relative import with no known parent package
ID: python/pytest-collection-import-mismatch
80%Fix Rate
88%Confidence
0Evidence
2024-05-19First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 7.x | active | — | — | — |
| 8.x | active | — | — | — |
Root Cause
Pytest uses rootdir-based import modes. If `tests/` lacks an `__init__.py` and the test uses a relative import like `from .helpers import x`, Python cannot resolve the parent package.
generic中文
pytest 使用基于 rootdir 的导入模式。如果 `tests/` 目录缺少 `__init__.py`,而测试中使用了 `from .helpers import x` 这类相对导入,Python 就无法解析父包。
Workarounds
-
90% success
Add an empty `__init__.py` to the tests directory so it becomes a package: touch tests/__init__.py
-
90% success
Switch to absolute imports and set rootdir on sys.path via pyproject: # pyproject.toml [tool.pytest.ini_options] pythonpath = ["."] # test file from tests.helpers import make_client
Dead Ends
Common approaches that don't work:
-
85% fail
Relative imports are resolved by Python's import machinery, not sys.path; adding the path does not create a parent package.
-
70% fail
Changes rootdir and breaks other tests; the relative import still fails because there is still no package.