收集 tests/test_api.py 时出错 导入测试模块 'tests/test_api.py' 时发生 ImportError。 提示: 确保你的测试模块/包具有有效的 Python 名称。 ModuleNotFoundError: 没有名为 'myapp' 的模块
ERROR collecting tests/test_api.py ImportError while importing test module 'tests/test_api.py'. Hint: make sure your test modules/packages have valid Python names. ModuleNotFoundError: No module named 'myapp'
ID: python/pytest-collection-error-importerror
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 7.x | active | — | — | — |
| 8.x | active | — | — | — |
根因分析
pytest 从项目根目录不在 sys.path 上的目录运行,且包未以可编辑模式安装;pytest 基于 rootdir 的 sys.path 插入不覆盖源码布局。
English
pytest is invoked from a directory where the project root is not on sys.path, and the package is not installed in editable mode; pytest's rootdir-based sys.path insertion does not cover the source layout.
解决方案
-
97% 成功率
pip install -e . # or with pyproject: pip install -e '.[dev]' pytest
-
94% 成功率
# pyproject.toml [tool.pytest.ini_options] pythonpath = ["."] testpaths = ["tests"]
无效尝试
常见但无效的做法:
-
70% 失败
Works locally but breaks in CI where cwd differs; also fails when tests are collected before the insert executes for other modules.
-
65% 失败
Does not persist across CI jobs or IDE runs; developers forget to export it and the error returns.