Skip to content

Instantly share code, notes, and snippets.

@macghriogair
Last active July 22, 2020 18:41
Show Gist options
  • Save macghriogair/4976b8e6ea6d20a61cdeb95effb73364 to your computer and use it in GitHub Desktop.
Save macghriogair/4976b8e6ea6d20a61cdeb95effb73364 to your computer and use it in GitHub Desktop.
[patch PHPUnit XML report for sonarqube] #phpunit #sonarqube
#!/usr/bin/env python
# coding: utf-8
import sys
import xml.etree.ElementTree as ET
report_file_path = 'project/tests/_output/report.xml'
if (len(sys.argv) > 1):
report_file_path = sys.argv[1]
et = ET.parse(report_file_path)
root = et.getroot()
parent_map = dict((c, p) for p in root.getiterator() for c in p)
# Step 1: find dataProvider tests
data_provider_suites = []
for item in root.iter("testcase"):
if "with data set " in item.attrib['name']:
suite = parent_map[item]
if suite not in data_provider_suites:
data_provider_suites.append(suite)
# Step 2: move testcases up by 1 node level
for suite in data_provider_suites:
parent_suite = parent_map[suite]
for testcase in suite:
parent_suite.append(testcase)
suite_id = id(suite)
for s in parent_suite:
if (id(s) == suite_id):
parent_suite.remove(s)
et.write(report_file_path)
print('Patched PHPUnit report for Sonarqube:' + report_file_path)
@pleszczynski
Copy link

Actually, PHPUnit supports named data sets, in which case this won't work. Example dataProvider:

    public function additionProvider()
    {
        return [
            'adding zeros'  => [0, 0, 0],
            'zero plus one' => [0, 1, 1],
            'one plus zero' => [1, 0, 1],
            'one plus one'  => [1, 1, 3]
        ];
    }

This will produce testsuite with name name="testDataProviders with data set "adding zeros""

To fix this, simply change "with data set #" to "with data set ".

@macghriogair
Copy link
Author

Nice, thanks for the hint @pleszczynski!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment