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

如何在pytest HTML报告中添加标记(mark)列?求解决方案

在pytest HTML报告中新增测试标记列的实现方法

要给pytest生成的HTML报告加一列显示测试用例的标记,用pytest-html插件配合自定义钩子就能实现,步骤如下:

  1. 先安装pytest-html插件
    执行命令:

    pip install pytest-html
    
  2. 在测试脚本所在目录创建conftest.py文件,添加以下代码:

    def pytest_html_results_table_header(cells):
        # 在表头插入新列,标题为"测试标记"
        cells.insert(2, "<th>测试标记</th>")
    
    def pytest_html_results_table_row(report, cells):
        # 获取当前测试用例的所有标记
        markers = []
        if hasattr(report, 'item'):
            markers = [mark.name for mark in report.item.iter_markers()]
        # 将标记转为逗号分隔的字符串,无标记则显示"-"
        cells.insert(2, f"<td>{', '.join(markers) if markers else '-'}</td>")
    
  3. 运行测试生成带标记列的HTML报告
    执行命令:

    pytest --html=test_report.html
    

简单说明

  • pytest_html_results_table_header钩子负责修改报告表头,插入新的列标题;
  • pytest_html_results_table_row钩子会遍历每个测试用例结果,提取该用例的所有pytest标记,插入到新增列中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 18:22:40