You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何仅在测试失败时生成pytest-html测试报告?

解决方案:通过pytest钩子函数控制报告生成

要实现仅当测试失败时生成pytest-html报告,可以借助pytest的钩子函数,在测试会话结束后根据结果决定是否保留报告。以下是具体实现步骤:

方法一:使用conftest.py钩子函数(推荐)

在你的测试项目根目录下创建或修改conftest.py文件,添加以下代码:

import os
import pytest

@pytest.hookimpl(tryfirst=True)
def pytest_sessionfinish(session, exitstatus):
    # 获取命令行中指定的报告路径
    report_path = session.config.getoption("--html")
    if not report_path:
        return
    
    # 若没有测试失败,删除生成的报告文件
    if session.testsfailed == 0 and os.path.exists(report_path):
        os.remove(report_path)

原理说明

  • 让pytest正常执行所有测试并生成报告,避免重复执行测试的额外开销
  • 测试会话结束后,通过session.testsfailed判断是否有失败用例:
    • 若为0(全部通过),自动删除报告文件
    • 若大于0(存在失败),保留报告文件

使用方式

继续使用你的pytest命令(可去掉重复的--verbose,-v已包含该功能):

pytest -v -s --html=report.html --self-contained-html --capture=tee-sys -rx --maxfail=6 testCases/test_signup_0.py

方法二:Shell脚本二次执行(不推荐)

如果不想修改代码,也可以用Shell脚本先执行测试判断结果,仅在失败时重新执行并生成报告。但此方法会执行两次测试,效率较低:

# 先执行测试不生成报告,获取返回码
pytest -v -s --capture=tee-sys -rx --maxfail=6 testCases/test_signup_0.py
TEST_EXIT_CODE=$?

# 若返回码非0(存在失败),再执行带报告的命令
if [ $TEST_EXIT_CODE -ne 0 ]; then
    pytest -v -s --html=report.html --self-contained-html --capture=tee-sys -rx --maxfail=6 testCases/test_signup_0.py
fi

内容的提问来源于stack exchange,提问作者Georgian Costea

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 08:06:23