# ImportError: 尝试相对导入但没有已知的父包

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

## 根因

测试模块使用了相对导入（from .foo import bar），但测试目录缺少 __init__.py，pytest 会将测试文件作为顶层模块导入，从而失去包上下文，导致相对导入失败。

## 版本兼容性

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

## 解决方案

1. **** (92% 成功率)
   ```
   touch tests/__init__.py
touch tests/unit/__init__.py
# then run from project root
pytest tests/
   ```
2. **** (95% 成功率)
   ```
   # before: from .helpers import make_user
# after:
from tests.helpers import make_user
   ```
3. **** (85% 成功率)
   ```
   # pyproject.toml
[tool.pytest.ini_options]
addopts = "--import-mode=importlib"
   ```

## 无效尝试

- **** — Path insertion does not create a parent package; relative imports still fail because __package__ is empty. (80% 失败率)
- **** — Changes rootdir discovery but does not fix the missing package marker; the relative import still has no parent. (75% 失败率)
