pytest 常见问题解答 (FAQ)
1. 基础问题
Q1: 如何让 pytest 发现我的测试文件?
- 测试文件命名需符合
test_*.py
或*_test.py
模式 - 测试函数/方法需以
test_
开头 - 测试类需以
Test
开头(且不能有__init__
方法)
Q2: 如何运行特定测试?
pytest path/to/test_file.py::test_func # 运行单个测试
pytest -k "pattern" # 运行名称匹配的测试
pytest -m mark_name # 运行特定标记的测试
Q3: 如何查看详细的测试输出?
pytest -v # 详细模式
pytest -s # 显示print输出
pytest --tb=auto # 控制错误回溯显示方式(native/short/no等)
2. 配置问题
Q4: 如何配置 pytest 默认选项?
在项目根目录创建 pytest.ini
:
[pytest]
addopts = -v --tb=short
python_files = test_*.py
markers =slow: marks tests as slow
Q5: 如何跳过某些测试?
@pytest.mark.skip(reason="Not implemented yet")
def test_feature():...@pytest.mark.skipif(sys.version_info < (3, 8), reason="requires Python 3.8+")
def test_py38_feature():...
3. 高级用法问题
Q6: 什么是 fixture?如何使用?
Fixture 是 pytest 的依赖注入系统:
@pytest.fixture
def db_connection():conn = create_connection()yield conn # 测试执行前运行conn.close() # 测试执行后清理def test_query(db_connection): # 自动注入fixtureresult = db_connection.query("SELECT 1")assert result == 1
Q7: 如何参数化测试?
@pytest.mark.parametrize("input,expected", [("3+5", 8),("2+4", 6),
])
def test_eval(input, expected):assert eval(input) == expected
4. 常见错误解决
Q8: 遇到 “fixture not found” 错误?
- 确保 fixture 名称拼写正确
- 将常用 fixture 放在
conftest.py
文件中 - 检查 fixture 作用域(如 module/session 级fixture不能用在函数级fixture中)
Q9: 如何解决插件冲突?
pip list | grep pytest # 查看已安装插件
pytest --trace-config # 查看加载的插件
5. 集成与扩展
Q10: 如何生成覆盖率报告?
pip install pytest-cov
pytest --cov=my_package --cov-report=html
Q11: 如何并行运行测试?
pip install pytest-xdist
pytest -n 4 # 使用4个worker
6. 调试技巧
Q12: 如何调试失败的测试?
pytest --pdb # 失败时进入pdb调试
pytest --trace # 立即进入调试在每个测试开始前
Q13: 如何查看fixture执行顺序?
pytest --setup-show test_file.py
7. 最佳实践
Q14: 如何组织大型测试套件?
- 按功能模块组织测试文件
- 使用
conftest.py
共享 fixture - 合理使用标记分类测试
Q15: 如何测试异常?
def test_divide_by_zero():with pytest.raises(ZeroDivisionError):1 / 0# 也可以检查异常信息with pytest.raises(ValueError, match="invalid literal"):int("a")
8. 性能问题
Q16: 如何加速测试执行?
- 使用
pytest-xdist
并行运行 - 减少 I/O 操作,使用 mock
- 将慢测试标记为
@pytest.mark.slow
并默认跳过