Skip to content

Instantly share code, notes, and snippets.

@kekru
Last active August 9, 2023 13:47
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kekru/347807ffad81bf7ba0d5119e4b148b2e to your computer and use it in GitHub Desktop.
Save kekru/347807ffad81bf7ba0d5119e4b148b2e to your computer and use it in GitHub Desktop.
Aggregate Sonar Generic Test Data Execution

Sonarqube aggregate Generic Test Data Execution

This is how to combine multiple SonarQube test data reports in the Generic Execution format, using node js.

This can be useful, if you run multiple jest tests, exporting with jest-sonar-reporter and want to combine the results to pass it to SonarQube

We will use glob to find files and xml2js to combine them.

const fs = require('fs');
const xml2js = require('xml2js');
const glob = require('glob');

const targetFile = 'test-result.xml';
const sourcePattern = '/some/dir/**.xml';

glob(sourcePattern, (globErr, files) => {
  if (globErr) {
    console.err("Failed to find files for pattern " + sourcePattern, globErr);
    process.exit(1);
  }

  const aggregatedXml = {
    testExecutions: { 
      $: {version: 1},
      file:[] 
    }
  };

  for (const file of files) {
    const fileContent = fs.readFileSync(file, 'utf8');
    xml2js.parseString(fileContent, (err, result) => {
      if (err) {
        console.err("Failed to parse xml " + file, err);
      }

      const fileEntries = result && result.testExecutions && result.testExecutions.file
      if (fileEntries) {
        console.log("Adding %s entries of %s", fileEntries.length, file);
        aggregatedXml.testExecutions.file = aggregatedXml.testExecutions.file.concat(fileEntries);
      } else {
        console.log("No entries in %s", file);
      }
    });      
  }    
  const builder = new xml2js.Builder({xmldec: { 'version': '1.0', 'encoding': 'UTF-8' }});
  const xml = builder.buildObject(aggregatedXml);
  console.log("Writing %s test files to %s", aggregatedXml.testExecutions.file.length, targetFile);
  fs.writeFileSync(targetFile, xml);
});

After this, set the sonar property to the resulting file

'sonar.testExecutionReportPaths': 'test-result.xml'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment