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

如何将pytest结果解析并收集至pandas DataFrame?

当然有可行的方法!我来给你拆解几种实用的方案,包括你提到的那篇资料里涉及的核心思路,一步步来实践:

方法1:用pytest内置钩子实时收集结果(对应你提到的资料思路)

那篇《Collecting and Reporting pytest Results》的核心就是利用pytest的钩子机制,在测试运行过程中实时捕获结果,再转成DataFrame。这是最灵活的方案,能自定义收集任意你需要的字段。

具体操作步骤:

  1. 在项目根目录创建conftest.py文件,定义一个全局fixture用来暂存测试结果:
import pytest
import pandas as pd

@pytest.fixture(scope="session")
def test_results():
    # 用列表暂存所有测试结果
    results_list = []
    yield results_list
    # 所有测试结束后,把列表转成DataFrame
    results_df = pd.DataFrame(results_list)
    print("\n整理后的测试结果DataFrame:\n", results_df)
    # 也可以直接导出到CSV
    results_df.to_csv("pytest_results.csv", index=False)
  1. 实现pytest_runtest_makereport钩子,捕获每个测试的结果并存入fixture:
def pytest_runtest_makereport(item, call):
    # 只收集测试执行阶段的结果(跳过setup/teardown阶段)
    if call.when == "call":
        # 提取你需要的字段,这里是基础示例,可按需扩展
        test_result = {
            "测试用例路径": item.nodeid,
            "执行状态": call.outcome,  # passed/failed/skipped
            "耗时(秒)": round(call.duration, 3),
            "错误信息": str(call.excinfo.value) if call.excinfo else None
        }
        # 把结果追加到之前定义的fixture列表中
        item.funcargs["test_results"].append(test_result)

运行pytest时,所有测试结果会自动收集,测试结束后直接生成DataFrame。如果需要收集更多信息(比如测试标记、所属模块),还可以通过item.iter_markers()或item.module来扩展字段。

方法2:解析pytest的JSON输出文件(适合快速处理已有报告)

如果你已经生成了测试报告,或者不想写钩子,可以让pytest输出JSON格式的结果,再用pandas读取解析:

  1. 先安装生成JSON报告的插件:
pip install pytest-json-report
  1. 运行pytest时指定输出JSON文件:
pytest --json-report --json-report-file=pytest_results.json
  1. 读取JSON文件并转成DataFrame:
import pandas as pd
import json

with open("pytest_results.json", "r") as f:
    raw_data = json.load(f)

# 提取测试用例的核心数据
test_cases = raw_data["tests"]
# 按需筛选字段生成DataFrame
results_df = pd.DataFrame(test_cases)[["nodeid", "outcome", "duration", "error"]]
print(results_df)

这个方法更轻量化,适合快速生成结构化结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:54:32