python module_error ai_generated true

收集 tests/test_app.py 时出错 ImportError: 尝试相对导入,但没有已知的父包

ERROR collecting tests/test_app.py ImportError: attempted relative import with no known parent package

ID: python/pytest-collection-import-mismatch

其他格式: JSON · Markdown 中文 · English
80%修复率
88%置信度
0证据数
2024-05-19首次发现

版本兼容性

版本状态引入弃用备注
7.x active — — —
8.x active — — —

根因分析

pytest 使用基于 rootdir 的导入模式。如果 `tests/` 目录缺少 `__init__.py`,而测试中使用了 `from .helpers import x` 这类相对导入,Python 就无法解析父包。

English

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

解决方案

  1. 90% 成功率
    Add an empty `__init__.py` to the tests directory so it becomes a package:
    
    touch tests/__init__.py
  2. 90% 成功率
    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

无效尝试

常见但无效的做法:

  1. 85% 失败

    Relative imports are resolved by Python's import machinery, not sys.path; adding the path does not create a parent package.

  2. 70% 失败

    Changes rootdir and breaks other tests; the relative import still fails because there is still no package.