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

如何在pytest HTML报告中添加测试函数docstring列?

在pytest-html报告中添加测试函数的Docstring列

要实现你的需求,直接在项目根目录创建conftest.py文件,通过以下pytest钩子函数即可完成:

完整代码片段

import pytest

def pytest_runtest_makereport(item, call):
    # 提取测试函数的docstring并清理格式
    raw_doc = item.function.__doc__
    cleaned_doc = raw_doc.strip() if raw_doc else "无测试描述"
    
    # 将处理后的描述存入报告的用户属性,供表格渲染调用
    if call.when == "call":
        item.user_properties.append(("docstring", cleaned_doc))

def pytest_html_results_table_header(cells):
    # 在"Test"列和"Duration"列之间插入新表头
    duration_col_idx = next(i for i, cell in enumerate(cells) if cell.text == "Duration")
    cells.insert(duration_col_idx, '<th>测试描述</th>')

def pytest_html_results_table_row(report, cells):
    # 从报告属性中取出描述,插入对应行的指定位置
    doc_content = next((val for key, val in report.user_properties if key == "docstring"), "无测试描述")
    duration_col_idx = next(i for i, cell in enumerate(cells) if cell.text.startswith("Duration"))
    cells.insert(duration_col_idx, f'<td>{doc_content}</td>')

代码说明

  • pytest_runtest_makereport:捕获测试函数的文档字符串,处理掉多余换行和空格后,存入报告的用户属性集合中。
  • pytest_html_results_table_header:修改HTML报告的表头结构,在"Duration"列前插入自定义的"测试描述"列。
  • pytest_html_results_table_row:对应每一行测试结果,从报告属性中取出预存的描述内容,插入到新增的表格列位置。

使用方式

运行pytest时指定生成HTML报告:

pytest --html=test_report.html

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 21:25:41