# ModuleNotFoundError：没有名为 'myapp' 的模块
  文件 "/app/tests/test_api.py"，第 3 行，在 <module> 中
    from myapp.api import create_app

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

## 根因

pytest 运行时项目根目录不在 sys.path 上。当从项目根目录以外的目录调用测试，或者包未安装（pip install -e .）且项目根目录没有 conftest.py 来锚定 rootdir 时，就会发生这种情况。

## 版本兼容性

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

## 解决方案

1. **** (97% 成功率)
   ```
   pip install -e .
pytest tests/
   ```
2. **** (90% 成功率)
   ```
   # project/conftest.py (empty is enough)
touch conftest.py
pytest tests/
   ```
3. **** (93% 成功率)
   ```
   # pyproject.toml
[tool.pytest.ini_options]
pythonpath = ["."]
   ```

## 无效尝试

- **** — Depends on CWD at runtime; breaks in CI when pytest is invoked from a different directory, and pollutes each test file. (80% 失败率)
- **** — Works interactively but not in CI or IDE test runners; teammates hit the same error. (75% 失败率)
