# 收集 tests/test_api.py 时出错
导入测试模块时 ImportError。
ModuleNotFoundError: 没有名为 'myapp' 的模块

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

## 根因

pytest 仅在特定模式下将 rootdir 加入 sys.path。当从子目录运行 'pytest tests/' 或使用 src 布局时，包根目录不在 sys.path 上。

## 版本兼容性

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

## 解决方案

1. **** (95% 成功率)
   ```
   pip install -e .
# then run: pytest
   ```
2. **** (90% 成功率)
   ```
   # pytest.ini
[pytest]
pythonpath = src
   ```

## 无效尝试

- **** — The CWD is not always the project root, and sys.path hacks break when tests run from CI with a different working directory. (60% 失败率)
- **** — This works only if the CWD is the project root; under src layout it still fails because the package lives under src/. (50% 失败率)
