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
相关产品推荐
相关产品推荐

