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

如何在pytest-html-reporter中为测试用例添加自定义消息?

给pytest-html-reporter测试用例添加自定义消息的方法

你用print和普通日志没显示是因为pytest-html-reporter默认不会捕获这类输出,得用插件兼容的方式添加自定义内容,下面是几种可行方案:

方案1:在测试用例中直接添加报告章节

通过request fixture在测试函数内直接插入自定义内容,代码示例:

def test_dashboard_example(request):
    # 你的测试逻辑代码
    request.node.add_report_section(
        "custom",
        "自定义消息",
        "这里可以写测试步骤说明、中间校验结果等自定义内容"
    )
    assert 1 == 1

添加后,报告中会新增一个「自定义消息」板块,展示你填写的内容。

方案2:用自定义标记+钩子统一注入内容

先给测试用例添加自定义标记,再通过conftest.py的钩子函数把标记内容同步到报告:

  1. 编写conftest.py钩子:
import pytest

@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
    outcome = yield
    report = outcome.get_result()
    # 获取自定义标记的内容
    custom_msg = item.get_closest_marker("custom_msg")
    if custom_msg:
        report.sections.append(("自定义描述", custom_msg.args[0]))
  1. 测试用例写法:
import pytest

@pytest.mark.custom_msg("验证Dashboard页面加载状态,已检查标题、导航栏元素")
def test_dashboard_load():
    # 测试逻辑代码
    assert True

方案3:把print输出捕获到报告

如果坚持用print,可以通过capsys fixture捕获输出后手动注入报告:

def test_dashboard_print(capsys, request):
    print("测试过程:正在校验Dashboard数据展示")
    # 捕获print输出内容
    captured = capsys.readouterr()
    # 添加到报告
    request.node.add_report_section(
        "custom",
        "打印输出",
        captured.out.strip()
    )
    assert 1 == 1

另外注意:你命令行里的--capture=tee-sys只会把输出同步到控制台和pytest的捕获缓冲区,但不会自动同步到pytest-html-reporter的报告里,需要通过上面的手动注入方式实现。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 01:10:04