|
| 1 | +/** |
| 2 | + * commons - Enables analysis of Swift and Objective-C projects into SonarQube. |
| 3 | + * Copyright © 2015 Backelite (${email}) |
| 4 | + * |
| 5 | + * This program is free software: you can redistribute it and/or modify |
| 6 | + * it under the terms of the GNU Lesser General Public License as published by |
| 7 | + * the Free Software Foundation, either version 3 of the License, or |
| 8 | + * (at your option) any later version. |
| 9 | + * |
| 10 | + * This program is distributed in the hope that it will be useful, |
| 11 | + * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 12 | + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 13 | + * GNU Lesser General Public License for more details. |
| 14 | + * |
| 15 | + * You should have received a copy of the GNU Lesser General Public License |
| 16 | + * along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 17 | + */ |
| 18 | +package com.backelite.sonarqube.commons.surefire; |
| 19 | + |
| 20 | +import com.backelite.sonarqube.commons.TestFileFinders; |
| 21 | +import org.slf4j.Logger; |
| 22 | +import org.slf4j.LoggerFactory; |
| 23 | +import org.sonar.api.batch.fs.FileSystem; |
| 24 | +import org.sonar.api.batch.fs.InputFile; |
| 25 | +import org.sonar.api.batch.sensor.SensorContext; |
| 26 | +import org.sonar.api.component.ResourcePerspectives; |
| 27 | +import org.sonar.api.measures.CoreMetrics; |
| 28 | +import org.sonar.api.measures.Metric; |
| 29 | +import org.sonar.api.test.MutableTestPlan; |
| 30 | +import org.sonar.api.test.TestCase; |
| 31 | +import org.sonar.squidbridge.api.AnalysisException; |
| 32 | + |
| 33 | +import javax.annotation.CheckForNull; |
| 34 | +import javax.xml.parsers.DocumentBuilderFactory; |
| 35 | +import javax.xml.stream.XMLStreamException; |
| 36 | +import java.io.File; |
| 37 | +import java.io.IOException; |
| 38 | +import java.io.Serializable; |
| 39 | +import java.nio.file.DirectoryStream; |
| 40 | +import java.nio.file.Files; |
| 41 | +import java.nio.file.Path; |
| 42 | +import java.util.ArrayList; |
| 43 | +import java.util.HashMap; |
| 44 | +import java.util.List; |
| 45 | +import java.util.Map; |
| 46 | + |
| 47 | +public class SurefireReportParser { |
| 48 | + private static final Logger LOGGER = LoggerFactory.getLogger(SurefireReportParser.class); |
| 49 | + private static final String TESTSUITE = "testsuite"; |
| 50 | + private static final String TESTCASE = "testcase"; |
| 51 | + |
| 52 | + protected final SensorContext context; |
| 53 | + private final DocumentBuilderFactory dbfactory; |
| 54 | + private final UnitTestIndex index; |
| 55 | + private final ResourcePerspectives perspectives; |
| 56 | + private final FileSystem fileSystem; |
| 57 | + |
| 58 | + protected SurefireReportParser(FileSystem fileSystem, ResourcePerspectives perspectives, SensorContext context) { |
| 59 | + this.fileSystem = fileSystem; |
| 60 | + this.context = context; |
| 61 | + this.perspectives = perspectives; |
| 62 | + this.dbfactory = DocumentBuilderFactory.newInstance(); |
| 63 | + this.index = new UnitTestIndex(); |
| 64 | + } |
| 65 | + |
| 66 | + public void collect(File reportsDir) { |
| 67 | + List<File> xmlFiles = new ArrayList<>(); |
| 68 | + try (DirectoryStream<Path> stream = Files.newDirectoryStream(reportsDir.toPath(), "{TEST}*.{xml}")) { |
| 69 | + for (Path p: stream) { |
| 70 | + LOGGER.info("Processing Surefire report {}", p.getFileName()); |
| 71 | + xmlFiles.add(p.toFile()); |
| 72 | + } |
| 73 | + } catch (IOException e) { |
| 74 | + LOGGER.error( "Error while finding test files.", e); |
| 75 | + } |
| 76 | + |
| 77 | + if (!xmlFiles.isEmpty()) { |
| 78 | + parseFiles(xmlFiles); |
| 79 | + } |
| 80 | + } |
| 81 | + |
| 82 | + private void parseFiles(List<File> reports) { |
| 83 | + UnitTestIndex index = new UnitTestIndex(); |
| 84 | + parseFiles(reports, index); |
| 85 | + save(index, context); |
| 86 | + } |
| 87 | + |
| 88 | + private static void parseFiles(List<File> reports, UnitTestIndex index) { |
| 89 | + StaxParser parser = new StaxParser(index); |
| 90 | + for (File report : reports) { |
| 91 | + try { |
| 92 | + parser.parse(report); |
| 93 | + } catch (XMLStreamException e) { |
| 94 | + throw new AnalysisException("Fail to parse the Surefire report: " + report, e); |
| 95 | + } |
| 96 | + } |
| 97 | + } |
| 98 | + |
| 99 | + private void save(UnitTestIndex index, SensorContext context) { |
| 100 | + long negativeTimeTestNumber = 0; |
| 101 | + Map<InputFile, UnitTestClassReport> indexByInputFile = mapToInputFile(index.getIndexByClassname()); |
| 102 | + for (Map.Entry<InputFile, UnitTestClassReport> entry : indexByInputFile.entrySet()) { |
| 103 | + UnitTestClassReport report = entry.getValue(); |
| 104 | + if (report.getTests() > 0) { |
| 105 | + negativeTimeTestNumber += report.getNegativeTimeTestNumber(); |
| 106 | + save(report, entry.getKey(), context); |
| 107 | + } |
| 108 | + } |
| 109 | + if (negativeTimeTestNumber > 0) { |
| 110 | + LOGGER.warn("There is {} test(s) reported with negative time by surefire, total duration may not be accurate.", negativeTimeTestNumber); |
| 111 | + } |
| 112 | + } |
| 113 | + |
| 114 | + private Map<InputFile, UnitTestClassReport> mapToInputFile(Map<String, UnitTestClassReport> indexByClassname) { |
| 115 | + Map<InputFile, UnitTestClassReport> result = new HashMap<>(); |
| 116 | + indexByClassname.forEach((className, index) -> { |
| 117 | + InputFile resource = getUnitTestResource(className, index); |
| 118 | + if (resource != null) { |
| 119 | + UnitTestClassReport report = result.computeIfAbsent(resource, r -> new UnitTestClassReport()); |
| 120 | + // in case of repeated/parameterized tests (JUnit 5.x) we may end up with tests having the same name |
| 121 | + index.getResults().forEach(report::add); |
| 122 | + } else { |
| 123 | + LOGGER.debug("Resource not found: {}", className); |
| 124 | + } |
| 125 | + }); |
| 126 | + return result; |
| 127 | + } |
| 128 | + |
| 129 | + private void save(UnitTestClassReport report, InputFile inputFile, SensorContext context) { |
| 130 | + int testsCount = report.getTests() - report.getSkipped(); |
| 131 | + saveMeasure(context, inputFile, CoreMetrics.SKIPPED_TESTS, report.getSkipped()); |
| 132 | + saveMeasure(context, inputFile, CoreMetrics.TESTS, testsCount); |
| 133 | + saveMeasure(context, inputFile, CoreMetrics.TEST_ERRORS, report.getErrors()); |
| 134 | + saveMeasure(context, inputFile, CoreMetrics.TEST_FAILURES, report.getFailures()); |
| 135 | + saveMeasure(context, inputFile, CoreMetrics.TEST_EXECUTION_TIME, report.getDurationMilliseconds()); |
| 136 | + saveResults(inputFile, report); |
| 137 | + } |
| 138 | + |
| 139 | + protected void saveResults(InputFile testFile, UnitTestClassReport report) { |
| 140 | + for (UnitTestResult unitTestResult : report.getResults()) { |
| 141 | + MutableTestPlan testPlan = perspectives.as(MutableTestPlan.class, testFile); |
| 142 | + if (testPlan != null) { |
| 143 | + testPlan.addTestCase(unitTestResult.getName()) |
| 144 | + .setDurationInMs(Math.max(unitTestResult.getDurationMilliseconds(), 0)) |
| 145 | + .setStatus(TestCase.Status.of(unitTestResult.getStatus())) |
| 146 | + .setMessage(unitTestResult.getMessage()) |
| 147 | + .setStackTrace(unitTestResult.getStackTrace()); |
| 148 | + } |
| 149 | + } |
| 150 | + } |
| 151 | + |
| 152 | + @CheckForNull |
| 153 | + private InputFile getUnitTestResource(String className, UnitTestClassReport unitTestClassReport) { |
| 154 | + return TestFileFinders.getInstance().getUnitTestResource(fileSystem, className); |
| 155 | + } |
| 156 | + |
| 157 | + private static <T extends Serializable> void saveMeasure(SensorContext context, InputFile inputFile, Metric<T> metric, T value) { |
| 158 | + context.<T>newMeasure().forMetric(metric).on(inputFile).withValue(value).save(); |
| 159 | + } |
| 160 | + |
| 161 | +} |
0 commit comments