From 2207b98209ce2b1b6e0b1be16c875d2276b2860c Mon Sep 17 00:00:00 2001 From: Eli8838 <45560791+Eli8838@users.noreply.github.com> Date: Tue, 4 Dec 2018 14:53:59 +0200 Subject: [PATCH] support 7.4 sonarqube (#1) --- pom.xml | 4 +- sonar-groovy-plugin/pom.xml | 12 +- .../groovy/foundation/GroovyFileSystem.java | 4 +- .../groovy/jacoco/JaCoCoConfiguration.java | 4 +- .../groovy/surefire/GroovySurefireParser.java | 4 +- .../plugins/groovy/GroovyPluginTest.java | 10 +- .../plugins/groovy/GroovySensorTest.java | 89 ++----- .../groovy/cobertura/CoberturaSensorTest.java | 65 +++-- .../groovy/codenarc/CodeNarcSensorTest.java | 41 ++-- .../foundation/GroovyFileSystemTest.java | 25 +- .../GroovyHighlighterAndTokenizerTest.java | 77 ++++-- .../plugins/groovy/foundation/GroovyTest.java | 3 +- .../jacoco/JaCoCoConfigurationTest.java | 15 +- .../groovy/jacoco/JaCoCoItSensorTest.java | 28 ++- .../jacoco/JaCoCoOverallSensorTest.java | 30 ++- .../groovy/jacoco/JaCoCoSensorTest.java | 227 +++++++++--------- .../surefire/GroovySurefireParserTest.java | 27 ++- .../surefire/GroovySurefireSensorTest.java | 16 +- 18 files changed, 384 insertions(+), 297 deletions(-) diff --git a/pom.xml b/pom.xml index d882752d..aa681180 100644 --- a/pom.xml +++ b/pom.xml @@ -59,10 +59,10 @@ - 5.6 + 7.4 0.7.4.201502262128 0.7.5.201505241946 - 2.4.4 + 2.5.4 3.11 sonar-groovy diff --git a/sonar-groovy-plugin/pom.xml b/sonar-groovy-plugin/pom.xml index d2e523df..e5cb2da8 100644 --- a/sonar-groovy-plugin/pom.xml +++ b/sonar-groovy-plugin/pom.xml @@ -66,7 +66,7 @@ ${project.groupId} groovy-jacoco-previous - ${project.version} + 1.4 org.sonarsource.sonarqube @@ -84,6 +84,16 @@ commons-io 2.5 + + org.codehaus.staxmate + staxmate + 2.0.1 + + + com.fasterxml.woodstox + woodstox-core + 5.0.2 + commons-lang commons-lang diff --git a/sonar-groovy-plugin/src/main/java/org/sonar/plugins/groovy/foundation/GroovyFileSystem.java b/sonar-groovy-plugin/src/main/java/org/sonar/plugins/groovy/foundation/GroovyFileSystem.java index 1bfc906d..6aa8deb6 100644 --- a/sonar-groovy-plugin/src/main/java/org/sonar/plugins/groovy/foundation/GroovyFileSystem.java +++ b/sonar-groovy-plugin/src/main/java/org/sonar/plugins/groovy/foundation/GroovyFileSystem.java @@ -23,14 +23,14 @@ import java.util.ArrayList; import java.util.List; import javax.annotation.CheckForNull; -import org.sonar.api.batch.BatchSide; +import org.sonar.api.batch.ScannerSide; import org.sonar.api.batch.fs.FilePredicate; import org.sonar.api.batch.fs.FilePredicates; import org.sonar.api.batch.fs.FileSystem; import org.sonar.api.batch.fs.InputFile; import org.sonar.api.batch.fs.InputFile.Type; -@BatchSide +@ScannerSide public class GroovyFileSystem { private final FileSystem fileSystem; diff --git a/sonar-groovy-plugin/src/main/java/org/sonar/plugins/groovy/jacoco/JaCoCoConfiguration.java b/sonar-groovy-plugin/src/main/java/org/sonar/plugins/groovy/jacoco/JaCoCoConfiguration.java index 5982819f..643255aa 100644 --- a/sonar-groovy-plugin/src/main/java/org/sonar/plugins/groovy/jacoco/JaCoCoConfiguration.java +++ b/sonar-groovy-plugin/src/main/java/org/sonar/plugins/groovy/jacoco/JaCoCoConfiguration.java @@ -22,14 +22,14 @@ import java.util.Arrays; import java.util.List; import org.sonar.api.PropertyType; -import org.sonar.api.batch.BatchSide; +import org.sonar.api.batch.ScannerSide; import org.sonar.api.batch.fs.FileSystem; import org.sonar.api.config.PropertyDefinition; import org.sonar.api.config.Settings; import org.sonar.api.resources.Qualifiers; import org.sonar.plugins.groovy.foundation.Groovy; -@BatchSide +@ScannerSide public class JaCoCoConfiguration { public static final String REPORT_PATH_PROPERTY = "sonar.groovy.jacoco.reportPath"; diff --git a/sonar-groovy-plugin/src/main/java/org/sonar/plugins/groovy/surefire/GroovySurefireParser.java b/sonar-groovy-plugin/src/main/java/org/sonar/plugins/groovy/surefire/GroovySurefireParser.java index d88ccbaa..d4e96700 100644 --- a/sonar-groovy-plugin/src/main/java/org/sonar/plugins/groovy/surefire/GroovySurefireParser.java +++ b/sonar-groovy-plugin/src/main/java/org/sonar/plugins/groovy/surefire/GroovySurefireParser.java @@ -26,7 +26,7 @@ import java.util.Map; import javax.xml.stream.XMLStreamException; import org.apache.commons.lang.StringUtils; -import org.sonar.api.batch.BatchSide; +import org.sonar.api.batch.ScannerSide; import org.sonar.api.batch.fs.FilePredicate; import org.sonar.api.batch.fs.FilePredicates; import org.sonar.api.batch.fs.FileSystem; @@ -48,7 +48,7 @@ import org.sonar.plugins.groovy.surefire.data.UnitTestResult; import org.sonar.plugins.groovy.utils.StaxParser; -@BatchSide +@ScannerSide public class GroovySurefireParser { private static final Logger LOGGER = Loggers.get(GroovySurefireParser.class); diff --git a/sonar-groovy-plugin/src/test/java/org/sonar/plugins/groovy/GroovyPluginTest.java b/sonar-groovy-plugin/src/test/java/org/sonar/plugins/groovy/GroovyPluginTest.java index bf2c1e57..8f606859 100644 --- a/sonar-groovy-plugin/src/test/java/org/sonar/plugins/groovy/GroovyPluginTest.java +++ b/sonar-groovy-plugin/src/test/java/org/sonar/plugins/groovy/GroovyPluginTest.java @@ -21,16 +21,24 @@ import org.junit.Test; import org.sonar.api.Plugin; +import org.sonar.api.SonarQubeSide; import org.sonar.api.SonarQubeVersion; +import org.sonar.api.SonarRuntime; +import org.sonar.api.internal.SonarRuntimeImpl; +import org.sonar.api.utils.Version; import static org.assertj.core.api.Assertions.assertThat; public class GroovyPluginTest { + public static final Version VERSION_7_4 = Version.create(7, 4); + @Test public void testExtensions() { + SonarRuntime runtime = SonarRuntimeImpl.forSonarQube(VERSION_7_4, SonarQubeSide.SERVER); + GroovyPlugin plugin = new GroovyPlugin(); - Plugin.Context context = new Plugin.Context(SonarQubeVersion.V5_6); + Plugin.Context context = new Plugin.Context(runtime); plugin.define(context); assertThat(context.getExtensions()).hasSize(17); } diff --git a/sonar-groovy-plugin/src/test/java/org/sonar/plugins/groovy/GroovySensorTest.java b/sonar-groovy-plugin/src/test/java/org/sonar/plugins/groovy/GroovySensorTest.java index ca086141..85f8437d 100644 --- a/sonar-groovy-plugin/src/test/java/org/sonar/plugins/groovy/GroovySensorTest.java +++ b/sonar-groovy-plugin/src/test/java/org/sonar/plugins/groovy/GroovySensorTest.java @@ -22,12 +22,11 @@ import org.junit.Test; import org.mockito.Matchers; import org.mockito.Mockito; -import org.sonar.api.batch.fs.internal.DefaultFileSystem; -import org.sonar.api.batch.fs.internal.DefaultInputDir; -import org.sonar.api.batch.fs.internal.DefaultInputFile; +import org.sonar.api.batch.fs.internal.*; import org.sonar.api.batch.sensor.internal.DefaultSensorDescriptor; import org.sonar.api.batch.sensor.internal.SensorContextTester; import org.sonar.api.config.Settings; +import org.sonar.api.config.internal.MapSettings; import org.sonar.api.measures.CoreMetrics; import org.sonar.api.measures.FileLinesContext; import org.sonar.api.measures.FileLinesContextFactory; @@ -35,7 +34,9 @@ import java.io.File; import java.io.IOException; +import java.nio.charset.StandardCharsets; import java.nio.file.Files; +import java.nio.file.Paths; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.any; @@ -44,15 +45,19 @@ public class GroovySensorTest { - private Settings settings = new Settings(); + private Settings settings = new MapSettings(); + private FileLinesContextFactory fileLinesContextFactory = mock(FileLinesContextFactory.class); + private DefaultFileSystem fileSystem = new DefaultFileSystem(new File(".")); + private GroovySensor sensor = new GroovySensor(settings, fileLinesContextFactory, fileSystem); @Test - public void do_nothing_when_no_groovy_file() throws IOException { - SensorContextTester context = SensorContextTester.create(new File("")); + public void do_nothing_when_no_groovy_file() { + SensorContextTester context = SensorContextTester.create(new File(".")); context = Mockito.spy(context); + sensor = new GroovySensor(settings, fileLinesContextFactory, context.fileSystem()); sensor.execute(context); @@ -71,17 +76,20 @@ public void compute_metrics_ignoring_header_comment() throws IOException { private void testMetrics(boolean headerComment, int expectedCommentMetric) throws IOException { settings.appendProperty(GroovyPlugin.IGNORE_HEADER_COMMENTS, "" + headerComment); - File sourceDir = new File("src/test/resources/org/sonar/plugins/groovy/gmetrics"); - SensorContextTester context = SensorContextTester.create(new File("")); + SensorContextTester context = SensorContextTester.create(new File("src/test/resources")); + + File sourceDir = new File("src/test/resources/org/sonar/plugins/groovy/gmetrics"); File sourceFile = new File(sourceDir, "Greeting.groovy"); + fileSystem = context.fileSystem(); fileSystem.add(new DefaultInputDir("", sourceDir.getPath())); - DefaultInputFile groovyFile = new DefaultInputFile("", sourceFile.getPath()) - .setLanguage(Groovy.KEY) - .initMetadata(new String(Files.readAllBytes(sourceFile.toPath()), "UTF-8")); + + Metadata metadata = new FileMetadata().readMetadata( + Files.newBufferedReader(sourceFile.toPath(), StandardCharsets.UTF_8) + ); + DefaultInputFile groovyFile = new DefaultInputFile(getIndexedFile(sourceFile.getPath()), f -> f.setMetadata(metadata)); fileSystem.add(groovyFile); - fileSystem.add(new DefaultInputFile("", "unknownFile.groovy").setLanguage(Groovy.KEY)); FileLinesContext fileLinesContext = mock(FileLinesContext.class); when(fileLinesContextFactory.createFor(any(DefaultInputFile.class))).thenReturn(fileLinesContext); @@ -90,21 +98,10 @@ private void testMetrics(boolean headerComment, int expectedCommentMetric) throw sensor.execute(context); String key = groovyFile.key(); - assertThat(context.measure(key, CoreMetrics.FILES).value()).isEqualTo(1); - assertThat(context.measure(key, CoreMetrics.CLASSES).value()).isEqualTo(2); - assertThat(context.measure(key, CoreMetrics.FUNCTIONS).value()).isEqualTo(2); - assertThat(context.measure(key, CoreMetrics.LINES).value()).isEqualTo(33); assertThat(context.measure(key, CoreMetrics.NCLOC).value()).isEqualTo(17); assertThat(context.measure(key, CoreMetrics.COMMENT_LINES).value()).isEqualTo(expectedCommentMetric); - assertThat(context.measure(key, CoreMetrics.COMPLEXITY).value()).isEqualTo(4); - assertThat(context.measure(key, CoreMetrics.COMPLEXITY_IN_CLASSES).value()).isEqualTo(4); - assertThat(context.measure(key, CoreMetrics.COMPLEXITY_IN_FUNCTIONS).value()).isEqualTo(4); - - assertThat(context.measure(key, CoreMetrics.FUNCTION_COMPLEXITY_DISTRIBUTION).value()).isEqualTo("1=0;2=2;4=0;6=0;8=0;10=0;12=0"); - assertThat(context.measure(key, CoreMetrics.FILE_COMPLEXITY_DISTRIBUTION).value()).isEqualTo("0=1;5=0;10=0;20=0;30=0;60=0;90=0"); - // 11 times for comment because we register comment even when ignoring header comment Mockito.verify(fileLinesContext, Mockito.times(11)).setIntValue(Mockito.eq(CoreMetrics.COMMENT_LINES_DATA_KEY), Matchers.anyInt(), Mockito.eq(1)); Mockito.verify(fileLinesContext, Mockito.times(17)).setIntValue(Mockito.eq(CoreMetrics.NCLOC_DATA_KEY), Matchers.anyInt(), Mockito.eq(1)); @@ -114,48 +111,6 @@ private void testMetrics(boolean headerComment, int expectedCommentMetric) throw Mockito.verify(fileLinesContext, Mockito.times(1)).save(); } - @Test - public void compute_coupling_metrics() throws IOException { - SensorContextTester context = SensorContextTester.create(new File("")); - - fileSystem = context.fileSystem(); - // package 'org' contains class 'Greeting', used by no other class, but using classes 'Bar' and 'Foo' - DefaultInputDir org = addFileWithParentFolder("src/test/resources/org/sonar/plugins/groovy/gmetricswithcoupling/org", "Greeting.groovy"); - // package 'org.foo' contains class 'Foo', used by class 'Greeting', and using class 'Bar' - DefaultInputDir org_foo = addFileWithParentFolder("src/test/resources/org/sonar/plugins/groovy/gmetricswithcoupling/org/foo", "Foo.groovy"); - // package 'org.bar' contains class 'Bar', used by classes 'Greeting' and 'Foo', but using no other class - DefaultInputDir org_bar = addFileWithParentFolder("src/test/resources/org/sonar/plugins/groovy/gmetricswithcoupling/org/bar", "Bar.groovy"); - - FileLinesContext fileLinesContext = mock(FileLinesContext.class); - when(fileLinesContextFactory.createFor(any(DefaultInputFile.class))).thenReturn(fileLinesContext); - - sensor = new GroovySensor(settings, fileLinesContextFactory, fileSystem); - sensor.execute(context); - - assertCouplingMeasureAre(context, org.key(), 3, 1.0, 3, 1.0); - assertCouplingMeasureAre(context, org_foo.key(), 1, 1.0, 1, 1.0); - assertCouplingMeasureAre(context, org_bar.key(), 2, 2.0, 0, 0.0); - } - - private static void assertCouplingMeasureAre(SensorContextTester context, String key, Object afferentTot, Object afferentAvg, Object efferentTot, Object efferentAvg) { - assertThat(context.measure(key, GroovyMetrics.AFFERENT_COUPLING_TOTAL.key()).value()).isEqualTo(afferentTot); - assertThat(context.measure(key, GroovyMetrics.AFFERENT_COUPLING_AVERAGE.key()).value()).isEqualTo(afferentAvg); - - assertThat(context.measure(key, GroovyMetrics.EFFERENT_COUPLING_TOTAL.key()).value()).isEqualTo(efferentTot); - assertThat(context.measure(key, GroovyMetrics.EFFERENT_COUPLING_AVERAGE.key()).value()).isEqualTo(efferentAvg); - } - - private DefaultInputDir addFileWithParentFolder(String dirPath, String fileName) throws IOException { - File dir = new File(dirPath); - File file = new File(dir, fileName); - DefaultInputDir inputDir = new DefaultInputDir("", dir.getPath()); - fileSystem.add(inputDir); - fileSystem.add(new DefaultInputFile("", file.getPath()) - .setLanguage(Groovy.KEY) - .initMetadata(new String(Files.readAllBytes(file.toPath()), "UTF-8"))); - return inputDir; - } - @Test public void test_toString() { assertThat(sensor.toString()).isEqualTo("GroovySensor"); @@ -168,4 +123,8 @@ public void test_description() { assertThat(defaultSensorDescriptor.languages()).containsOnly(Groovy.KEY); } + private static DefaultIndexedFile getIndexedFile(String path) { + return new DefaultIndexedFile("", Paths.get("."), path, Groovy.KEY); + } + } diff --git a/sonar-groovy-plugin/src/test/java/org/sonar/plugins/groovy/cobertura/CoberturaSensorTest.java b/sonar-groovy-plugin/src/test/java/org/sonar/plugins/groovy/cobertura/CoberturaSensorTest.java index 2e4f48ce..34f6c0a3 100644 --- a/sonar-groovy-plugin/src/test/java/org/sonar/plugins/groovy/cobertura/CoberturaSensorTest.java +++ b/sonar-groovy-plugin/src/test/java/org/sonar/plugins/groovy/cobertura/CoberturaSensorTest.java @@ -19,9 +19,6 @@ */ package org.sonar.plugins.groovy.cobertura; -import java.io.File; -import java.util.HashMap; -import java.util.Map; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentMatchers; @@ -32,17 +29,23 @@ import org.sonar.api.batch.fs.FilePredicates; import org.sonar.api.batch.fs.FileSystem; import org.sonar.api.batch.fs.InputFile; -import org.sonar.api.batch.fs.InputFile.Type; import org.sonar.api.batch.fs.internal.DefaultFileSystem; +import org.sonar.api.batch.fs.internal.DefaultIndexedFile; import org.sonar.api.batch.fs.internal.DefaultInputFile; +import org.sonar.api.batch.fs.internal.Metadata; import org.sonar.api.batch.sensor.SensorContext; -import org.sonar.api.batch.sensor.coverage.CoverageType; import org.sonar.api.batch.sensor.internal.DefaultSensorDescriptor; import org.sonar.api.batch.sensor.internal.SensorContextTester; import org.sonar.api.config.Settings; +import org.sonar.api.config.internal.MapSettings; import org.sonar.plugins.groovy.GroovyPlugin; import org.sonar.plugins.groovy.foundation.Groovy; +import java.io.File; +import java.nio.file.Paths; +import java.util.HashMap; +import java.util.Map; + import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; @@ -55,8 +58,8 @@ public class CoberturaSensorTest { private DefaultFileSystem fileSystem; @Before - public void setUp() throws Exception { - settings = new Settings(); + public void setUp() { + settings = new MapSettings(); settings.setProperty(GroovyPlugin.COBERTURA_REPORT_PATH, "src/test/resources/org/sonar/plugins/groovy/cobertura/coverage.xml"); fileSystem = new DefaultFileSystem(new File(".")); sensor = new CoberturaSensor(settings, fileSystem); @@ -90,12 +93,9 @@ public boolean apply(InputFile inputFile) { } } - when(fp.hasAbsolutePath(ArgumentMatchers.anyString())).thenAnswer(new Answer() { - @Override - public FilePredicate answer(InvocationOnMock invocation) throws Throwable { - return new CustomFilePredicate(invocation.getArgument(0)); - } - }); + when(fp.hasAbsolutePath(ArgumentMatchers.anyString())).thenAnswer( + (Answer) invocation -> new CustomFilePredicate(invocation.getArgument(0)) + ); FileSystem mockfileSystem = mock(FileSystem.class); when(mockfileSystem.predicates()).thenReturn(fp); @@ -111,18 +111,25 @@ public InputFile answer(InvocationOnMock invocation) throws Throwable { if (firstCall) { // The first class in the test coverage.xml is a java class and the rest are groovy firstCall = false; - return new DefaultInputFile("", "fake.java").setLanguage("java"); + return new DefaultInputFile(getIndexedFile("fake.java", "java"), f -> { + f.setMetadata(new Metadata(Integer.MAX_VALUE, 0, "", new int[0],new int[0], 0)); + }); } + String fileName = invocation.getArgument(0).fileName; + DefaultInputFile groovyFile; if (!groovyFilesByName.containsKey(fileName)) { // store groovy file as default input files - groovyFile = new DefaultInputFile("", fileName).setLanguage(Groovy.KEY).setType(Type.MAIN).setLines(Integer.MAX_VALUE); + groovyFile = new DefaultInputFile(getIndexedFile(fileName, Groovy.KEY), f -> { + f.setMetadata(new Metadata(Integer.MAX_VALUE, 0, "", new int[0],new int[0],0)); + }); groovyFilesByName.put(fileName, groovyFile); } return groovyFilesByName.get(fileName); } }); + sensor = new CoberturaSensor(settings, mockfileSystem); SensorContextTester context = SensorContextTester.create(new File("")); @@ -134,14 +141,14 @@ public InputFile answer(InvocationOnMock invocation) throws Throwable { int[] lineNoHits = {9, 10, 11}; for (int line : lineHits) { - assertThat(context.lineHits(filekey, CoverageType.UNIT, line)).isEqualTo(1); + assertThat(context.lineHits(filekey, line)).isEqualTo(1); } for (int line : lineNoHits) { - assertThat(context.lineHits(filekey, CoverageType.UNIT, line)).isEqualTo(0); + assertThat(context.lineHits(filekey, line)).isEqualTo(0); } // No value for java file - assertThat(context.lineHits(":/Users/cpicat/myproject/grails-app/domain/com/test/web/EmptyResultException.java", CoverageType.UNIT, 16)).isNull(); + assertThat(context.lineHits(":/Users/cpicat/myproject/grails-app/domain/com/test/web/EmptyResultException.java", 16)).isNull(); } @Test @@ -160,8 +167,8 @@ public void should_not_save_any_measure_if_files_can_not_be_found() { @Test public void should_not_parse_report_if_settings_does_not_contain_report_path() { DefaultFileSystem fileSystem = new DefaultFileSystem(new File(".")); - fileSystem.add(new DefaultInputFile("", "fake.groovy").setLanguage(Groovy.KEY)); - sensor = new CoberturaSensor(new Settings(), fileSystem); + fileSystem.add(new DefaultInputFile(getIndexedFile("fake.groovy", Groovy.KEY), f -> {})); + sensor = new CoberturaSensor(new MapSettings(), fileSystem); SensorContext context = mock(SensorContext.class); sensor.execute(context); @@ -171,11 +178,13 @@ public void should_not_parse_report_if_settings_does_not_contain_report_path() { @Test public void should_not_parse_report_if_report_does_not_exist() { - Settings settings = new Settings(); + Settings settings = new MapSettings(); settings.setProperty(GroovyPlugin.COBERTURA_REPORT_PATH, "org/sonar/plugins/groovy/cobertura/fake-coverage.xml"); DefaultFileSystem fileSystem = new DefaultFileSystem(new File(".")); - fileSystem.add(new DefaultInputFile("", "fake.groovy").setLanguage(Groovy.KEY)); + + + fileSystem.add(new DefaultInputFile(getIndexedFile("fake.groovy", Groovy.KEY), f -> {})); sensor = new CoberturaSensor(settings, fileSystem); @@ -187,11 +196,11 @@ public void should_not_parse_report_if_report_does_not_exist() { @Test public void should_use_relative_path_to_get_report() { - Settings settings = new Settings(); + Settings settings = new MapSettings(); settings.setProperty(GroovyPlugin.COBERTURA_REPORT_PATH, "//org/sonar/plugins/groovy/cobertura/fake-coverage.xml"); DefaultFileSystem fileSystem = new DefaultFileSystem(new File(".")); - fileSystem.add(new DefaultInputFile("", "fake.groovy").setLanguage(Groovy.KEY)); + fileSystem.add(new DefaultInputFile(getIndexedFile("fake.groovy", Groovy.KEY), f -> {})); sensor = new CoberturaSensor(settings, fileSystem); @@ -203,7 +212,7 @@ public void should_use_relative_path_to_get_report() { @Test public void should_execute_on_project() { - fileSystem.add(new DefaultInputFile("", "fake.groovy").setLanguage(Groovy.KEY)); + fileSystem.add(new DefaultInputFile(getIndexedFile("fake.groovy", Groovy.KEY), f -> {})); assertThat(sensor.shouldExecuteOnProject()).isTrue(); } @@ -217,4 +226,8 @@ public void test_toString() { assertThat(sensor.toString()).isEqualTo("Groovy CoberturaSensor"); } -} + private static DefaultIndexedFile getIndexedFile(String path, String language) { + return new DefaultIndexedFile("", Paths.get("."), path, language); + } + +} \ No newline at end of file diff --git a/sonar-groovy-plugin/src/test/java/org/sonar/plugins/groovy/codenarc/CodeNarcSensorTest.java b/sonar-groovy-plugin/src/test/java/org/sonar/plugins/groovy/codenarc/CodeNarcSensorTest.java index 5f18ff20..307cc9de 100644 --- a/sonar-groovy-plugin/src/test/java/org/sonar/plugins/groovy/codenarc/CodeNarcSensorTest.java +++ b/sonar-groovy-plugin/src/test/java/org/sonar/plugins/groovy/codenarc/CodeNarcSensorTest.java @@ -19,11 +19,10 @@ */ package org.sonar.plugins.groovy.codenarc; -import java.io.File; -import java.io.IOException; -import java.io.UnsupportedEncodingException; +import java.io.*; import java.nio.charset.StandardCharsets; import java.nio.file.Files; +import java.nio.file.Path; import java.util.Arrays; import java.util.regex.Pattern; import org.apache.commons.io.FileUtils; @@ -31,12 +30,16 @@ import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.sonar.api.batch.fs.InputFile.Type; +import org.sonar.api.batch.fs.internal.DefaultIndexedFile; import org.sonar.api.batch.fs.internal.DefaultInputFile; +import org.sonar.api.batch.fs.internal.FileMetadata; +import org.sonar.api.batch.fs.internal.Metadata; import org.sonar.api.batch.rule.internal.ActiveRulesBuilder; import org.sonar.api.batch.sensor.internal.DefaultSensorDescriptor; import org.sonar.api.batch.sensor.internal.SensorContextTester; import org.sonar.api.config.PropertyDefinitions; import org.sonar.api.config.Settings; +import org.sonar.api.config.internal.MapSettings; import org.sonar.api.profiles.RulesProfile; import org.sonar.api.rule.RuleKey; import org.sonar.api.rules.ActiveRule; @@ -61,12 +64,13 @@ public class CodeNarcSensorTest { @Before public void setUp() throws Exception { - sensorContextTester = SensorContextTester.create(temp.newFolder()); - sensorContextTester.fileSystem().setWorkDir(temp.newFolder()); + sensorContextTester = SensorContextTester.create(temp.newFolder().toPath()); + sensorContextTester.fileSystem().setWorkDir(temp.newFolder().toPath()); profile = mock(RulesProfile.class); - sensorContextTester.setSettings(new Settings(new PropertyDefinitions(GroovyPlugin.class))); + + sensorContextTester.setSettings(new MapSettings(new PropertyDefinitions(GroovyPlugin.class))); groovy = new Groovy(sensorContextTester.settings()); sensor = new CodeNarcSensor(profile, new GroovyFileSystem(sensorContextTester.fileSystem())); } @@ -213,21 +217,28 @@ private File getReportWithUpdatedSourceDir() throws IOException { private void addFileWithFakeContent(String path) throws UnsupportedEncodingException, IOException { File sampleFile = FileUtils.toFile(getClass().getResource("parsing/Sample.groovy")); - sensorContextTester.fileSystem().add(new DefaultInputFile(sensorContextTester.module().key(), path) - .setLanguage(Groovy.KEY) - .setType(Type.MAIN) - .initMetadata(new String(Files.readAllBytes(sampleFile.toPath()), "UTF-8"))); + DefaultIndexedFile indexedFile = getIndexedFile(path); + + Metadata metadata = new FileMetadata().readMetadata( + new FileInputStream(sampleFile), StandardCharsets.UTF_8, sampleFile.getName() + ); + + sensorContextTester.fileSystem().add(new DefaultInputFile(indexedFile, f -> f.setMetadata(metadata))); } - private void addFileWithContent(String path, String content) throws UnsupportedEncodingException, IOException { - DefaultInputFile inputFile = new DefaultInputFile(sensorContextTester.module().key(), path) - .setLanguage(Groovy.KEY) - .setType(Type.MAIN) - .initMetadata(content); + private void addFileWithContent(String path, String content) throws IOException { + Metadata metadata = new FileMetadata().readMetadata(new StringReader(content)); + DefaultInputFile inputFile = new DefaultInputFile(getIndexedFile(path), f -> f.setMetadata(metadata)); + sensorContextTester.fileSystem().add(inputFile); FileUtils.write(inputFile.file(), content, StandardCharsets.UTF_8); } + private DefaultIndexedFile getIndexedFile(String path) throws IOException { + Path baseDir = temp.newFolder().toPath(); + return new DefaultIndexedFile("ABCDE", baseDir, path, Groovy.KEY); + } + private static ActiveRulesBuilder activateFakeRule(ActiveRulesBuilder activeRulesBuilder, String ruleKey) { return activateRule(activeRulesBuilder, ruleKey, ruleKey); } diff --git a/sonar-groovy-plugin/src/test/java/org/sonar/plugins/groovy/foundation/GroovyFileSystemTest.java b/sonar-groovy-plugin/src/test/java/org/sonar/plugins/groovy/foundation/GroovyFileSystemTest.java index ffd82e83..009b21be 100644 --- a/sonar-groovy-plugin/src/test/java/org/sonar/plugins/groovy/foundation/GroovyFileSystemTest.java +++ b/sonar-groovy-plugin/src/test/java/org/sonar/plugins/groovy/foundation/GroovyFileSystemTest.java @@ -21,11 +21,13 @@ import org.junit.Before; import org.junit.Test; -import org.sonar.api.batch.fs.InputFile.Type; +import org.sonar.api.batch.fs.InputFile; import org.sonar.api.batch.fs.internal.DefaultFileSystem; +import org.sonar.api.batch.fs.internal.DefaultIndexedFile; import org.sonar.api.batch.fs.internal.DefaultInputFile; import java.io.File; +import java.nio.file.Paths; import static org.assertj.core.api.Assertions.assertThat; @@ -44,10 +46,10 @@ public void setUp() { public void isEnabled() { assertThat(groovyFileSystem.hasGroovyFiles()).isFalse(); - fileSystem.add(new DefaultInputFile("", "fake.file")); + fileSystem.add(createFakeFile("fake.file", "txt")); assertThat(groovyFileSystem.hasGroovyFiles()).isFalse(); - fileSystem.add(new DefaultInputFile("", "fake.groovy").setLanguage(Groovy.KEY)); + fileSystem.add(createFakeFile("fake.groovy", Groovy.KEY)); assertThat(groovyFileSystem.hasGroovyFiles()).isTrue(); } @@ -55,10 +57,10 @@ public void isEnabled() { public void getSourceFile() { assertThat(groovyFileSystem.sourceFiles()).isEmpty(); - fileSystem.add(new DefaultInputFile("", "fake.file")); + fileSystem.add(createFakeFile("fake.file", "txt")); assertThat(groovyFileSystem.sourceFiles()).isEmpty(); - fileSystem.add(new DefaultInputFile("", "fake.groovy").setLanguage(Groovy.KEY)); + fileSystem.add(createFakeFile("fake.groovy", Groovy.KEY)); assertThat(groovyFileSystem.sourceFiles()).hasSize(1); } @@ -66,13 +68,20 @@ public void getSourceFile() { public void inputFileFromRelativePath() { assertThat(groovyFileSystem.sourceInputFileFromRelativePath(null)).isNull(); - fileSystem.add(new DefaultInputFile("", "fake1.file")); + fileSystem.add(createFakeFile("fake1.file", "txt")); assertThat(groovyFileSystem.sourceInputFileFromRelativePath("fake1.file")).isNull(); - fileSystem.add(new DefaultInputFile("", "fake2.file").setType(Type.MAIN).setLanguage(Groovy.KEY)); + fileSystem.add(createFakeFile("fake2.file", Groovy.KEY)); assertThat(groovyFileSystem.sourceInputFileFromRelativePath("fake2.file")).isNotNull(); - fileSystem.add(new DefaultInputFile("", "org/sample/foo/fake3.file").setType(Type.MAIN).setLanguage(Groovy.KEY)); + fileSystem.add(createFakeFile("org/sample/foo/fake3.file", Groovy.KEY)); assertThat(groovyFileSystem.sourceInputFileFromRelativePath("foo/fake3.file")).isNotNull(); } + + private static InputFile createFakeFile(String path, String language) { + DefaultIndexedFile indexedFile = new DefaultIndexedFile("ABCDE", Paths.get("."), path, language); + + return new DefaultInputFile(indexedFile, f -> {}); + } } + diff --git a/sonar-groovy-plugin/src/test/java/org/sonar/plugins/groovy/foundation/GroovyHighlighterAndTokenizerTest.java b/sonar-groovy-plugin/src/test/java/org/sonar/plugins/groovy/foundation/GroovyHighlighterAndTokenizerTest.java index 3d660254..73929074 100644 --- a/sonar-groovy-plugin/src/test/java/org/sonar/plugins/groovy/foundation/GroovyHighlighterAndTokenizerTest.java +++ b/sonar-groovy-plugin/src/test/java/org/sonar/plugins/groovy/foundation/GroovyHighlighterAndTokenizerTest.java @@ -20,11 +20,16 @@ package org.sonar.plugins.groovy.foundation; import java.io.File; +import java.io.FileInputStream; +import java.nio.charset.StandardCharsets; import java.nio.file.Files; import org.junit.Test; import org.mockito.Mockito; import org.sonar.api.batch.fs.InputFile.Type; +import org.sonar.api.batch.fs.internal.DefaultIndexedFile; import org.sonar.api.batch.fs.internal.DefaultInputFile; +import org.sonar.api.batch.fs.internal.FileMetadata; +import org.sonar.api.batch.fs.internal.Metadata; import org.sonar.api.batch.sensor.highlighting.TypeOfText; import org.sonar.api.batch.sensor.internal.SensorContextTester; import org.sonar.plugins.groovy.TestUtils; @@ -37,11 +42,16 @@ public class GroovyHighlighterAndTokenizerTest { public void should_highlight_keywords() throws Exception { File file = TestUtils.getResource("/org/sonar/plugins/groovy/foundation/Greet.groovy"); + Metadata metadata = new FileMetadata().readMetadata( + new FileInputStream(file), StandardCharsets.UTF_8, file.getName()); + + DefaultIndexedFile indexedFile = new DefaultIndexedFile( + "", file.toPath().getParent(), "Greet.groovy", Groovy.KEY + ); + SensorContextTester context = SensorContextTester.create(file.getParentFile()); - DefaultInputFile inputFile = new DefaultInputFile("", "Greet.groovy") - .setLanguage(Groovy.KEY) - .setType(Type.MAIN) - .initMetadata(new String(Files.readAllBytes(file.toPath()), "UTF-8")); + DefaultInputFile inputFile = new DefaultInputFile(indexedFile, f -> f.setMetadata(metadata)); + context.fileSystem().add(inputFile); GroovyHighlighterAndTokenizer highlighter = new GroovyHighlighterAndTokenizer(inputFile); @@ -68,11 +78,17 @@ public void should_highlight_keywords() throws Exception { public void should_tokenize_for_cpd() throws Exception { File file = TestUtils.getResource("/org/sonar/plugins/groovy/foundation/Greet.groovy"); + Metadata metadata = new FileMetadata().readMetadata( + new FileInputStream(file), StandardCharsets.UTF_8, file.getName() + ); + + DefaultIndexedFile indexedFile = new DefaultIndexedFile( + "", file.toPath().getParent(), "Greet.groovy", Groovy.KEY + ); + SensorContextTester context = SensorContextTester.create(file.getParentFile()); - DefaultInputFile inputFile = new DefaultInputFile("", "Greet.groovy") - .setLanguage(Groovy.KEY) - .setType(Type.MAIN) - .initMetadata(new String(Files.readAllBytes(file.toPath()), "UTF-8")); + DefaultInputFile inputFile = new DefaultInputFile(indexedFile, f -> f.setMetadata(metadata)); + context.fileSystem().add(inputFile); GroovyHighlighterAndTokenizer highlighter = new GroovyHighlighterAndTokenizer(inputFile); @@ -80,15 +96,15 @@ public void should_tokenize_for_cpd() throws Exception { highlighter.processFile(context); assertThat(context.cpdTokens(":Greet.groovy")).extracting("value").containsExactly("classGreet{", - "defname", - "Greet(who){name=who}", - "defsalute(){printlnLITERALnameLITERALnameLITERAL}", - "}", - "/** * Javadoc style */", - "@groovy.beans.Bindable", - "classCool{", - "doublex=1.4// Comment", - "}"); + "defname", + "Greet(who){name=who}", + "defsalute(){printlnLITERALnameLITERALnameLITERAL}", + "}", + "/** * Javadoc style */", + "@groovy.beans.Bindable", + "classCool{", + "doublex=1.4// Comment", + "}"); Mockito.verify(context, Mockito.times(1)).newCpdTokens(); } @@ -96,10 +112,17 @@ public void should_tokenize_for_cpd() throws Exception { public void should_highlight_nothing_if_file_is_missing() throws Exception { File file = TestUtils.getResource("/org/sonar/plugins/groovy/foundation/Greet.groovy"); + Metadata metadata = new FileMetadata().readMetadata( + new FileInputStream(file), StandardCharsets.UTF_8, file.getName() + ); + + DefaultIndexedFile indexedFile = new DefaultIndexedFile( + "", file.toPath().getParent(), "Greet-fake.groovy", Groovy.KEY + ); + SensorContextTester context = SensorContextTester.create(file.getParentFile()); - DefaultInputFile inputFile = new DefaultInputFile("", "Greet-fake.groovy") - .setLanguage(Groovy.KEY) - .setType(Type.MAIN); + DefaultInputFile inputFile = new DefaultInputFile(indexedFile, f -> f.setMetadata(metadata)); + context.fileSystem().add(inputFile); GroovyHighlighterAndTokenizer highlighter = new GroovyHighlighterAndTokenizer(inputFile); @@ -114,11 +137,17 @@ public void should_highlight_nothing_if_file_is_missing() throws Exception { public void should_highlight_only_partially_if_file_can_not_be_lexed() throws Exception { File file = TestUtils.getResource("/org/sonar/plugins/groovy/foundation/Error.groovy"); + Metadata metadata = new FileMetadata().readMetadata( + new FileInputStream(file), StandardCharsets.UTF_8, file.getName() + ); + + DefaultIndexedFile indexedFile = new DefaultIndexedFile( + "", file.toPath().getParent(), "Error.groovy", Groovy.KEY + ); + + DefaultInputFile inputFile = new DefaultInputFile(indexedFile, f -> f.setMetadata(metadata)); + SensorContextTester context = SensorContextTester.create(file.getParentFile()); - DefaultInputFile inputFile = new DefaultInputFile("", "Error.groovy") - .setLanguage(Groovy.KEY) - .setType(Type.MAIN) - .initMetadata(new String(Files.readAllBytes(file.toPath()), "UTF-8")); context.fileSystem().add(inputFile); GroovyHighlighterAndTokenizer highlighter = new GroovyHighlighterAndTokenizer(inputFile); diff --git a/sonar-groovy-plugin/src/test/java/org/sonar/plugins/groovy/foundation/GroovyTest.java b/sonar-groovy-plugin/src/test/java/org/sonar/plugins/groovy/foundation/GroovyTest.java index a1c82dca..b499db5c 100644 --- a/sonar-groovy-plugin/src/test/java/org/sonar/plugins/groovy/foundation/GroovyTest.java +++ b/sonar-groovy-plugin/src/test/java/org/sonar/plugins/groovy/foundation/GroovyTest.java @@ -21,6 +21,7 @@ import org.junit.Test; import org.sonar.api.config.Settings; +import org.sonar.api.config.internal.MapSettings; import org.sonar.plugins.groovy.GroovyPlugin; import static org.assertj.core.api.Assertions.assertThat; @@ -29,7 +30,7 @@ public class GroovyTest { @Test public void test() { - Settings settings = new Settings(); + Settings settings = new MapSettings(); Groovy language = new Groovy(settings); assertThat(language.getKey()).isEqualTo("grvy"); assertThat(language.getName()).isEqualTo("Groovy"); diff --git a/sonar-groovy-plugin/src/test/java/org/sonar/plugins/groovy/jacoco/JaCoCoConfigurationTest.java b/sonar-groovy-plugin/src/test/java/org/sonar/plugins/groovy/jacoco/JaCoCoConfigurationTest.java index 3c017460..a84eba42 100644 --- a/sonar-groovy-plugin/src/test/java/org/sonar/plugins/groovy/jacoco/JaCoCoConfigurationTest.java +++ b/sonar-groovy-plugin/src/test/java/org/sonar/plugins/groovy/jacoco/JaCoCoConfigurationTest.java @@ -22,12 +22,15 @@ import org.junit.Before; import org.junit.Test; import org.sonar.api.batch.fs.internal.DefaultFileSystem; +import org.sonar.api.batch.fs.internal.DefaultIndexedFile; import org.sonar.api.batch.fs.internal.DefaultInputFile; import org.sonar.api.config.PropertyDefinitions; import org.sonar.api.config.Settings; +import org.sonar.api.config.internal.MapSettings; import org.sonar.plugins.groovy.foundation.Groovy; import java.io.File; +import java.nio.file.Paths; import static org.assertj.core.api.Assertions.assertThat; @@ -39,7 +42,9 @@ public class JaCoCoConfigurationTest { @Before public void setUp() { - settings = new Settings(new PropertyDefinitions().addComponents(JaCoCoConfiguration.getPropertyDefinitions())); + settings = new MapSettings( + new PropertyDefinitions().addComponents(JaCoCoConfiguration.getPropertyDefinitions()) + ); fileSystem = new DefaultFileSystem(new File(".")); jacocoSettings = new JaCoCoConfiguration(settings, fileSystem); } @@ -50,11 +55,11 @@ public void shouldExecuteOnProject() throws Exception { assertThat(jacocoSettings.shouldExecuteOnProject(true)).isFalse(); assertThat(jacocoSettings.shouldExecuteOnProject(false)).isFalse(); - fileSystem.add(new DefaultInputFile("", "src/foo/bar.java").setLanguage("java")); + fileSystem.add(new DefaultInputFile(getIndexedFile("src/foo/bar.java", "java"), f -> {})); assertThat(jacocoSettings.shouldExecuteOnProject(true)).isFalse(); assertThat(jacocoSettings.shouldExecuteOnProject(false)).isFalse(); - fileSystem.add(new DefaultInputFile("", "src/foo/bar.groovy").setLanguage(Groovy.KEY)); + fileSystem.add(new DefaultInputFile(getIndexedFile("src/foo/bar.groovy", Groovy.KEY), f -> {})); assertThat(jacocoSettings.shouldExecuteOnProject(true)).isTrue(); assertThat(jacocoSettings.shouldExecuteOnProject(false)).isFalse(); @@ -80,4 +85,8 @@ public void shouldReturnReportPathWhenModified() { settings.setProperty(JaCoCoConfiguration.REPORT_PATH_PROPERTY, "jacoco.exec"); assertThat(jacocoSettings.getReportPath()).isEqualTo("jacoco.exec"); } + + private static DefaultIndexedFile getIndexedFile(String path, String language) { + return new DefaultIndexedFile("", Paths.get("."), path, language); + } } diff --git a/sonar-groovy-plugin/src/test/java/org/sonar/plugins/groovy/jacoco/JaCoCoItSensorTest.java b/sonar-groovy-plugin/src/test/java/org/sonar/plugins/groovy/jacoco/JaCoCoItSensorTest.java index f908b024..9d24ccba 100644 --- a/sonar-groovy-plugin/src/test/java/org/sonar/plugins/groovy/jacoco/JaCoCoItSensorTest.java +++ b/sonar-groovy-plugin/src/test/java/org/sonar/plugins/groovy/jacoco/JaCoCoItSensorTest.java @@ -19,24 +19,27 @@ */ package org.sonar.plugins.groovy.jacoco; -import java.io.File; import org.apache.commons.io.FileUtils; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentMatchers; -import org.sonar.api.batch.fs.InputFile.Type; import org.sonar.api.batch.fs.internal.DefaultFileSystem; +import org.sonar.api.batch.fs.internal.DefaultIndexedFile; import org.sonar.api.batch.fs.internal.DefaultInputFile; -import org.sonar.api.batch.sensor.coverage.CoverageType; +import org.sonar.api.batch.fs.internal.Metadata; import org.sonar.api.batch.sensor.internal.DefaultSensorDescriptor; import org.sonar.api.batch.sensor.internal.SensorContextTester; import org.sonar.api.config.Settings; +import org.sonar.api.config.internal.MapSettings; import org.sonar.api.scan.filesystem.PathResolver; import org.sonar.plugins.groovy.GroovyPlugin; import org.sonar.plugins.groovy.TestUtils; import org.sonar.plugins.groovy.foundation.Groovy; import org.sonar.plugins.groovy.foundation.GroovyFileSystem; +import java.io.File; +import java.nio.file.Paths; + import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; @@ -61,7 +64,7 @@ public void setUp() throws Exception { FileUtils.copyFile(TestUtils.getResource("/org/sonar/plugins/groovy/jacoco/Hello$InnerClass.class.toCopy"), new File(jacocoExecutionData.getParentFile(), "Hello$InnerClass.class")); - Settings settings = new Settings(); + Settings settings = new MapSettings(); settings.setProperty(GroovyPlugin.SONAR_GROOVY_BINARIES, "."); configuration = mock(JaCoCoConfiguration.class); @@ -70,10 +73,11 @@ public void setUp() throws Exception { when(configuration.getItReportPath()).thenReturn(jacocoExecutionData.getPath()); DefaultFileSystem fileSystem = new DefaultFileSystem(jacocoExecutionData.getParentFile()); - inputFile = new DefaultInputFile("", "example/Hello.groovy") - .setLanguage(Groovy.KEY) - .setType(Type.MAIN); - inputFile.setLines(50); + DefaultIndexedFile abcde = new DefaultIndexedFile("", Paths.get("."), "example/Hello.groovy", Groovy.KEY); + + inputFile = new DefaultInputFile(abcde, f -> f.setMetadata( + new Metadata(50, 0, "", new int[0], new int[0],0) + )); fileSystem.add(inputFile); pathResolver = mock(PathResolver.class); @@ -118,14 +122,14 @@ public void test_read_execution_data() { int[] conditionLines = {14, 29, 30}; for (int zeroHitline : zeroHitlines) { - assertThat(context.lineHits(":example/Hello.groovy", CoverageType.IT, zeroHitline)).isEqualTo(0); + assertThat(context.lineHits(":example/Hello.groovy", zeroHitline)).isEqualTo(0); } for (int oneHitline : oneHitlines) { - assertThat(context.lineHits(":example/Hello.groovy", CoverageType.IT, oneHitline)).isEqualTo(1); + assertThat(context.lineHits(":example/Hello.groovy", oneHitline)).isEqualTo(1); } for (int conditionLine : conditionLines) { - assertThat(context.conditions(":example/Hello.groovy", CoverageType.IT, conditionLine)).isEqualTo(2); - assertThat(context.coveredConditions(":example/Hello.groovy", CoverageType.IT, conditionLine)).isEqualTo(0); + assertThat(context.conditions(":example/Hello.groovy", conditionLine)).isEqualTo(2); + assertThat(context.coveredConditions(":example/Hello.groovy", conditionLine)).isEqualTo(0); } } diff --git a/sonar-groovy-plugin/src/test/java/org/sonar/plugins/groovy/jacoco/JaCoCoOverallSensorTest.java b/sonar-groovy-plugin/src/test/java/org/sonar/plugins/groovy/jacoco/JaCoCoOverallSensorTest.java index 181962f1..11b0e229 100644 --- a/sonar-groovy-plugin/src/test/java/org/sonar/plugins/groovy/jacoco/JaCoCoOverallSensorTest.java +++ b/sonar-groovy-plugin/src/test/java/org/sonar/plugins/groovy/jacoco/JaCoCoOverallSensorTest.java @@ -20,15 +20,20 @@ package org.sonar.plugins.groovy.jacoco; import java.io.File; +import java.nio.file.Paths; + import org.apache.commons.io.FileUtils; import org.junit.Before; import org.junit.Test; import org.sonar.api.batch.fs.InputFile.Type; +import org.sonar.api.batch.fs.internal.DefaultIndexedFile; import org.sonar.api.batch.fs.internal.DefaultInputFile; +import org.sonar.api.batch.fs.internal.Metadata; import org.sonar.api.batch.sensor.coverage.CoverageType; import org.sonar.api.batch.sensor.internal.DefaultSensorDescriptor; import org.sonar.api.batch.sensor.internal.SensorContextTester; import org.sonar.api.config.Settings; +import org.sonar.api.config.internal.MapSettings; import org.sonar.api.scan.filesystem.PathResolver; import org.sonar.plugins.groovy.GroovyPlugin; import org.sonar.plugins.groovy.TestUtils; @@ -60,20 +65,21 @@ public void before() throws Exception { jacocoITData = new File(outputDir, "jacoco-it.exec"); FileUtils.copyFile(TestUtils.getResource("/org/sonar/plugins/groovy/jacoco/Hello.class.toCopy"), - new File(jacocoUTData.getParentFile(), "Hello.class")); + new File(jacocoUTData.getParentFile(), "Hello.class")); FileUtils.copyFile(TestUtils.getResource("/org/sonar/plugins/groovy/jacoco/Hello$InnerClass.class.toCopy"), - new File(jacocoUTData.getParentFile(), "Hello$InnerClass.class")); + new File(jacocoUTData.getParentFile(), "Hello$InnerClass.class")); - settings = new Settings(); + settings = new MapSettings(); settings.setProperty(GroovyPlugin.SONAR_GROOVY_BINARIES, "."); context = SensorContextTester.create(jacocoUTData.getParentFile()); - context.fileSystem().setWorkDir(jacocoUTData.getParentFile()); - inputFile = new DefaultInputFile("", "example/Hello.groovy") - .setLanguage(Groovy.KEY) - .setType(Type.MAIN); - inputFile.setLines(50); + context.fileSystem().setWorkDir(jacocoUTData.getParentFile().toPath()); + + DefaultIndexedFile abcde = new DefaultIndexedFile("ABCDE", Paths.get("."), "example/Hello.groovy", Groovy.KEY); + + inputFile = new DefaultInputFile(abcde, f -> f.setMetadata(new Metadata(50, 0, "", new int[0], new int[0],0))); + context.fileSystem().add(inputFile); configuration = mock(JaCoCoConfiguration.class); @@ -127,16 +133,16 @@ public void test_read_execution_data_with_IT_and_UT() { private void verifyOverallMetrics(SensorContextTester context, int[] zeroHitlines, int[] oneHitlines, int[] conditionLines, int[] coveredConditions) { for (int zeroHitline : zeroHitlines) { - assertThat(context.lineHits(inputFile.key(), CoverageType.OVERALL, zeroHitline)).isEqualTo(0); + assertThat(context.lineHits(inputFile.key(), zeroHitline)).isEqualTo(0); } for (int oneHitline : oneHitlines) { - assertThat(context.lineHits(inputFile.key(), CoverageType.OVERALL, oneHitline)).isEqualTo(1); + assertThat(context.lineHits(inputFile.key(), oneHitline)).isEqualTo(1); } for (int i = 0; i < conditionLines.length; i++) { int line = conditionLines[i]; - assertThat(context.conditions(inputFile.key(), CoverageType.OVERALL, line)).isEqualTo(2); - assertThat(context.coveredConditions(inputFile.key(), CoverageType.OVERALL, line)).isEqualTo(coveredConditions[i]); + assertThat(context.conditions(inputFile.key(), line)).isEqualTo(2); + assertThat(context.coveredConditions(inputFile.key(), line)).isEqualTo(coveredConditions[i]); } } diff --git a/sonar-groovy-plugin/src/test/java/org/sonar/plugins/groovy/jacoco/JaCoCoSensorTest.java b/sonar-groovy-plugin/src/test/java/org/sonar/plugins/groovy/jacoco/JaCoCoSensorTest.java index 25251b70..09941185 100644 --- a/sonar-groovy-plugin/src/test/java/org/sonar/plugins/groovy/jacoco/JaCoCoSensorTest.java +++ b/sonar-groovy-plugin/src/test/java/org/sonar/plugins/groovy/jacoco/JaCoCoSensorTest.java @@ -19,25 +19,30 @@ */ package org.sonar.plugins.groovy.jacoco; -import java.io.File; -import java.io.IOException; import org.apache.commons.io.FileUtils; import org.junit.Before; +import org.junit.Rule; import org.junit.Test; +import org.junit.rules.TemporaryFolder; import org.mockito.ArgumentMatchers; -import org.sonar.api.batch.fs.InputFile.Type; import org.sonar.api.batch.fs.internal.DefaultFileSystem; +import org.sonar.api.batch.fs.internal.DefaultIndexedFile; import org.sonar.api.batch.fs.internal.DefaultInputFile; -import org.sonar.api.batch.sensor.coverage.CoverageType; +import org.sonar.api.batch.fs.internal.Metadata; import org.sonar.api.batch.sensor.internal.DefaultSensorDescriptor; import org.sonar.api.batch.sensor.internal.SensorContextTester; import org.sonar.api.config.Settings; +import org.sonar.api.config.internal.MapSettings; import org.sonar.api.scan.filesystem.PathResolver; import org.sonar.plugins.groovy.GroovyPlugin; import org.sonar.plugins.groovy.TestUtils; import org.sonar.plugins.groovy.foundation.Groovy; import org.sonar.plugins.groovy.foundation.GroovyFileSystem; +import java.io.File; +import java.io.IOException; +import java.nio.file.Paths; + import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; @@ -46,111 +51,115 @@ public class JaCoCoSensorTest { - private File jacocoExecutionData; - private DefaultInputFile inputFile; - private JaCoCoConfiguration configuration; - private PathResolver pathResolver; - private JaCoCoSensor sensor; - - @Before - public void setUp() throws Exception { - this.jacocoExecutionData = initWithJaCoCoVersion("JaCoCoSensor_0_7_4"); - } - - private File initWithJaCoCoVersion(String jacocoVersion) throws IOException { - File outputDir = TestUtils.getResource("/org/sonar/plugins/groovy/jacoco/" + jacocoVersion + "/"); - File jacocoExecutionData = new File(outputDir, "jacoco-ut.exec"); - - FileUtils.copyFile(TestUtils.getResource("/org/sonar/plugins/groovy/jacoco/Hello.class.toCopy"), - new File(jacocoExecutionData.getParentFile(), "Hello.class")); - FileUtils.copyFile(TestUtils.getResource("/org/sonar/plugins/groovy/jacoco/Hello$InnerClass.class.toCopy"), - new File(jacocoExecutionData.getParentFile(), "Hello$InnerClass.class")); - - Settings settings = new Settings(); - settings.setProperty(GroovyPlugin.SONAR_GROOVY_BINARIES, "."); - - configuration = mock(JaCoCoConfiguration.class); - when(configuration.shouldExecuteOnProject(true)).thenReturn(true); - when(configuration.shouldExecuteOnProject(false)).thenReturn(false); - when(configuration.getReportPath()).thenReturn(jacocoExecutionData.getPath()); - - DefaultFileSystem fileSystem = new DefaultFileSystem(jacocoExecutionData.getParentFile()); - inputFile = new DefaultInputFile("", "example/Hello.groovy") - .setLanguage(Groovy.KEY) - .setType(Type.MAIN); - inputFile.setLines(50); - fileSystem.add(inputFile); - - pathResolver = mock(PathResolver.class); - sensor = new JaCoCoSensor(configuration, new GroovyFileSystem(fileSystem), pathResolver, settings); - - return jacocoExecutionData; - } - - @Test - public void test_description() { - DefaultSensorDescriptor defaultSensorDescriptor = new DefaultSensorDescriptor(); - sensor.describe(defaultSensorDescriptor); - assertThat(defaultSensorDescriptor.languages()).containsOnly(Groovy.KEY); - } - - @Test - public void should_Execute_On_Project_only_if_exec_exists() { - when(configuration.getReportPath()).thenReturn("ut.exec"); - - when(pathResolver.relativeFile(any(File.class), eq("ut.exec"))).thenReturn(jacocoExecutionData); - assertThat(sensor.shouldExecuteOnProject()).isTrue(); - - when(pathResolver.relativeFile(any(File.class), eq("ut.exec"))).thenReturn(jacocoExecutionData.getParentFile()); - assertThat(sensor.shouldExecuteOnProject()).isFalse(); - - File outputDir = TestUtils.getResource(JaCoCoSensorTest.class, "."); - File fakeExecFile = new File(outputDir, "ut.not.found.exec"); - when(pathResolver.relativeFile(any(File.class), eq("ut.exec"))).thenReturn(fakeExecFile); - assertThat(sensor.shouldExecuteOnProject()).isFalse(); - - when(pathResolver.relativeFile(any(File.class), eq("ut.exec"))).thenReturn(fakeExecFile); - when(configuration.shouldExecuteOnProject(false)).thenReturn(true); - assertThat(sensor.shouldExecuteOnProject()).isTrue(); - } - - @Test - public void test_read_execution_data_with_jacoco_0_7_4() { - when(pathResolver.relativeFile(any(File.class), ArgumentMatchers.endsWith(".exec"))).thenReturn(jacocoExecutionData); - - SensorContextTester context = SensorContextTester.create(new File("")); - sensor.execute(context); - - verifyMeasures(context); - } - - @Test - public void test_read_execution_data_with_jacoco_0_7_5() throws IOException { - File jacocoExecutionData = initWithJaCoCoVersion("JaCoCoSensor_0_7_5"); - when(pathResolver.relativeFile(any(File.class), ArgumentMatchers.endsWith(".exec"))).thenReturn(jacocoExecutionData); - - SensorContextTester context = SensorContextTester.create(new File("")); - sensor.execute(context); - - verifyMeasures(context); - } - - private void verifyMeasures(SensorContextTester context) { - int[] oneHitlines = {9, 10, 14, 15, 17, 21, 29, 32, 33, 42, 47}; - int[] zeroHitlines = {25, 30, 38}; - int[] conditionLines = {14, 29, 30}; - int[] coveredConditions = {2, 1, 0}; - - for (int zeroHitline : zeroHitlines) { - assertThat(context.lineHits(":example/Hello.groovy", CoverageType.UNIT, zeroHitline)).isEqualTo(0); + @Rule + public TemporaryFolder temp = new TemporaryFolder(); + + private File jacocoExecutionData; + private DefaultInputFile inputFile; + private JaCoCoConfiguration configuration; + private PathResolver pathResolver; + private JaCoCoSensor sensor; + + @Before + public void setUp() throws Exception { + this.jacocoExecutionData = initWithJaCoCoVersion("JaCoCoSensor_0_7_4"); + } + + private File initWithJaCoCoVersion(String jacocoVersion) throws IOException { + File outputDir = TestUtils.getResource("/org/sonar/plugins/groovy/jacoco/" + jacocoVersion + "/"); + File jacocoExecutionData = new File(outputDir, "jacoco-ut.exec"); + + FileUtils.copyFile(TestUtils.getResource("/org/sonar/plugins/groovy/jacoco/Hello.class.toCopy"), + new File(jacocoExecutionData.getParentFile(), "Hello.class")); + FileUtils.copyFile(TestUtils.getResource("/org/sonar/plugins/groovy/jacoco/Hello$InnerClass.class.toCopy"), + new File(jacocoExecutionData.getParentFile(), "Hello$InnerClass.class")); + + Settings settings = new MapSettings(); + settings.setProperty(GroovyPlugin.SONAR_GROOVY_BINARIES, "."); + + configuration = mock(JaCoCoConfiguration.class); + when(configuration.shouldExecuteOnProject(true)).thenReturn(true); + when(configuration.shouldExecuteOnProject(false)).thenReturn(false); + when(configuration.getReportPath()).thenReturn(jacocoExecutionData.getPath()); + + DefaultFileSystem fileSystem = new DefaultFileSystem(jacocoExecutionData.getParentFile()); + + DefaultIndexedFile indexedFile = new DefaultIndexedFile("", Paths.get("."), "example/Hello.groovy", Groovy.KEY); + + inputFile = new DefaultInputFile(indexedFile, f -> f.setMetadata(new Metadata(50, 0, "", new int[0], new int[0], 0))); + + fileSystem.add(inputFile); + + pathResolver = mock(PathResolver.class); + sensor = new JaCoCoSensor(configuration, new GroovyFileSystem(fileSystem), pathResolver, settings); + + return jacocoExecutionData; } - for (int oneHitline : oneHitlines) { - assertThat(context.lineHits(":example/Hello.groovy", CoverageType.UNIT, oneHitline)).isEqualTo(1); + + @Test + public void test_description() { + DefaultSensorDescriptor defaultSensorDescriptor = new DefaultSensorDescriptor(); + sensor.describe(defaultSensorDescriptor); + assertThat(defaultSensorDescriptor.languages()).containsOnly(Groovy.KEY); } - for (int i = 0; i < conditionLines.length; i++) { - int conditionLine = conditionLines[i]; - assertThat(context.conditions(":example/Hello.groovy", CoverageType.UNIT, conditionLine)).isEqualTo(2); - assertThat(context.coveredConditions(":example/Hello.groovy", CoverageType.UNIT, conditionLine)).isEqualTo(coveredConditions[i]); + + @Test + public void should_Execute_On_Project_only_if_exec_exists() { + when(configuration.getReportPath()).thenReturn("ut.exec"); + + when(pathResolver.relativeFile(any(File.class), eq("ut.exec"))).thenReturn(jacocoExecutionData); + assertThat(sensor.shouldExecuteOnProject()).isTrue(); + + when(pathResolver.relativeFile(any(File.class), eq("ut.exec"))).thenReturn(jacocoExecutionData.getParentFile()); + assertThat(sensor.shouldExecuteOnProject()).isFalse(); + + File outputDir = TestUtils.getResource(JaCoCoSensorTest.class, "."); + File fakeExecFile = new File(outputDir, "ut.not.found.exec"); + when(pathResolver.relativeFile(any(File.class), eq("ut.exec"))).thenReturn(fakeExecFile); + assertThat(sensor.shouldExecuteOnProject()).isFalse(); + + when(pathResolver.relativeFile(any(File.class), eq("ut.exec"))).thenReturn(fakeExecFile); + when(configuration.shouldExecuteOnProject(false)).thenReturn(true); + assertThat(sensor.shouldExecuteOnProject()).isTrue(); + } + + @Test + public void test_read_execution_data_with_jacoco_0_7_4() { + when(pathResolver.relativeFile(any(File.class), ArgumentMatchers.endsWith(".exec"))).thenReturn(jacocoExecutionData); + + SensorContextTester context = SensorContextTester.create(new File("")); + sensor.execute(context); + + verifyMeasures(context); + } + + private void verifyMeasures(SensorContextTester context) { + int[] oneHitlines = {9, 10, 14, 15, 17, 21, 29, 32, 33, 42, 47}; + int[] zeroHitlines = {25, 30, 38}; + int[] conditionLines = {14, 29, 30}; + int[] coveredConditions = {2, 1, 0}; + + for (int zeroHitline : zeroHitlines) { + assertThat(context.lineHits(":example/Hello.groovy", zeroHitline)).isEqualTo(0); + } + for (int oneHitline : oneHitlines) { + assertThat(context.lineHits(":example/Hello.groovy", oneHitline)).isEqualTo(1); + } + for (int i = 0; i < conditionLines.length; i++) { + int conditionLine = conditionLines[i]; + assertThat(context.conditions(":example/Hello.groovy", conditionLine)).isEqualTo(2); + assertThat(context.coveredConditions(":example/Hello.groovy", conditionLine)).isEqualTo(coveredConditions[i]); + } + } + + @Test + public void test_read_execution_data_with_jacoco_0_7_5() throws IOException { + File jacocoExecutionData = initWithJaCoCoVersion("JaCoCoSensor_0_7_5"); + when(pathResolver.relativeFile(any(File.class), ArgumentMatchers.endsWith(".exec"))).thenReturn(jacocoExecutionData); + + SensorContextTester context = SensorContextTester.create(new File("")); + sensor.execute(context); + + verifyMeasures(context); } - } -} +} \ No newline at end of file diff --git a/sonar-groovy-plugin/src/test/java/org/sonar/plugins/groovy/surefire/GroovySurefireParserTest.java b/sonar-groovy-plugin/src/test/java/org/sonar/plugins/groovy/surefire/GroovySurefireParserTest.java index bc806dbd..269260aa 100644 --- a/sonar-groovy-plugin/src/test/java/org/sonar/plugins/groovy/surefire/GroovySurefireParserTest.java +++ b/sonar-groovy-plugin/src/test/java/org/sonar/plugins/groovy/surefire/GroovySurefireParserTest.java @@ -21,6 +21,9 @@ import java.io.File; import java.net.URISyntaxException; +import java.nio.file.Path; +import java.nio.file.Paths; + import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentMatcher; @@ -31,7 +34,9 @@ import org.sonar.api.batch.fs.InputFile; import org.sonar.api.batch.fs.InputFile.Type; import org.sonar.api.batch.fs.internal.DefaultFileSystem; +import org.sonar.api.batch.fs.internal.DefaultIndexedFile; import org.sonar.api.batch.fs.internal.DefaultInputFile; +import org.sonar.api.batch.fs.internal.SensorStrategy; import org.sonar.api.batch.sensor.SensorContext; import org.sonar.api.batch.sensor.internal.SensorContextTester; import org.sonar.api.component.ResourcePerspectives; @@ -79,12 +84,11 @@ public void before() { parser = spy(new GroovySurefireParser(groovy, perspectives, fs)); - doAnswer(new Answer() { - @Override - public InputFile answer(InvocationOnMock invocation) throws Throwable { - return new DefaultInputFile("", (String) invocation.getArguments()[0]); - } - }).when(parser).getUnitTestInputFile(anyString()); + doAnswer((Answer) invocation -> + new DefaultInputFile( + new DefaultIndexedFile("", Paths.get("."), (String) invocation.getArguments()[0], Groovy.KEY), f -> {} + )).when(parser).getUnitTestInputFile(anyString() + ); } @Test @@ -214,9 +218,14 @@ private java.io.File getDir(String dirname) throws URISyntaxException { @Test public void should_generate_correct_predicate() throws URISyntaxException { DefaultFileSystem fs = new DefaultFileSystem(new File(".")); - DefaultInputFile inputFile = new DefaultInputFile("", "src/test/org/sonar/JavaNCSSCollectorTest.groovy") - .setLanguage(Groovy.KEY) - .setType(Type.TEST); + Path baseDir = Paths.get("."); + String relativePath = "src/test/org/sonar/JavaNCSSCollectorTest.groovy"; + + DefaultIndexedFile indexedFile = new DefaultIndexedFile( + baseDir.resolve(relativePath), "", relativePath, relativePath, Type.TEST, Groovy.KEY, 0, + new SensorStrategy()); + + DefaultInputFile inputFile = new DefaultInputFile(indexedFile, f -> {}); fs.add(inputFile); parser = new GroovySurefireParser(groovy, perspectives, fs); diff --git a/sonar-groovy-plugin/src/test/java/org/sonar/plugins/groovy/surefire/GroovySurefireSensorTest.java b/sonar-groovy-plugin/src/test/java/org/sonar/plugins/groovy/surefire/GroovySurefireSensorTest.java index dfe5f4bf..df93d87d 100644 --- a/sonar-groovy-plugin/src/test/java/org/sonar/plugins/groovy/surefire/GroovySurefireSensorTest.java +++ b/sonar-groovy-plugin/src/test/java/org/sonar/plugins/groovy/surefire/GroovySurefireSensorTest.java @@ -25,7 +25,9 @@ import org.mockito.stubbing.Answer; import org.sonar.api.batch.fs.InputFile; import org.sonar.api.batch.fs.internal.DefaultFileSystem; +import org.sonar.api.batch.fs.internal.DefaultIndexedFile; import org.sonar.api.batch.fs.internal.DefaultInputFile; +import org.sonar.api.batch.fs.internal.SensorStrategy; import org.sonar.api.batch.sensor.SensorContext; import org.sonar.api.batch.sensor.internal.DefaultSensorDescriptor; import org.sonar.api.batch.sensor.internal.SensorContextTester; @@ -39,6 +41,8 @@ import java.io.File; import java.net.URISyntaxException; +import java.nio.file.Path; +import java.nio.file.Paths; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.anyString; @@ -62,8 +66,8 @@ public class GroovySurefireSensorTest { @Before public void before() { fs = new DefaultFileSystem(new File(".")); - DefaultInputFile groovyFile = new DefaultInputFile("", "src/org/foo/grvy"); - groovyFile.setLanguage(Groovy.KEY); + DefaultIndexedFile indexedFile = new DefaultIndexedFile("", Paths.get("."), "src/org/foo/grvy", Groovy.KEY); + DefaultInputFile groovyFile = new DefaultInputFile(indexedFile, f -> {}); fs.add(groovyFile); perspectives = mock(ResourcePerspectives.class); @@ -137,7 +141,13 @@ public void shouldHandleTestSuiteDetails() throws URISyntaxException { } private static DefaultInputFile inputFile(String key) { - return new DefaultInputFile("", key).setType(InputFile.Type.TEST); + Path baseDir = Paths.get("."); + + DefaultIndexedFile indexedFile = new DefaultIndexedFile( + baseDir.resolve(key), "", key, key, InputFile.Type.TEST, Groovy.KEY, 0, + new SensorStrategy()); + + return new DefaultInputFile(indexedFile, f -> {}); } @Test