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

- **ID:** `python/pytest-collection-import-mismatch`
- **领域:** python
- **类别:** module_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

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

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 7.x | active | — | — |
| 8.x | active | — | — |

## 解决方案

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
   ```

## 无效尝试

- **** — Relative imports are resolved by Python's import machinery, not sys.path; adding the path does not create a parent package. (85% 失败率)
- **** — Changes rootdir and breaks other tests; the relative import still fails because there is still no package. (70% 失败率)
