# 收集 tests/test_api.py 时出错
导入测试模块 'tests/test_api.py' 时发生 ImportError。
提示: 确保你的测试模块/包具有有效的 Python 名称。
ModuleNotFoundError: 没有名为 'myapp' 的模块

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

## 根因

pytest 从项目根目录不在 sys.path 上的目录运行，且包未以可编辑模式安装；pytest 基于 rootdir 的 sys.path 插入不覆盖源码布局。

## 版本兼容性

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

## 解决方案

1. **** (97% 成功率)
   ```
   pip install -e .
# or with pyproject:
pip install -e '.[dev]'
pytest
   ```
2. **** (94% 成功率)
   ```
   # pyproject.toml
[tool.pytest.ini_options]
pythonpath = ["."]
testpaths = ["tests"]
   ```

## 无效尝试

- **** — Works locally but breaks in CI where cwd differs; also fails when tests are collected before the insert executes for other modules. (70% 失败率)
- **** — Does not persist across CI jobs or IDE runs; developers forget to export it and the error returns. (65% 失败率)
