一、问题现象描述
当开发者使用pytest.main([...])执行测试套件时,经常遇到测试用例收集失败的情况。控制台输出类似警告:
============================ no tests ran in 0.12s ============================
这种问题通常表现为:
- 明明存在测试文件但被识别为空
- 子目录中的测试用例未被发现
- 自定义命名的测试文件未被包含
二、根本原因分析
1. 工作目录问题
pytest默认从当前工作目录开始搜索测试文件。当通过IDE或脚本调用时,工作目录可能与项目根目录不一致。通过os.getcwd()可验证实际工作路径。
2. 文件命名规范
pytest默认识别以下文件模式:
| 有效模式 | 无效模式 |
|---|---|
| test_*.py | check_*.py |
| *_test.py | spec_*.py |
3. 路径配置错误
常见错误配置包括:
- 相对路径使用不当(如
../tests) - Windows路径未转义(
C:\\dev\\project应写作r"C:\dev\project")
三、解决方案
方案1:显式指定搜索路径
pytest.main([r"project_root/tests", "--verbose"])
方案2:修改pythonpath环境变量
import sys
sys.path.insert(0, os.path.dirname(__file__))
pytest.main()
方案3:自定义收集规则
在pytest.ini中配置:
[pytest]
python_files = check_*.py spec_*.py
python_paths = ./src ./tests
四、高级调试技巧
1. 使用--collect-only参数
pytest --collect-only -v
2. 检查插件冲突
某些插件(如pytest-cov)可能影响测试发现:
pytest.main(["--no-cov", "tests/"])
3. 日志诊断
启用调试日志:
import logging
logging.basicConfig(level=logging.DEBUG)
pytest.main(["-rA"])
五、最佳实践建议
- 始终在项目根目录执行测试
- 统一使用
test_*.py命名规范 - 复杂项目使用
pyproject.toml配置 - CI环境中显式设置PYTHONPATH