如何为pytest-html报告添加Git仓库自定义链接及测试文件相对路径
在pytest-html报告中为测试用例添加Git仓库文件链接
使用的工具版本
- pytest 6.2.4
- pytest-html 3.1.1
- pytest-json-report 1.2.4
- pytest-metadata 2.0.4
现有测试用例(test.py)
import logging import pytest @pytest.mark.order(2) @pytest.mark.parametrize('p_iteration', [x for x in range(3)]) def test_a(p_iteration): logging.info('test_a') if p_iteration == 2: logging.debug(f'I am parameter: {p_iteration}') assert True else: pass @pytest.mark.order(1) def test_b(): logging.info('test_b') assert True
现有conftest.py钩子配置
import pytest from py.xml import html def pytest_html_report_title(report): report.title = "My very own title!" @pytest.hookimpl(tryfirst=True) def pytest_html_results_table_header(cells): cells.insert(4, html.th('Custom Data Row')) @pytest.hookimpl(tryfirst=True) def pytest_html_results_table_row(report, cells): test_id = report custom_data = getattr(report, 'custom_data', test_id) # Access the custom data from the report cells.insert(4, html.td(custom_data))
需求与问题
希望在Custom Data Row列中添加当前测试用例对应Git仓库文件的直接链接,而非仅显示测试名称。目前通过pytest_runtest_makereport钩子仅能获取测试文件的绝对路径,需要将其转换为相对于工作目录的路径,再拼接Git仓库地址生成可点击的链接。
解决方案
通过以下步骤实现:
- 利用pytest的
config.rootpath获取项目根目录(即Git仓库的工作目录) - 从测试报告的
nodeid中提取测试文件的路径部分 - 计算文件路径相对于根目录的相对路径
- 拼接Git仓库的URL(需替换为你的实际仓库地址和分支)
- 将生成的HTML链接存入报告的
custom_data属性,在表格行钩子中渲染
修改后的conftest.py代码
import pytest from py.xml import html import os # 替换为你的Git仓库基础URL和分支,例如GitHub格式:https://github.com/your-username/your-repo/blob/main/ GIT_REPO_BASE_URL = "https://github.com/your-username/your-repo/blob/main/" def pytest_html_report_title(report): report.title = "My very own title!" @pytest.hookimpl(tryfirst=True) def pytest_html_results_table_header(cells): cells.insert(4, html.th('Git File Link')) # 可修改列名更清晰 @pytest.hookimpl(tryfirst=True, hookwrapper=True) def pytest_runtest_makereport(item, call): outcome = yield report = outcome.get_result() # 获取项目根目录 root_path = item.config.rootpath # 从nodeid中提取测试文件路径(nodeid格式如:test.py::test_a[0]) test_file_path = report.nodeid.split("::")[0] # 计算相对路径 relative_path = os.path.relpath(test_file_path, root_path) # 拼接Git仓库链接 git_link = f"{GIT_REPO_BASE_URL}{relative_path}" # 将链接作为HTML元素存入report的custom_data report.custom_data = html.a("View in Git", href=git_link, target="_blank") @pytest.hookimpl(tryfirst=True) def pytest_html_results_table_row(report, cells): custom_data = getattr(report, 'custom_data', "N/A") cells.insert(4, html.td(custom_data))
说明
pytest_runtest_makereport使用hookwrapper=True来获取并修改测试报告对象item.config.rootpath是pytest识别的项目根目录,比os.getcwd()更可靠,适配从子目录运行pytest的场景- 需将
GIT_REPO_BASE_URL替换为你的实际仓库地址,注意包含分支部分(如main或master) - 生成的链接会在新窗口打开(
target="_blank"),方便跳转查看
内容的提问来源于stack exchange,提问作者dubaksk
相关产品推荐
相关产品推荐

