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

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

## 根因

pytest 在特定配置下（例如测试目录中没有 __init__.py 或 rootdir 设置错误）默认不会将项目根目录添加到 sys.path。测试文件中的相对导入因此失败。

## 版本兼容性

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

## 解决方案

1. **** (93% 成功率)
   ```
   # pytest.ini
[pytest]
pythonpath = .

# Or in pyproject.toml:
# [tool.pytest.ini_options]
# pythonpath = ["."]
   ```
2. **** (88% 成功率)
   ```
   pip install -e .
# Then absolute imports work from anywhere
   ```

## 无效尝试

- **** — The current working directory may not be the project root when pytest is invoked from a different location. This is fragile and non-portable. (75% 失败率)
- **** — This may work locally but breaks when the package is installed or when tests are run from a different directory. It also violates package structure conventions. (65% 失败率)
