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

如何在Pytest-HTML-Reporter中添加展示Gitlab问题链接/ID的列

给Pytest-HTML-Reporter 0.2.9添加Gitlab问题列的解决方案

步骤1:给测试用例添加Gitlab问题标记

在测试用例上通过@pytest.mark标记Gitlab的问题ID和链接,方便后续收集信息:

import pytest

# 示例测试用例,标记Gitlab问题
@pytest.mark.gitlab_issue(id="GL-123", url="https://gitlab.com/your-team/your-project/issues/123")
def test_login_success():
    assert 1 == 1

@pytest.mark.gitlab_issue(id="GL-456")
def test_checkout_failure():
    assert 2 == 1

步骤2:编写钩子函数收集标记信息

在项目根目录的conftest.py中添加钩子函数,提取测试用例的Gitlab标记信息并附加到测试报告对象上:

import pytest

@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
    outcome = yield
    report = outcome.get_result()
    
    # 提取Gitlab issue标记
    gitlab_marker = item.get_closest_marker("gitlab_issue")
    if gitlab_marker:
        # 从标记中获取ID和链接,默认空字符串
        report.gitlab_issue_id = gitlab_marker.kwargs.get("id", "")
        report.gitlab_issue_url = gitlab_marker.kwargs.get("url", "")

步骤3:修改报告模板添加新列

  1. 找到Pytest-HTML-Reporter的默认模板文件:
    通常在Python安装目录的site-packages/pytest_html_reporter/templates/report.html(虚拟环境下路径类似venv/lib/python3.x/site-packages/pytest_html_reporter/templates/report.html)。
  2. 复制该模板到项目目录,命名为custom_report.html(避免修改全局模板影响其他项目)。
  3. 打开custom_report.html,找到测试结果表格的表头部分(<thead>内的<tr>),在目标位置添加新表头:
    <!-- 在现有表头后添加 -->
    <th>Gitlab Issue</th>
    
  4. 找到表格内容行(<tbody>内的<tr>),对应位置添加列内容:
    <td>
      {% if report.gitlab_issue_url %}
        <a href="{{ report.gitlab_issue_url }}" target="_blank">{{ report.gitlab_issue_id }}</a>
      {% else %}
        {{ report.gitlab_issue_id or '-' }}
      {% endif %}
    </td>
    

步骤4:指定自定义模板生成报告

运行pytest时,通过--template参数指定自定义模板路径:

pytest --html-report=test_report.html --template=./custom_report.html

这样生成的报告就会新增一列,展示对应的Gitlab问题ID或可点击的链接。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 05:22:45