如何合并多个Google Test生成的XML测试报告?
问题描述
我尝试为用Google Test创建的多个测试生成XML测试报告。现有两个可执行文件:/test1.out 和 /test2.out,我使用如下shell脚本运行它们:
#!/bin/sh /test1.out --gtest_output="xml:testreport.xml" /test2.out --gtest_output="xml:testreport.xml"
我希望将两份测试报告合并,但当前test2的报告会覆盖test1的testreport.xml,请问有没有简单的实现方法?
解决方法
方法1:先生成分开的XML,再合并
Google Test本身不支持直接追加到同一个XML文件,但可以先让每个测试生成独立报告,再用工具合并。
- 修改脚本,让每个测试生成单独的XML:
#!/bin/sh /test1.out --gtest_output="xml:test1_report.xml" /test2.out --gtest_output="xml:test2_report.xml"
- 用Python脚本合并(无需额外依赖),把多个XML里的
<testsuite>节点合并到统一的<testsuites>根节点下:
import xml.etree.ElementTree as ET import sys def merge_gtest_xmls(input_files, output_file): root = ET.Element("testsuites") for file in input_files: tree = ET.parse(file) test_suites = tree.findall(".//testsuite") for suite in test_suites: root.append(suite) ET.ElementTree(root).write(output_file, encoding='utf-8', xml_declaration=True) if __name__ == "__main__": if len(sys.argv) < 3: print("用法: python merge_gtest.py <输入文件1> <输入文件2> ... <输出文件>") sys.exit(1) merge_gtest_xmls(sys.argv[1:-1], sys.argv[-1])
保存为merge_gtest.py后运行:
python merge_gtest.py test1_report.xml test2_report.xml testreport.xml
方法2:用shell命令追加并修正XML
如果不想写脚本,可以用sed等命令提取第二个测试的有效节点,插入到原XML中:
# 先运行第一个测试生成完整报告 /test1.out --gtest_output="xml:testreport.xml" # 提取第二个测试的testsuite部分,过滤掉XML声明和根节点 /test2.out --gtest_output="xml:-" | sed -n '/<testsuite/,/<\/testsuite>/p' > temp_suite.xml # 把提取的内容插入到原XML的</testsuites>标签前 sed -i.bak -e '/<\/testsuites>/e cat temp_suite.xml' testreport.xml # 清理临时文件 rm temp_suite.xml testreport.xml.bak
这种方法适合Linux/macOS环境快速处理,若测试有多个<testsuite>节点,需调整sed匹配规则。
方法3:使用gtest-parallel工具
如果经常处理多测试二进制文件,可直接用gtest-parallel工具,它能自动并行运行测试并生成合并后的XML:
gtest-parallel /test1.out /test2.out --output=xml:testreport.xml
内容的提问来源于stack exchange,提问作者Gaston
相关产品推荐
相关产品推荐

