jenkins-lib/resources/merge-junit-results.py

74 lines
1.9 KiB
Python
Executable File

#!/usr/bin/env python
#
# Corey Goldberg, Dec 2012
#
import os
import re
import sys
import xml.etree.ElementTree as ET
"""Merge multiple JUnit XML files into a single results file.
Output dumps to sdtdout.
example usage:
$ python merge_junit_results.py results1.xml results2.xml > results.xml
"""
def main():
args = sys.argv[1:]
if not args:
usage()
sys.exit(2)
if '-h' in args or '--help' in args:
usage()
sys.exit(2)
merge_results(args[:])
JUNIT_RE = re.compile('junit-(.*?)(-results?)?.xml')
def merge_results(xml_files):
failures = 0
tests = 0
errors = 0
time = 0.0
cases = []
for file_name in xml_files:
tree = ET.parse(file_name)
name = JUNIT_RE.match(file_name)
if name:
name = name.group(1)
test_suites = tree.getroot()
for test_suite in test_suites:
failures += int(test_suite.attrib.get('failures', '0'))
tests += int(test_suite.attrib.get('tests', '0'))
errors += int(test_suite.attrib.get('errors', '0'))
time += float(test_suite.attrib.get('time', '0.'))
for test_case in test_suite.findall('testcase'):
if name:
test_case.attrib['classname'] = '%s.%s' % (name, test_case.attrib.get('classname', ''))
cases.append(test_case)
new_root = ET.Element('testsuites')
test_suite = ET.SubElement(new_root, 'testsuite')
test_suite.attrib['failures'] = '%s' % failures
test_suite.attrib['tests'] = '%s' % tests
test_suite.attrib['errors'] = '%s' % errors
test_suite.attrib['time'] = '%s' % time
test_suite.extend(cases)
new_tree = ET.ElementTree(new_root)
ET.dump(new_tree)
def usage():
this_file = os.path.basename(__file__)
print('Usage: %s results1.xml results2.xml' % this_file)
if __name__ == '__main__':
main()