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

如何使用Python pytest生成CSV或Excel格式的自定义测试报告

当然可以!pytest的扩展性极强,不管是用现成插件快速生成标准报告,还是自己定制高度个性化的CSV/Excel报告都完全可行,给你两种实用方案参考:

方案一:使用现成插件快速实现

这种方式适合不需要太多定制化的场景,上手快:

生成CSV报告

可以用pytest-csv插件,步骤很简单:

  1. 安装插件:
    pip install pytest-csv
    
  2. 执行测试时生成CSV报告:
    py.test --csv=report.csv test.py
    
    你还可以通过命令行参数自定义报告里的字段,比如包含测试耗时、失败原因等,比如:
    py.test --csv=report.csv --csv-columns=id,module,name,status,duration,message test.py
    

生成Excel报告

pytest没有直接生成Excel的官方插件,但可以通过两种方式实现:

  • 先生成CSV报告,再用Excel直接打开(Excel原生支持CSV格式),或者用简单脚本转成xlsx格式;
  • 用pytest-excel插件直接生成xlsx文件,安装后执行:
    pip install pytest-excel
    py.test --excel=report.xlsx test.py
    
方案二:自定义实现(适合高度定制需求)

既然你已经在conftest.py里用了hookwrapper,可以直接扩展现有代码来收集测试结果,然后手动写入CSV或Excel文件。

自定义CSV报告示例

在conftest.py中添加如下代码:

import csv
from datetime import datetime
from pytest import hookimpl

# 存储测试结果的列表
test_results = []

@hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
    outcome = yield
    report = outcome.get_result()
    # 只收集每个测试用例的最终执行结果
    if report.when == "call":
        test_results.append({
            "test_name": item.name,
            "module": item.module.__name__,
            "status": report.outcome,
            "duration": round(report.duration, 2),
            "error_msg": report.longreprtext if report.failed else ""
        })

def pytest_sessionfinish(session, exitstatus):
    # 测试结束后写入CSV文件
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    csv_filename = f"custom_test_report_{timestamp}.csv"
    with open(csv_filename, "w", newline="", encoding="utf-8") as f:
        fieldnames = ["test_name", "module", "status", "duration", "error_msg"]
        writer = csv.DictWriter(f, fieldnames=fieldnames)
        writer.writeheader()
        writer.writerows(test_results)
    print(f"\n自定义CSV报告已生成:{csv_filename}")

自定义Excel报告示例

如果要生成xlsx格式,可以用openpyxl库来实现,先安装依赖:

pip install openpyxl

然后在conftest.py中替换pytest_sessionfinish的代码:

from openpyxl import Workbook
from datetime import datetime

# (前面的pytest_runtest_makereport代码不变)

def pytest_sessionfinish(session, exitstatus):
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    excel_filename = f"custom_test_report_{timestamp}.xlsx"
    wb = Workbook()
    ws = wb.active
    ws.title = "测试结果汇总"
    # 写入表头
    headers = ["测试用例名称", "所属模块", "执行状态", "耗时(秒)", "失败详情"]
    ws.append(headers)
    # 写入测试结果
    for result in test_results:
        row = [
            result["test_name"],
            result["module"],
            result["status"],
            result["duration"],
            result["error_msg"]
        ]
        ws.append(row)
    # 保存文件
    wb.save(excel_filename)
    print(f"\n自定义Excel报告已生成:{excel_filename}")

你可以根据实际需求调整要收集的字段、格式样式或者添加更多自定义逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:56:47