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

如何捕获pytest测试结果并写入CSV同步至Jama?

实现pytest测试结果收集并写入CSV

方案一:用pytest钩子函数直接捕获结果

pytest自带的钩子函数能精准捕获每个测试用例的执行细节,最适合的是pytest_runtest_makereport——它能拿到测试用例的完整执行报告,包括断言失败的具体信息。

具体操作

在项目根目录新建conftest.py(pytest会自动加载这个文件),写入以下代码:

import csv
from datetime import datetime

# 初始化CSV文件,写入表头
def pytest_configure(config):
    with open('test_results.csv', 'w', newline='', encoding='utf-8') as f:
        writer = csv.writer(f)
        writer.writerow([
            '测试用例名称', 
            '执行时间', 
            '测试结果', 
            '断言详情'
        ])

# 捕获每个测试用例的最终执行结果
def pytest_runtest_makereport(item, call):
    # 只处理测试用例执行完成的阶段(跳过setup/teardown环节)
    if call.when == 'call':
        # 提取测试用例名称(去掉文件路径和类名,只留函数名)
        test_name = item.nodeid.split('::')[-1]
        # 记录执行时间
        exec_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        # 测试结果:passed/failed/skipped等
        result = call.outcome
        # 提取断言详情——如果失败,就把错误信息存下来
        assert_detail = ''
        if result == 'failed':
            # 捕获assert语句抛出的具体错误
            if hasattr(call.excinfo, 'value'):
                assert_detail = str(call.excinfo.value)
        
        # 追加写入CSV
        with open('test_results.csv', 'a', newline='', encoding='utf-8') as f:
            writer = csv.writer(f)
            writer.writerow([
                test_name,
                exec_time,
                result,
                assert_detail
            ])

运行测试时直接执行pytest命令,测试结束后根目录会生成test_results.csv,里面每条记录对应一个测试用例的结果,包括断言失败的具体内容(比如assert 2 == 3失败时,会记录2 != 3)。

方案二:借助pytest-html导出后转CSV(可选)

如果已经在用pytest-html生成HTML报告,可以把HTML转成CSV,适合快速迁移现有报告:

  1. 先安装插件:pip install pytest-html
  2. 生成HTML报告:pytest --html=test_report.html
  3. 用Python脚本解析HTML并生成CSV:
from bs4 import BeautifulSoup
import csv

with open('test_report.html', 'r', encoding='utf-8') as f:
    soup = BeautifulSoup(f, 'html.parser')

# 定位测试结果表格
result_table = soup.find('table', class_='results-table')
rows = result_table.find_all('tr')

with open('test_results_from_html.csv', 'w', newline='', encoding='utf-8') as f:
    writer = csv.writer(f)
    # 写入表头
    header = [th.text.strip() for th in rows[0].find_all('th')]
    writer.writerow(header)
    # 逐行写入测试数据
    for row in rows[1:]:
        row_data = [td.text.strip() for td in row.find_all('td')]
        writer.writerow(row_data)

额外提示

  • 要是测试用例用了参数化,item.nodeid会带参数信息,你可以换成item.name来获取更简洁的用例标识。
  • 跳过的测试用例(skipped)也能在pytest_runtest_makereport里捕获,只需在代码里判断result == 'skipped',然后提取跳过原因即可。
  • 用utf-8编码写CSV,避免中文乱码,方便后续同步到Jama系统。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 17:27:15