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

Python脚本从多行测试文本生成XML仅保留最后一行,求修正方案

修正Python脚本实现多行测试结果生成Jenkins兼容XML

问题背景

现有脚本output_unittests.py仅能从unittests.txt读取最后一行测试结果生成单个<testsuite>节点,需求改为每行对应一个<testsuite>节点,生成符合Jenkins要求的XML报告。

测试文本示例(unittests.txt)

TestSuite1: tests=5, failures=0, errors=0, skipped=1, time=2.34
TestSuite2: tests=3, failures=1, errors=0, skipped=0, time=1.12
TestSuite3: tests=8, failures=0, errors=1, skipped=2, time=4.56

原脚本代码

import xml.etree.ElementTree as ET

def generate_xml():
    root = ET.Element("testsuites")
    with open("unittests.txt", "r") as f:
        # 仅读取最后一行
        last_line = f.readlines()[-1].strip()
        parts = last_line.split(": ")
        suite_name = parts[0]
        stats = parts[1].split(", ")
        testsuite = ET.SubElement(root, "testsuite", name=suite_name)
        for stat in stats:
            key, value = stat.split("=")
            testsuite.set(key, value)
    tree = ET.ElementTree(root)
    tree.write("jenkins_tests.xml", encoding="utf-8", xml_declaration=True)

if __name__ == "__main__":
    generate_xml()

期望XML输出

<?xml version='1.0' encoding='utf-8'?>
<testsuites>
  <testsuite name="TestSuite1" tests="5" failures="0" errors="0" skipped="1" time="2.34"/>
  <testsuite name="TestSuite2" tests="3" failures="1" errors="0" skipped="0" time="1.12"/>
  <testsuite name="TestSuite3" tests="8" failures="0" errors="1" skipped="2" time="4.56"/>
</testsuites>

修正后的脚本

import xml.etree.ElementTree as ET

def generate_xml():
    root = ET.Element("testsuites")
    with open("unittests.txt", "r") as f:
        # 遍历每一行测试结果
        for line in f:
            line = line.strip()
            # 跳过空行和格式异常的行
            if not line or ": " not in line:
                continue
            
            suite_name, stats_str = line.split(": ", 1)
            stats = stats_str.split(", ")
            
            # 为当前行创建testsuite节点
            testsuite = ET.SubElement(root, "testsuite", name=suite_name)
            
            # 解析并设置统计属性
            for stat in stats:
                if "=" not in stat:
                    continue
                key, value = stat.split("=", 1)
                testsuite.set(key.strip(), value.strip())
    
    # 给XML添加缩进(Python 3.9+支持)
    ET.indent(root, space="  ")
    tree = ET.ElementTree(root)
    tree.write("jenkins_tests.xml", encoding="utf-8", xml_declaration=True)

if __name__ == "__main__":
    generate_xml()

关键修改说明

  • 移除了仅读取最后一行的逻辑,改为逐行遍历文件内容
  • 添加了基础格式校验:跳过空行、跳过不含: 或=的异常行,避免脚本崩溃
  • 每处理一行就新建一个<testsuite>节点,实现一行对应一个测试套件
  • 加入ET.indent()让输出的XML格式更整洁(如果你的Python版本低于3.9,可以自行实现缩进函数,或者去掉该语句不影响功能)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 11:15:33