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

Python2.7中xml.etree.ElementTree的findall无法返回全部匹配节点

问题根因

你的代码调用findall匹配到所有符合条件的testsuite节点后,仅通过索引[0]获取了第一个节点的属性值,没有遍历所有节点做累加,因此统计结果只包含第一个测试套件的数值。

修正后的代码
import os
import xml.etree.ElementTree as ET
import sys

filename = sys.argv[1]
filepath = os.path.join(os.path.dirname(os.path.realpath(__file__)),filename)  

print("Processing File: ", format(filepath))
    
tests = 0
failures = 0
errors = 0
skipped = 0
issues = 0

file = open(filepath, "r")

tree = ET.parse(file)
root = tree.getroot()

# 遍历所有匹配节点累加数值
for node in root.findall(".//*[@tests]"):
    tests += int(node.attrib.get("tests"))
for node in root.findall(".//*[@failures]"):
    failures += int(node.attrib.get("failures"))
for node in root.findall(".//*[@errors]"):
    errors += int(node.attrib.get("errors"))
for node in root.findall(".//*[@skipped]"):
    skipped += int(node.attrib.get("skipped"))

issues += int(failures) + int(errors)
status = "PASSED"
        
if issues > 0:
    status = "FAILED"

print("tests: ", format(tests))
print("issues: ", format(issues))
print("status: ", format(status))
sys.exit(issues)
验证说明

你提供的测试XML中共有3个testsuite节点:

  • 测试用例总数:16 + 1 + 20 = 37
  • 错误总数:0 + 1 + 4 = 5
    修正后代码运行输出和你预期的结果完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 12:15:03