diff options
author | Duarte Meneses <duarte.meneses@sonarsource.com> | 2017-04-05 14:21:53 +0200 |
---|---|---|
committer | dbmeneses <duarte.meneses@sonarsource.com> | 2017-04-11 13:39:57 +0200 |
commit | 964fff7ca9f072e6e084c0fac605980f19bc0278 (patch) | |
tree | 0176917753cd10f0c776492bc33c1cf05ea77613 /sonar-scanner-engine/src/test | |
parent | 2489c157e7a4e563c7279b57f12c197aa53d28b5 (diff) | |
download | sonarqube-964fff7ca9f072e6e084c0fac605980f19bc0278.tar.gz sonarqube-964fff7ca9f072e6e084c0fac605980f19bc0278.zip |
SONAR-9025 Optimize computation issue exclusions
Diffstat (limited to 'sonar-scanner-engine/src/test')
15 files changed, 218 insertions, 440 deletions
diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/ModuleIssuesTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/ModuleIssuesTest.java index af240c47660..c180e8e1da6 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/ModuleIssuesTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/ModuleIssuesTest.java @@ -24,7 +24,6 @@ import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; -import org.sonar.api.batch.fs.FileSystem; import org.sonar.api.batch.fs.internal.DefaultInputFile; import org.sonar.api.batch.fs.internal.TestInputFileBuilder; import org.sonar.api.batch.rule.internal.ActiveRulesBuilder; @@ -36,10 +35,6 @@ import org.sonar.api.rule.Severity; import org.sonar.api.utils.MessageException; import org.sonar.scanner.issue.IssueFilters; import org.sonar.scanner.issue.ModuleIssues; -import org.sonar.scanner.issue.ignore.pattern.IssueExclusionPatternInitializer; -import org.sonar.scanner.issue.ignore.pattern.IssueInclusionPatternInitializer; -import org.sonar.scanner.issue.ignore.scanner.IssueExclusionsLoader; -import org.sonar.scanner.issue.ignore.scanner.IssueExclusionsRegexpScanner; import org.sonar.scanner.protocol.output.ScannerReport; import org.sonar.scanner.report.ReportPublisher; @@ -211,9 +206,7 @@ public class ModuleIssuesTest { * Every rules and active rules has to be added in builders before creating ModuleIssues */ private void initModuleIssues() { - IssueExclusionsLoader issueExclusionsLoader = new IssueExclusionsLoader(mock(IssueExclusionsRegexpScanner.class), mock(IssueExclusionPatternInitializer.class), - mock(IssueInclusionPatternInitializer.class), mock(FileSystem.class)); - moduleIssues = new ModuleIssues(activeRulesBuilder.build(), ruleBuilder.build(), filters, reportPublisher, issueExclusionsLoader); + moduleIssues = new ModuleIssues(activeRulesBuilder.build(), ruleBuilder.build(), filters, reportPublisher); } } diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/ignore/EnforceIssuesFilterTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/ignore/EnforceIssuesFilterTest.java index dab1de1df03..d3089b298fa 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/ignore/EnforceIssuesFilterTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/ignore/EnforceIssuesFilterTest.java @@ -25,11 +25,14 @@ import com.google.common.collect.ImmutableList; import org.junit.Before; import org.junit.Test; import org.sonar.api.scan.issue.filter.IssueFilterChain; +import org.sonar.api.batch.fs.InputComponent; +import org.sonar.api.batch.fs.internal.TestInputFileBuilder; import org.sonar.api.rule.RuleKey; import org.sonar.api.utils.WildcardPattern; import org.sonar.scanner.issue.ignore.EnforceIssuesFilter; import org.sonar.scanner.issue.ignore.pattern.IssueInclusionPatternInitializer; import org.sonar.scanner.issue.ignore.pattern.IssuePattern; +import org.sonar.scanner.scan.filesystem.InputComponentStore; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; @@ -40,18 +43,20 @@ import static org.mockito.Mockito.when; public class EnforceIssuesFilterTest { private IssueInclusionPatternInitializer exclusionPatternInitializer; + private InputComponentStore inputComponentStore; private EnforceIssuesFilter ignoreFilter; private FilterableIssue issue; private IssueFilterChain chain; @Before public void init() { + inputComponentStore = mock(InputComponentStore.class); exclusionPatternInitializer = mock(IssueInclusionPatternInitializer.class); issue = mock(FilterableIssue.class); chain = mock(IssueFilterChain.class); when(chain.accept(issue)).thenReturn(true); - ignoreFilter = new EnforceIssuesFilter(exclusionPatternInitializer); + ignoreFilter = new EnforceIssuesFilter(exclusionPatternInitializer, inputComponentStore); } @Test @@ -95,12 +100,16 @@ public class EnforceIssuesFilterTest { when(matching.getResourcePattern()).thenReturn(pathPattern); when(pathPattern.match(path)).thenReturn(true); when(exclusionPatternInitializer.getMulticriteriaPatterns()).thenReturn(ImmutableList.of(matching)); - when(exclusionPatternInitializer.getPathForComponent(componentKey)).thenReturn(path); + when(inputComponentStore.getByKey(componentKey)).thenReturn(createComponentWithPath(path)); assertThat(ignoreFilter.accept(issue, chain)).isTrue(); verifyZeroInteractions(chain); } + private InputComponent createComponentWithPath(String path) { + return new TestInputFileBuilder("", path).build(); + } + @Test public void shouldRefuseIssueIfRuleMatchesButNotPath() { String rule = "rule"; @@ -119,7 +128,7 @@ public class EnforceIssuesFilterTest { when(matching.getResourcePattern()).thenReturn(pathPattern); when(pathPattern.match(path)).thenReturn(false); when(exclusionPatternInitializer.getMulticriteriaPatterns()).thenReturn(ImmutableList.of(matching)); - when(exclusionPatternInitializer.getPathForComponent(componentKey)).thenReturn(path); + when(inputComponentStore.getByKey(componentKey)).thenReturn(createComponentWithPath(path)); assertThat(ignoreFilter.accept(issue, chain)).isFalse(); verifyZeroInteractions(chain); @@ -143,7 +152,7 @@ public class EnforceIssuesFilterTest { when(matching.getResourcePattern()).thenReturn(pathPattern); when(pathPattern.match(path)).thenReturn(false); when(exclusionPatternInitializer.getMulticriteriaPatterns()).thenReturn(ImmutableList.of(matching)); - when(exclusionPatternInitializer.getPathForComponent(componentKey)).thenReturn(null); + when(inputComponentStore.getByKey(componentKey)).thenReturn(null); assertThat(ignoreFilter.accept(issue, chain)).isFalse(); verifyZeroInteractions(chain); diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/ignore/IgnoreIssuesFilterTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/ignore/IgnoreIssuesFilterTest.java index b1a88ce858c..ccf1ed016c6 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/ignore/IgnoreIssuesFilterTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/ignore/IgnoreIssuesFilterTest.java @@ -19,23 +19,24 @@ */ package org.sonar.scanner.issue.ignore; +import org.sonar.api.rule.RuleKey; import org.sonar.api.scan.issue.filter.FilterableIssue; import org.junit.Before; import org.junit.Test; import org.sonar.api.scan.issue.filter.IssueFilterChain; import org.sonar.scanner.issue.ignore.IgnoreIssuesFilter; -import org.sonar.scanner.issue.ignore.pattern.IssueExclusionPatternInitializer; import org.sonar.scanner.issue.ignore.pattern.IssuePattern; import org.sonar.scanner.issue.ignore.pattern.PatternMatcher; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.when; public class IgnoreIssuesFilterTest { - private IssueExclusionPatternInitializer exclusionPatternInitializer; private PatternMatcher exclusionPatternMatcher; private IgnoreIssuesFilter ignoreFilter; private FilterableIssue issue; @@ -44,25 +45,23 @@ public class IgnoreIssuesFilterTest { @Before public void init() { exclusionPatternMatcher = mock(PatternMatcher.class); - exclusionPatternInitializer = mock(IssueExclusionPatternInitializer.class); - when(exclusionPatternInitializer.getPatternMatcher()).thenReturn(exclusionPatternMatcher); issue = mock(FilterableIssue.class); chain = mock(IssueFilterChain.class); when(chain.accept(issue)).thenReturn(true); - ignoreFilter = new IgnoreIssuesFilter(exclusionPatternInitializer); + ignoreFilter = new IgnoreIssuesFilter(exclusionPatternMatcher); } @Test public void shouldPassToChainIfMatcherHasNoPatternForIssue() { - when(exclusionPatternMatcher.getMatchingPattern(issue)).thenReturn(null); + when(exclusionPatternMatcher.getMatchingPattern(anyString(), any(RuleKey.class), any(Integer.class))).thenReturn(null); assertThat(ignoreFilter.accept(issue, chain)).isTrue(); } @Test public void shouldAcceptOrRefuseIfMatcherHasPatternForIssue() { - when(exclusionPatternMatcher.getMatchingPattern(issue)).thenReturn(mock(IssuePattern.class)); + when(exclusionPatternMatcher.getMatchingPattern(anyString(), any(RuleKey.class), any(Integer.class))).thenReturn(mock(IssuePattern.class)); assertThat(ignoreFilter.accept(issue, chain)).isFalse(); } diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/ignore/pattern/IssueExclusionPatternInitializerTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/ignore/pattern/IssueExclusionPatternInitializerTest.java index a298c822a2e..7fadd593235 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/ignore/pattern/IssueExclusionPatternInitializerTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/ignore/pattern/IssueExclusionPatternInitializerTest.java @@ -19,76 +19,45 @@ */ package org.sonar.scanner.issue.ignore.pattern; - import org.junit.Before; import org.junit.Test; import org.sonar.api.config.PropertyDefinitions; import org.sonar.api.config.Settings; import org.sonar.api.config.MapSettings; -import org.sonar.api.utils.SonarException; import org.sonar.core.config.IssueExclusionProperties; import static org.assertj.core.api.Assertions.assertThat; public class IssueExclusionPatternInitializerTest { - private IssueExclusionPatternInitializer patternsInitializer; - private Settings settings; @Before public void init() { settings = new MapSettings(new PropertyDefinitions(IssueExclusionProperties.all())); - patternsInitializer = new IssueExclusionPatternInitializer(settings); } @Test public void testNoConfiguration() { - patternsInitializer.initPatterns(); + patternsInitializer = new IssueExclusionPatternInitializer(settings); assertThat(patternsInitializer.hasConfiguredPatterns()).isFalse(); assertThat(patternsInitializer.getMulticriteriaPatterns().size()).isEqualTo(0); } - @Test - public void shouldHavePatternsBasedOnMulticriteriaPattern() { - settings.setProperty("sonar.issue.ignore" + ".multicriteria", "1,2"); - settings.setProperty("sonar.issue.ignore" + ".multicriteria" + ".1." + "resourceKey", "org/foo/Bar.java"); - settings.setProperty("sonar.issue.ignore" + ".multicriteria" + ".1." + "ruleKey", "*"); - settings.setProperty("sonar.issue.ignore" + ".multicriteria" + ".2." + "resourceKey", "org/foo/Hello.java"); - settings.setProperty("sonar.issue.ignore" + ".multicriteria" + ".2." + "ruleKey", "checkstyle:MagicNumber"); - patternsInitializer.initPatterns(); - - assertThat(patternsInitializer.hasConfiguredPatterns()).isTrue(); - assertThat(patternsInitializer.hasFileContentPattern()).isFalse(); - assertThat(patternsInitializer.hasMulticriteriaPatterns()).isTrue(); - assertThat(patternsInitializer.getMulticriteriaPatterns().size()).isEqualTo(2); - assertThat(patternsInitializer.getBlockPatterns().size()).isEqualTo(0); - assertThat(patternsInitializer.getAllFilePatterns().size()).isEqualTo(0); - - patternsInitializer.initializePatternsForPath("org/foo/Bar.java", "org.foo.Bar"); - patternsInitializer.initializePatternsForPath("org/foo/Baz.java", "org.foo.Baz"); - patternsInitializer.initializePatternsForPath("org/foo/Hello.java", "org.foo.Hello"); - - assertThat(patternsInitializer.getPatternMatcher().getPatternsForComponent("org.foo.Bar")).hasSize(1); - assertThat(patternsInitializer.getPatternMatcher().getPatternsForComponent("org.foo.Baz")).hasSize(0); - assertThat(patternsInitializer.getPatternMatcher().getPatternsForComponent("org.foo.Hello")).hasSize(1); - - } - - @Test(expected = SonarException.class) + @Test(expected = IllegalStateException.class) public void shouldLogInvalidResourceKey() { settings.setProperty("sonar.issue.ignore" + ".multicriteria", "1"); settings.setProperty("sonar.issue.ignore" + ".multicriteria" + ".1." + "resourceKey", ""); settings.setProperty("sonar.issue.ignore" + ".multicriteria" + ".1." + "ruleKey", "*"); - patternsInitializer.initPatterns(); + patternsInitializer = new IssueExclusionPatternInitializer(settings); } - @Test(expected = SonarException.class) + @Test(expected = IllegalStateException.class) public void shouldLogInvalidRuleKey() { settings.setProperty("sonar.issue.ignore" + ".multicriteria", "1"); settings.setProperty("sonar.issue.ignore" + ".multicriteria" + ".1." + "resourceKey", "*"); settings.setProperty("sonar.issue.ignore" + ".multicriteria" + ".1." + "ruleKey", ""); - patternsInitializer.initPatterns(); + patternsInitializer = new IssueExclusionPatternInitializer(settings); } @Test @@ -100,7 +69,7 @@ public class IssueExclusionPatternInitializerTest { settings.setProperty(IssueExclusionProperties.PATTERNS_BLOCK_KEY + ".2." + IssueExclusionProperties.END_BLOCK_REGEXP, "// FOO-ON"); settings.setProperty(IssueExclusionProperties.PATTERNS_BLOCK_KEY + ".3." + IssueExclusionProperties.BEGIN_BLOCK_REGEXP, "// IGNORE-TO-EOF"); settings.setProperty(IssueExclusionProperties.PATTERNS_BLOCK_KEY + ".3." + IssueExclusionProperties.END_BLOCK_REGEXP, ""); - patternsInitializer.loadFileContentPatterns(); + patternsInitializer = new IssueExclusionPatternInitializer(settings); assertThat(patternsInitializer.hasConfiguredPatterns()).isTrue(); assertThat(patternsInitializer.hasFileContentPattern()).isTrue(); @@ -110,12 +79,12 @@ public class IssueExclusionPatternInitializerTest { assertThat(patternsInitializer.getAllFilePatterns().size()).isEqualTo(0); } - @Test(expected = SonarException.class) + @Test(expected = IllegalStateException.class) public void shouldLogInvalidStartBlockPattern() { settings.setProperty(IssueExclusionProperties.PATTERNS_BLOCK_KEY, "1"); settings.setProperty(IssueExclusionProperties.PATTERNS_BLOCK_KEY + ".1." + IssueExclusionProperties.BEGIN_BLOCK_REGEXP, ""); settings.setProperty(IssueExclusionProperties.PATTERNS_BLOCK_KEY + ".1." + IssueExclusionProperties.END_BLOCK_REGEXP, "// SONAR-ON"); - patternsInitializer.loadFileContentPatterns(); + patternsInitializer = new IssueExclusionPatternInitializer(settings); } @Test @@ -123,7 +92,7 @@ public class IssueExclusionPatternInitializerTest { settings.setProperty(IssueExclusionProperties.PATTERNS_ALLFILE_KEY, "1,2"); settings.setProperty(IssueExclusionProperties.PATTERNS_ALLFILE_KEY + ".1." + IssueExclusionProperties.FILE_REGEXP, "@SONAR-IGNORE-ALL"); settings.setProperty(IssueExclusionProperties.PATTERNS_ALLFILE_KEY + ".2." + IssueExclusionProperties.FILE_REGEXP, "//FOO-IGNORE-ALL"); - patternsInitializer.loadFileContentPatterns(); + patternsInitializer = new IssueExclusionPatternInitializer(settings); assertThat(patternsInitializer.hasConfiguredPatterns()).isTrue(); assertThat(patternsInitializer.hasFileContentPattern()).isTrue(); @@ -133,10 +102,10 @@ public class IssueExclusionPatternInitializerTest { assertThat(patternsInitializer.getAllFilePatterns().size()).isEqualTo(2); } - @Test(expected = SonarException.class) + @Test(expected = IllegalStateException.class) public void shouldLogInvalidAllFilePattern() { settings.setProperty(IssueExclusionProperties.PATTERNS_ALLFILE_KEY, "1"); settings.setProperty(IssueExclusionProperties.PATTERNS_ALLFILE_KEY + ".1." + IssueExclusionProperties.FILE_REGEXP, ""); - patternsInitializer.loadFileContentPatterns(); + patternsInitializer = new IssueExclusionPatternInitializer(settings); } } diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/ignore/pattern/IssueInclusionPatternInitializerTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/ignore/pattern/IssueInclusionPatternInitializerTest.java index de3982e504e..6feecb28637 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/ignore/pattern/IssueInclusionPatternInitializerTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/ignore/pattern/IssueInclusionPatternInitializerTest.java @@ -31,7 +31,6 @@ import static org.assertj.core.api.Assertions.assertThat; public class IssueInclusionPatternInitializerTest { private IssueInclusionPatternInitializer patternsInitializer; - private Settings settings; @Before @@ -58,14 +57,6 @@ public class IssueInclusionPatternInitializerTest { assertThat(patternsInitializer.hasConfiguredPatterns()).isTrue(); assertThat(patternsInitializer.hasMulticriteriaPatterns()).isTrue(); assertThat(patternsInitializer.getMulticriteriaPatterns().size()).isEqualTo(2); - - patternsInitializer.initializePatternsForPath("org/foo/Bar.java", "org.foo.Bar"); - patternsInitializer.initializePatternsForPath("org/foo/Baz.java", "org.foo.Baz"); - patternsInitializer.initializePatternsForPath("org/foo/Hello.java", "org.foo.Hello"); - - assertThat(patternsInitializer.getPathForComponent("org.foo.Bar")).isEqualTo("org/foo/Bar.java"); - assertThat(patternsInitializer.getPathForComponent("org.foo.Baz")).isEqualTo("org/foo/Baz.java"); - assertThat(patternsInitializer.getPathForComponent("org.foo.Hello")).isEqualTo("org/foo/Hello.java"); } } diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/ignore/pattern/IssuePatternTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/ignore/pattern/IssuePatternTest.java index b14cc76e4a3..d6c6f778b53 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/ignore/pattern/IssuePatternTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/ignore/pattern/IssuePatternTest.java @@ -22,18 +22,23 @@ package org.sonar.scanner.issue.ignore.pattern; import org.junit.Test; import org.sonar.api.rule.RuleKey; import org.sonar.api.rules.Rule; -import org.sonar.api.scan.issue.filter.FilterableIssue; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; + +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; public class IssuePatternTest { @Test public void shouldMatchLines() { - IssuePattern pattern = new IssuePattern("*", "*"); - pattern.addLine(12).addLine(15).addLineRange(20, 25); + Set<LineRange> lineRanges = new HashSet<>(); + lineRanges.add(new LineRange(12)); + lineRanges.add(new LineRange(15)); + lineRanges.add(new LineRange(20, 25)); + + IssuePattern pattern = new IssuePattern("*", "*", lineRanges); assertThat(pattern.matchLine(3)).isFalse(); assertThat(pattern.matchLine(12)).isTrue(); @@ -77,31 +82,17 @@ public class IssuePatternTest { Rule rule = Rule.create("checkstyle", "IllegalRegexp", ""); String javaFile = "org.foo.Bar"; - IssuePattern pattern = new IssuePattern("*", "*"); - pattern.addLine(12); - - assertThat(pattern.match(create(rule, javaFile, null))).isFalse(); - assertThat(pattern.match(create(rule, javaFile, 12))).isTrue(); - assertThat(pattern.match(create(rule, null, null))).isFalse(); - } + IssuePattern pattern = new IssuePattern("*", "*", Collections.singleton(new LineRange(12))); - private FilterableIssue create(Rule rule, String component, Integer line) { - FilterableIssue mockIssue = mock(FilterableIssue.class); - RuleKey ruleKey = null; - if (rule != null) { - ruleKey = rule.ruleKey(); - } - when(mockIssue.ruleKey()).thenReturn(ruleKey); - when(mockIssue.componentKey()).thenReturn(component); - when(mockIssue.line()).thenReturn(line); - return mockIssue; + assertThat(pattern.match(javaFile, rule.ruleKey(), null)).isFalse(); + assertThat(pattern.match(javaFile, rule.ruleKey(), 12)).isTrue(); + assertThat(pattern.match(null, rule.ruleKey(), null)).isFalse(); } @Test public void shouldPrintPatternToString() { IssuePattern pattern = new IssuePattern("*", "checkstyle:*"); - assertThat(pattern.toString()).isEqualTo( - "IssuePattern[resourcePattern=*,rulePattern=checkstyle:*,lines=[],lineRanges=[],beginBlockRegexp=<null>,endBlockRegexp=<null>,allFileRegexp=<null>,checkLines=true]"); + assertThat(pattern.toString()).isEqualTo("IssuePattern[resourcePattern=*,rulePattern=checkstyle:*,lines=[],lineRanges=[],checkLines=false]"); } } diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/ignore/pattern/PatternDecoderTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/ignore/pattern/PatternDecoderTest.java index 056451fb3e2..f4ca8b9c745 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/ignore/pattern/PatternDecoderTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/ignore/pattern/PatternDecoderTest.java @@ -19,41 +19,12 @@ */ package org.sonar.scanner.issue.ignore.pattern; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.sonar.api.utils.SonarException; -import org.sonar.scanner.issue.ignore.pattern.IssuePattern; import org.sonar.scanner.issue.ignore.pattern.PatternDecoder; -import java.util.List; import static org.assertj.core.api.Assertions.assertThat; public class PatternDecoderTest { - - private PatternDecoder decoder = new PatternDecoder(); - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Test - public void shouldReadString() { - String patternsList = "# a comment followed by a blank line\n\n" + - "# suppress all violations\n" + - "*;*;*\n\n" + - "# exclude a Java file\n" + - "com.foo.Bar;*;*\n\n" + - "# exclude a Java package\n" + - "com.foo.*;*;*\n\n" + - "# exclude a specific rule\n" + - "*;checkstyle:IllegalRegexp;*\n\n" + - "# exclude a specific rule on a specific file\n" + - "com.foo.Bar;checkstyle:IllegalRegexp;*\n"; - List<IssuePattern> patterns = decoder.decode(patternsList); - - assertThat(patterns).hasSize(5); - } - @Test public void shouldCheckFormatOfResource() { assertThat(PatternDecoder.isResource("")).isFalse(); @@ -83,106 +54,4 @@ public class PatternDecoderTest { assertThat(PatternDecoder.isLinesRange("[24-65]")).isTrue(); assertThat(PatternDecoder.isLinesRange("[13,24-65,84-89,122]")).isTrue(); } - - @Test - public void shouldReadStarPatterns() { - IssuePattern pattern = decoder.decodeLine("*;*;*"); - - assertThat(pattern.getResourcePattern().toString()).isEqualTo("*"); - assertThat(pattern.getRulePattern().toString()).isEqualTo("*"); - assertThat(pattern.isCheckLines()).isFalse(); - } - - @Test - public void shouldReadLineIds() { - IssuePattern pattern = decoder.decodeLine("*;*;[10,25,98]"); - - assertThat(pattern.isCheckLines()).isTrue(); - assertThat(pattern.getAllLines()).containsOnly(10, 25, 98); - } - - @Test - public void shouldReadRangeOfLineIds() { - IssuePattern pattern = decoder.decodeLine("*;*;[10-12,25,97-100]"); - - assertThat(pattern.isCheckLines()).isTrue(); - assertThat(pattern.getAllLines()).containsOnly(10, 11, 12, 25, 97, 98, 99, 100); - } - - @Test - public void shouldNotExcludeLines() { - // [] is different than * - // - all violations are excluded on * - // * no violations are excluded on [] - IssuePattern pattern = decoder.decodeLine("*;*;[]"); - - assertThat(pattern.isCheckLines()).isTrue(); - assertThat(pattern.getAllLines()).isEmpty(); - } - - @Test - public void shouldReadBlockPattern() { - IssuePattern pattern = decoder.decodeLine("SONAR-OFF;SONAR-ON"); - - assertThat(pattern.getResourcePattern()).isNull(); - assertThat(pattern.getBeginBlockRegexp()).isEqualTo("SONAR-OFF"); - assertThat(pattern.getEndBlockRegexp()).isEqualTo("SONAR-ON"); - } - - @Test - public void shouldReadAllFilePattern() { - IssuePattern pattern = decoder.decodeLine("SONAR-ALL-OFF"); - - assertThat(pattern.getResourcePattern()).isNull(); - assertThat(pattern.getAllFileRegexp()).isEqualTo("SONAR-ALL-OFF"); - } - - @Test - public void shouldFailToReadUncorrectLine1() { - thrown.expect(SonarException.class); - thrown.expectMessage("Exclusions > Issues : Invalid format. The following line has more than 3 fields separated by comma"); - - decoder.decode(";;;;"); - } - - @Test - public void shouldFailToReadUncorrectLine3() { - thrown.expect(SonarException.class); - thrown.expectMessage("Exclusions > Issues : Invalid format. The first field does not define a resource pattern"); - - decoder.decode(";*;*"); - } - - @Test - public void shouldFailToReadUncorrectLine4() { - thrown.expect(SonarException.class); - thrown.expectMessage("Exclusions > Issues : Invalid format. The second field does not define a rule pattern"); - - decoder.decode("*;;*"); - } - - @Test - public void shouldFailToReadUncorrectLine5() { - thrown.expect(SonarException.class); - thrown.expectMessage("Exclusions > Issues : Invalid format. The third field does not define a range of lines"); - - decoder.decode("*;*;blabla"); - } - - @Test - public void shouldFailToReadUncorrectLine6() { - thrown.expect(SonarException.class); - thrown.expectMessage("Exclusions > Issues : Invalid format. The first field does not define a regular expression"); - - decoder.decode(";ON"); - } - - @Test - public void shouldAcceptEmptyEndBlockRegexp() { - IssuePattern pattern = decoder.decodeLine("OFF;"); - - assertThat(pattern.getResourcePattern()).isNull(); - assertThat(pattern.getBeginBlockRegexp()).isEqualTo("OFF"); - assertThat(pattern.getEndBlockRegexp()).isEmpty(); - } } diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/ignore/pattern/PatternMatcherTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/ignore/pattern/PatternMatcherTest.java index 2025d0d1fd8..ea9cdb5606c 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/ignore/pattern/PatternMatcherTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/ignore/pattern/PatternMatcherTest.java @@ -19,22 +19,20 @@ */ package org.sonar.scanner.issue.ignore.pattern; -import org.sonar.api.scan.issue.filter.FilterableIssue; import org.sonar.scanner.issue.ignore.pattern.IssuePattern; import org.sonar.scanner.issue.ignore.pattern.LineRange; -import org.sonar.scanner.issue.ignore.pattern.PatternDecoder; import org.sonar.scanner.issue.ignore.pattern.PatternMatcher; import com.google.common.collect.Sets; import org.junit.Before; import org.junit.Test; -import org.sonar.api.rule.RuleKey; import org.sonar.api.rules.Rule; +import java.util.Collections; import java.util.Set; +import javax.annotation.Nullable; + import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; public class PatternMatcherTest { @@ -72,51 +70,47 @@ public class PatternMatcherTest { @Test public void shouldHaveNoMatcherIfNoneDefined() { - assertThat(patternMatcher.getMatchingPattern(create(CHECKSTYLE_RULE, JAVA_FILE, null))).isNull(); + assertThat(patternMatcher.getMatchingPattern(JAVA_FILE, CHECKSTYLE_RULE.ruleKey(), null)).isNull(); } @Test public void shouldMatchWithStandardPatterns() { - patternMatcher.addPatternForComponent(JAVA_FILE, createPattern("org.foo.Hello;checkstyle:MagicNumber;[15-200]")); + patternMatcher.addPatternForComponent(JAVA_FILE, createPattern("org.foo.Hello", "checkstyle:MagicNumber", createRanges(15, 200))); - assertThat(patternMatcher.getMatchingPattern(create(CHECKSTYLE_RULE, JAVA_FILE, 150))).isNotNull(); + assertThat(patternMatcher.getMatchingPattern(JAVA_FILE, CHECKSTYLE_RULE.ruleKey(), 150)).isNotNull(); } @Test public void shouldNotMatchWithStandardPatterns() { - patternMatcher.addPatternForComponent(JAVA_FILE, createPattern("org.foo.Hello;checkstyle:MagicNumber;[15-200]")); + patternMatcher.addPatternForComponent(JAVA_FILE, createPattern("org.foo.Hello", "checkstyle:MagicNumber", createRanges(15, 200))); - assertThat(patternMatcher.getMatchingPattern(create(CHECKSTYLE_RULE, JAVA_FILE, 5))).isNull(); + assertThat(patternMatcher.getMatchingPattern(JAVA_FILE, CHECKSTYLE_RULE.ruleKey(), 5)).isNull(); } @Test public void shouldMatchWithExtraPattern() { - patternMatcher.addPatternForComponent(JAVA_FILE, createPattern("org.foo.Hello;*;[15-200]")); + patternMatcher.addPatternForComponent(JAVA_FILE, createPattern("org.foo.Hello", "*", createRanges(15, 200))); - assertThat(patternMatcher.getMatchingPattern(create(CHECKSTYLE_RULE, JAVA_FILE, 150))).isNotNull(); + assertThat(patternMatcher.getMatchingPattern(JAVA_FILE, CHECKSTYLE_RULE.ruleKey(), 150)).isNotNull(); } @Test public void shouldNotMatchWithExtraPattern() { - patternMatcher.addPatternForComponent(JAVA_FILE, createPattern("org.foo.Hello;*;[15-200]")); + patternMatcher.addPatternForComponent(JAVA_FILE, createPattern("org.foo.Hello", "*", createRanges(15, 200))); - assertThat(patternMatcher.getMatchingPattern(create(CHECKSTYLE_RULE, JAVA_FILE, 5))).isNull(); + assertThat(patternMatcher.getMatchingPattern(JAVA_FILE, CHECKSTYLE_RULE.ruleKey(), 5)).isNull(); } - private FilterableIssue create(Rule rule, String component, Integer line) { - FilterableIssue mockIssue = mock(FilterableIssue.class); - RuleKey ruleKey = null; - if (rule != null) { - ruleKey = rule.ruleKey(); + private IssuePattern createPattern(String resourcePattern, String rulePattern, @Nullable Set<LineRange> lineRanges) { + if (lineRanges != null) { + return new IssuePattern(resourcePattern, rulePattern, lineRanges); + } else { + return new IssuePattern(resourcePattern, rulePattern); } - when(mockIssue.ruleKey()).thenReturn(ruleKey); - when(mockIssue.componentKey()).thenReturn(component); - when(mockIssue.line()).thenReturn(line); - return mockIssue; } - private IssuePattern createPattern(String line) { - return new PatternDecoder().decode(line).get(0); + private Set<LineRange> createRanges(int from, int to) { + return Collections.singleton(new LineRange(from, to)); } } diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/ignore/scanner/IssueExclusionsLoaderTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/ignore/scanner/IssueExclusionsLoaderTest.java index 1c2922c2141..638e504b6ce 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/ignore/scanner/IssueExclusionsLoaderTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/ignore/scanner/IssueExclusionsLoaderTest.java @@ -20,31 +20,23 @@ package org.sonar.scanner.issue.ignore.scanner; import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.nio.file.Path; +import java.util.Arrays; +import java.util.Collections; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import org.junit.rules.TemporaryFolder; import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import org.sonar.api.batch.fs.InputFile; -import org.sonar.api.batch.fs.internal.DefaultFileSystem; -import org.sonar.api.batch.fs.internal.DefaultInputFile; -import org.sonar.api.batch.fs.internal.TestInputFileBuilder; import org.sonar.scanner.issue.ignore.pattern.IssueExclusionPatternInitializer; -import org.sonar.scanner.issue.ignore.pattern.IssueInclusionPatternInitializer; +import org.sonar.scanner.issue.ignore.pattern.IssuePattern; import org.sonar.scanner.issue.ignore.pattern.PatternMatcher; -import static java.nio.charset.StandardCharsets.UTF_8; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; public class IssueExclusionsLoaderTest { @@ -52,31 +44,18 @@ public class IssueExclusionsLoaderTest { @Rule public ExpectedException thrown = ExpectedException.none(); - @Rule - public TemporaryFolder temp = new TemporaryFolder(); - - @Mock - private IssueExclusionsRegexpScanner regexpScanner; - - @Mock - private IssueInclusionPatternInitializer inclusionPatternInitializer; - @Mock private IssueExclusionPatternInitializer exclusionPatternInitializer; - @Mock private PatternMatcher patternMatcher; - private DefaultFileSystem fs; private IssueExclusionsLoader scanner; - private Path baseDir; @Before public void before() throws Exception { - baseDir = temp.newFolder().toPath(); - fs = new DefaultFileSystem(baseDir).setEncoding(UTF_8); + patternMatcher = new PatternMatcher(); MockitoAnnotations.initMocks(this); - scanner = new IssueExclusionsLoader(regexpScanner, exclusionPatternInitializer, inclusionPatternInitializer, fs); + scanner = new IssueExclusionsLoader(exclusionPatternInitializer, patternMatcher); } @Test @@ -85,108 +64,55 @@ public class IssueExclusionsLoaderTest { } @Test - public void shouldExecute() { - when(exclusionPatternInitializer.hasConfiguredPatterns()).thenReturn(true); - when(inclusionPatternInitializer.hasConfiguredPatterns()).thenReturn(true); - assertThat(scanner.shouldExecute()).isTrue(); + public void createComputer() { + assertThat(scanner.createCharHandlerFor("src/main/java/Foo.java")).isNull(); - when(exclusionPatternInitializer.hasConfiguredPatterns()).thenReturn(true); - when(inclusionPatternInitializer.hasConfiguredPatterns()).thenReturn(false); - assertThat(scanner.shouldExecute()).isTrue(); + when(exclusionPatternInitializer.getAllFilePatterns()).thenReturn(Collections.singletonList("pattern")); + scanner = new IssueExclusionsLoader(exclusionPatternInitializer, patternMatcher); + assertThat(scanner.createCharHandlerFor("src/main/java/Foo.java")).isNotNull(); - when(exclusionPatternInitializer.hasConfiguredPatterns()).thenReturn(false); - when(inclusionPatternInitializer.hasConfiguredPatterns()).thenReturn(true); - assertThat(scanner.shouldExecute()).isTrue(); - when(exclusionPatternInitializer.hasConfiguredPatterns()).thenReturn(false); - when(inclusionPatternInitializer.hasConfiguredPatterns()).thenReturn(false); - assertThat(scanner.shouldExecute()).isFalse(); } @Test - public void shouldAnalyzeProject() throws IOException { - Path javaFile1 = baseDir.resolve("src/main/java/Foo.java"); - fs.add(new TestInputFileBuilder("polop", "src/main/java/Foo.java") - .setModuleBaseDir(baseDir) - .setCharset(StandardCharsets.UTF_8) - .setType(InputFile.Type.MAIN) - .build()); - Path javaTestFile1 = baseDir.resolve("src/test/java/FooTest.java"); - fs.add(new TestInputFileBuilder("polop", "src/test/java/FooTest.java") - .setModuleBaseDir(baseDir) - .setCharset(StandardCharsets.UTF_8) - .setType(InputFile.Type.TEST) - .build()); - - when(exclusionPatternInitializer.hasFileContentPattern()).thenReturn(true); - - scanner.preLoadAllFiles(); - - verify(inclusionPatternInitializer).initializePatternsForPath("src/main/java/Foo.java", "polop:src/main/java/Foo.java"); - verify(inclusionPatternInitializer).initializePatternsForPath("src/test/java/FooTest.java", "polop:src/test/java/FooTest.java"); - verify(exclusionPatternInitializer).initializePatternsForPath("src/main/java/Foo.java", "polop:src/main/java/Foo.java"); - verify(exclusionPatternInitializer).initializePatternsForPath("src/test/java/FooTest.java", "polop:src/test/java/FooTest.java"); - verify(regexpScanner).scan("polop:src/main/java/Foo.java", javaFile1, UTF_8); - verify(regexpScanner).scan("polop:src/test/java/FooTest.java", javaTestFile1, UTF_8); - } - - @Test - public void isLoaded() { - DefaultInputFile inputFile1 = new TestInputFileBuilder("polop", "src/test/java/FooTest1.java") - .setModuleBaseDir(baseDir) - .setCharset(StandardCharsets.UTF_8) - .setType(InputFile.Type.TEST) - .build(); - DefaultInputFile inputFile2 = new TestInputFileBuilder("polop", "src/test/java/FooTest2.java") - .setModuleBaseDir(baseDir) - .setCharset(StandardCharsets.UTF_8) - .setType(InputFile.Type.TEST) - .build(); - - when(inclusionPatternInitializer.getPathForComponent(inputFile1.key())).thenReturn(null); - when(inclusionPatternInitializer.getPathForComponent(inputFile2.key())).thenReturn("path1"); - - assertFalse(scanner.isLoaded(inputFile1)); - assertTrue(scanner.isLoaded(inputFile2)); - + public void shouldHavePatternsBasedOnMulticriteriaPattern() { + IssuePattern pattern1 = new IssuePattern("org/foo/Bar.java", "*"); + IssuePattern pattern2 = new IssuePattern("org/foo/Hello.java", "checkstyle:MagicNumber"); + when(exclusionPatternInitializer.getMulticriteriaPatterns()).thenReturn(Arrays.asList(new IssuePattern[] {pattern1, pattern2})); + + IssueExclusionsLoader loader = new IssueExclusionsLoader(exclusionPatternInitializer, patternMatcher); + loader.addMulticriteriaPatterns("org/foo/Bar.java", "org.foo.Bar"); + loader.addMulticriteriaPatterns("org/foo/Baz.java", "org.foo.Baz"); + loader.addMulticriteriaPatterns("org/foo/Hello.java", "org.foo.Hello"); + + assertThat(patternMatcher.getPatternsForComponent("org.foo.Bar")).hasSize(1); + assertThat(patternMatcher.getPatternsForComponent("org.foo.Baz")).hasSize(0); + assertThat(patternMatcher.getPatternsForComponent("org.foo.Hello")).hasSize(1); } @Test - public void shouldAnalyseFilesOnlyWhenRegexConfigured() { - fs.add(new TestInputFileBuilder("polop", "src/main/java/Foo.java") - .setType(InputFile.Type.MAIN) - .setCharset(StandardCharsets.UTF_8) - .build()); - fs.add(new TestInputFileBuilder("polop", "src/test/java/FooTest.java") - .setType(InputFile.Type.TEST) - .setCharset(StandardCharsets.UTF_8) - .build()); - when(exclusionPatternInitializer.hasFileContentPattern()).thenReturn(false); - - scanner.preLoadAllFiles(); - - verify(inclusionPatternInitializer).initializePatternsForPath("src/main/java/Foo.java", "polop:src/main/java/Foo.java"); - verify(inclusionPatternInitializer).initializePatternsForPath("src/test/java/FooTest.java", "polop:src/test/java/FooTest.java"); - verify(exclusionPatternInitializer).initializePatternsForPath("src/main/java/Foo.java", "polop:src/main/java/Foo.java"); - verify(exclusionPatternInitializer).initializePatternsForPath("src/test/java/FooTest.java", "polop:src/test/java/FooTest.java"); - verifyZeroInteractions(regexpScanner); + public void shouldAnalyzeProject() throws IOException { + IssuePattern pattern = new IssuePattern("**", "*"); + when(exclusionPatternInitializer.getMulticriteriaPatterns()).thenReturn(Collections.singletonList(pattern)); + when(exclusionPatternInitializer.hasMulticriteriaPatterns()).thenReturn(true); + + PatternMatcher patternMatcher = mock(PatternMatcher.class); + IssueExclusionsLoader loader = new IssueExclusionsLoader(exclusionPatternInitializer, patternMatcher); + assertThat(loader.shouldExecute()).isTrue(); + loader.addMulticriteriaPatterns("src/main/java/Foo.java", "polop:src/main/java/Foo.java"); + loader.addMulticriteriaPatterns("src/test/java/FooTest.java", "polop:src/test/java/FooTest.java"); + + verify(patternMatcher).addPatternForComponent("polop:src/main/java/Foo.java", pattern); + verify(patternMatcher).addPatternForComponent("polop:src/test/java/FooTest.java", pattern); + verifyNoMoreInteractions(patternMatcher); } @Test - public void shouldReportFailure() throws IOException { - Path phpFile1 = baseDir.resolve("src/Foo.php"); - fs.add(new TestInputFileBuilder("polop", "src/Foo.php") - .setModuleBaseDir(baseDir) - .setType(InputFile.Type.MAIN) - .setCharset(StandardCharsets.UTF_8) - .build()); - - when(exclusionPatternInitializer.hasFileContentPattern()).thenReturn(true); - doThrow(new IOException("BUG")).when(regexpScanner).scan("polop:src/Foo.php", phpFile1, UTF_8); - - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Unable to read the source file"); + public void shouldExecute() { + when(exclusionPatternInitializer.hasMulticriteriaPatterns()).thenReturn(true); + assertThat(scanner.shouldExecute()).isTrue(); - scanner.preLoadAllFiles(); + when(exclusionPatternInitializer.hasMulticriteriaPatterns()).thenReturn(false); + assertThat(scanner.shouldExecute()).isFalse(); } } diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/ignore/scanner/IssueExclusionsRegexpScannerTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/ignore/scanner/IssueExclusionsRegexpScannerTest.java index 55581e74adc..37c2b957b65 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/ignore/scanner/IssueExclusionsRegexpScannerTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/ignore/scanner/IssueExclusionsRegexpScannerTest.java @@ -19,150 +19,146 @@ */ package org.sonar.scanner.issue.ignore.scanner; -import com.google.common.collect.Sets; import com.google.common.io.Resources; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; +import org.sonar.api.batch.fs.internal.FileMetadata; import org.sonar.scanner.issue.ignore.pattern.IssueExclusionPatternInitializer; -import org.sonar.scanner.issue.ignore.pattern.IssuePattern; import org.sonar.scanner.issue.ignore.pattern.LineRange; import org.sonar.scanner.issue.ignore.pattern.PatternMatcher; import org.sonar.scanner.issue.ignore.scanner.IssueExclusionsRegexpScanner; +import org.sonar.scanner.issue.ignore.scanner.IssueExclusionsLoader.DoubleRegexpMatcher; + +import java.net.URISyntaxException; +import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; import java.util.Set; +import java.util.regex.Pattern; import static java.nio.charset.StandardCharsets.UTF_8; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.when; public class IssueExclusionsRegexpScannerTest { - - private IssueExclusionsRegexpScanner regexpScanner; - private String javaFile; + @Mock private IssueExclusionPatternInitializer patternsInitializer; @Mock private PatternMatcher patternMatcher; - @Mock - private IssuePattern allFilePattern; - @Mock - private IssuePattern blockPattern1; - @Mock - private IssuePattern blockPattern2; + + private List<Pattern> allFilePatterns; + private List<DoubleRegexpMatcher> blockPatterns; + private IssueExclusionsRegexpScanner regexpScanner; + private FileMetadata fileMetadata = new FileMetadata(); @Before public void init() { MockitoAnnotations.initMocks(this); - when(allFilePattern.getAllFileRegexp()).thenReturn("@SONAR-IGNORE-ALL"); - when(blockPattern1.getBeginBlockRegexp()).thenReturn("// SONAR-OFF"); - when(blockPattern1.getEndBlockRegexp()).thenReturn("// SONAR-ON"); - when(blockPattern2.getBeginBlockRegexp()).thenReturn("// FOO-OFF"); - when(blockPattern2.getEndBlockRegexp()).thenReturn("// FOO-ON"); - when(patternsInitializer.getAllFilePatterns()).thenReturn(Arrays.asList(allFilePattern)); - when(patternsInitializer.getBlockPatterns()).thenReturn(Arrays.asList(blockPattern1, blockPattern2)); - when(patternsInitializer.getPatternMatcher()).thenReturn(patternMatcher); - - regexpScanner = new IssueExclusionsRegexpScanner(patternsInitializer); - verify(patternsInitializer, times(1)).getAllFilePatterns(); - verify(patternsInitializer, times(1)).getBlockPatterns(); + blockPatterns = Arrays.asList(new DoubleRegexpMatcher[] { + new DoubleRegexpMatcher(Pattern.compile("// SONAR-OFF"), Pattern.compile("// SONAR-ON")), + new DoubleRegexpMatcher(Pattern.compile("// FOO-OFF"), Pattern.compile("// FOO-ON")) + }); + allFilePatterns = Collections.singletonList(Pattern.compile("@SONAR-IGNORE-ALL")); javaFile = "org.sonar.test.MyFile"; + regexpScanner = new IssueExclusionsRegexpScanner(javaFile, allFilePatterns, blockPatterns, patternMatcher); + } + + @Test + public void shouldDetectPatternLastLine() throws URISyntaxException { + fileMetadata.readMetadata(getResource("file-with-single-regexp-last-line.txt").toFile(), UTF_8, regexpScanner); + + verify(patternMatcher, times(1)).addPatternToExcludeResource(javaFile); + verifyNoMoreInteractions(patternMatcher); } @Test public void shouldDoNothing() throws Exception { - regexpScanner.scan(javaFile, Paths.get(Resources.getResource( - "org/sonar/scanner/issue/ignore/scanner/IssueExclusionsRegexpScannerTest/file-with-no-regexp.txt").toURI()), UTF_8); - - verifyNoMoreInteractions(patternsInitializer); + fileMetadata.readMetadata(getResource("file-with-no-regexp.txt").toFile(), UTF_8, regexpScanner); + verifyNoMoreInteractions(patternMatcher); } @Test public void shouldAddPatternToExcludeFile() throws Exception { - regexpScanner.scan(javaFile, Paths.get(Resources.getResource( - "org/sonar/scanner/issue/ignore/scanner/IssueExclusionsRegexpScannerTest/file-with-single-regexp.txt").toURI()), UTF_8); + fileMetadata.readMetadata(getResource("file-with-single-regexp.txt").toFile(), UTF_8, regexpScanner); - verify(patternsInitializer).getPatternMatcher(); verify(patternMatcher, times(1)).addPatternToExcludeResource(javaFile); - verifyNoMoreInteractions(patternsInitializer); + verifyNoMoreInteractions(patternMatcher); } @Test public void shouldAddPatternToExcludeFileEvenIfAlsoDoubleRegexps() throws Exception { - regexpScanner.scan(javaFile, Paths.get(Resources.getResource( - "org/sonar/scanner/issue/ignore/scanner/IssueExclusionsRegexpScannerTest/file-with-single-regexp-and-double-regexp.txt").toURI()), UTF_8); + fileMetadata.readMetadata(getResource("file-with-single-regexp-and-double-regexp.txt").toFile(), UTF_8, regexpScanner); - verify(patternsInitializer).getPatternMatcher(); + Set<LineRange> lineRanges = new HashSet<>(); + lineRanges.add(new LineRange(5, 26)); verify(patternMatcher, times(1)).addPatternToExcludeResource(javaFile); - verifyNoMoreInteractions(patternsInitializer); + verify(patternMatcher, times(1)).addPatternToExcludeLines(javaFile, lineRanges); + verifyNoMoreInteractions(patternMatcher); } @Test public void shouldAddPatternToExcludeLines() throws Exception { - regexpScanner.scan(javaFile, Paths.get(Resources.getResource( - "org/sonar/scanner/issue/ignore/scanner/IssueExclusionsRegexpScannerTest/file-with-double-regexp.txt").toURI()), UTF_8); + fileMetadata.readMetadata(getResource("file-with-double-regexp.txt").toFile(), UTF_8, regexpScanner); - Set<LineRange> lineRanges = Sets.newHashSet(); + Set<LineRange> lineRanges = new HashSet<>(); lineRanges.add(new LineRange(21, 25)); - verify(patternsInitializer).getPatternMatcher(); verify(patternMatcher, times(1)).addPatternToExcludeLines(javaFile, lineRanges); - verifyNoMoreInteractions(patternsInitializer); + verifyNoMoreInteractions(patternMatcher); } @Test public void shouldAddPatternToExcludeLinesTillTheEnd() throws Exception { - regexpScanner.scan(javaFile, Paths.get(Resources.getResource( - "org/sonar/scanner/issue/ignore/scanner/IssueExclusionsRegexpScannerTest/file-with-double-regexp-unfinished.txt").toURI()), UTF_8); + fileMetadata.readMetadata(getResource("file-with-double-regexp-unfinished.txt").toFile(), UTF_8, regexpScanner); - Set<LineRange> lineRanges = Sets.newHashSet(); + Set<LineRange> lineRanges = new HashSet<>(); lineRanges.add(new LineRange(21, 34)); - verify(patternsInitializer).getPatternMatcher(); verify(patternMatcher, times(1)).addPatternToExcludeLines(javaFile, lineRanges); - verifyNoMoreInteractions(patternsInitializer); + verifyNoMoreInteractions(patternMatcher); } @Test public void shouldAddPatternToExcludeSeveralLineRanges() throws Exception { - regexpScanner.scan(javaFile, Paths.get(Resources.getResource( - "org/sonar/scanner/issue/ignore/scanner/IssueExclusionsRegexpScannerTest/file-with-double-regexp-twice.txt").toURI()), UTF_8); + fileMetadata.readMetadata(getResource("file-with-double-regexp-twice.txt").toFile(), UTF_8, regexpScanner); - Set<LineRange> lineRanges = Sets.newHashSet(); + Set<LineRange> lineRanges = new HashSet<>(); lineRanges.add(new LineRange(21, 25)); lineRanges.add(new LineRange(29, 33)); - verify(patternsInitializer).getPatternMatcher(); verify(patternMatcher, times(1)).addPatternToExcludeLines(javaFile, lineRanges); - verifyNoMoreInteractions(patternsInitializer); + verifyNoMoreInteractions(patternMatcher); } @Test public void shouldAddPatternToExcludeLinesWithWrongOrder() throws Exception { - regexpScanner.scan(javaFile, Paths.get(Resources.getResource( - "org/sonar/scanner/issue/ignore/scanner/IssueExclusionsRegexpScannerTest/file-with-double-regexp-wrong-order.txt").toURI()), UTF_8); + fileMetadata.readMetadata(getResource("file-with-double-regexp-wrong-order.txt").toFile(), UTF_8, regexpScanner); - Set<LineRange> lineRanges = Sets.newHashSet(); + Set<LineRange> lineRanges = new HashSet<>(); lineRanges.add(new LineRange(25, 35)); - verify(patternsInitializer).getPatternMatcher(); verify(patternMatcher, times(1)).addPatternToExcludeLines(javaFile, lineRanges); - verifyNoMoreInteractions(patternsInitializer); + verifyNoMoreInteractions(patternMatcher); } @Test public void shouldAddPatternToExcludeLinesWithMess() throws Exception { - regexpScanner.scan(javaFile, Paths.get(Resources.getResource( - "org/sonar/scanner/issue/ignore/scanner/IssueExclusionsRegexpScannerTest/file-with-double-regexp-mess.txt").toURI()), UTF_8); + fileMetadata.readMetadata(getResource("file-with-double-regexp-mess.txt").toFile(), UTF_8, regexpScanner); - Set<LineRange> lineRanges = Sets.newHashSet(); + Set<LineRange> lineRanges = new HashSet<>(); lineRanges.add(new LineRange(21, 29)); - verify(patternsInitializer).getPatternMatcher(); verify(patternMatcher, times(1)).addPatternToExcludeLines(javaFile, lineRanges); - verifyNoMoreInteractions(patternsInitializer); + verifyNoMoreInteractions(patternMatcher); + } + + private Path getResource(String fileName) throws URISyntaxException { + return Paths.get(Resources.getResource("org/sonar/scanner/issue/ignore/scanner/IssueExclusionsRegexpScannerTest/" + fileName).toURI()); } } diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/mediumtest/fs/FileSystemMediumTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/mediumtest/fs/FileSystemMediumTest.java index 6f569def502..d14f205ed8a 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/mediumtest/fs/FileSystemMediumTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/mediumtest/fs/FileSystemMediumTest.java @@ -349,8 +349,8 @@ public class FileSystemMediumTest { .start(); assertThat(logs.getAllAsString()).containsOnlyOnce("'src/myfile.binary' indexed with language 'null'"); - assertThat(logs.getAllAsString()).doesNotContain("Scanning com.foo.project:src/myfile.binary"); - assertThat(logs.getAllAsString()).containsOnlyOnce("Scanning com.foo.project:src/sample.xoo"); + assertThat(logs.getAllAsString()).doesNotContain("'src/myfile.binary' generating issue exclusions"); + assertThat(logs.getAllAsString()).containsOnlyOnce("'src/sample.xoo' generating issue exclusions"); tester2.stop(); @@ -366,7 +366,7 @@ public class FileSystemMediumTest { srcDir.mkdir(); File xooFile = new File(srcDir, "sample.xoo"); - FileUtils.write(xooFile, "Sample xoo\ncontent"); + FileUtils.write(xooFile, "Sample xoo\npattern"); File unknownFile = new File(srcDir, "myfile.binary"); FileUtils.write(unknownFile, "some text"); @@ -376,8 +376,9 @@ public class FileSystemMediumTest { .put("sonar.sources", "src") .build()) .start(); - - assertThat(logs.getAllAsString()).containsOnlyOnce("Scanning com.foo.project:src/myfile.binary"); + + assertThat(logs.getAllAsString()).containsOnlyOnce("- Exclusion pattern 'pattern'"); + assertThat(logs.getAllAsString()).containsOnlyOnce("'src/myfile.binary' generating issue exclusions"); } @Test diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/filesystem/MetadataGeneratorProviderTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/filesystem/MetadataGeneratorProviderTest.java index 965540c1047..c9c7312fab5 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/filesystem/MetadataGeneratorProviderTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/filesystem/MetadataGeneratorProviderTest.java @@ -23,6 +23,9 @@ import org.junit.Test; import org.mockito.Mockito; import org.sonar.api.batch.fs.internal.DefaultInputModule; import org.sonar.api.batch.fs.internal.FileMetadata; +import org.sonar.scanner.issue.ignore.pattern.IssueExclusionPatternInitializer; +import org.sonar.scanner.issue.ignore.pattern.PatternMatcher; +import org.sonar.scanner.issue.ignore.scanner.IssueExclusionsLoader; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; @@ -31,8 +34,9 @@ public class MetadataGeneratorProviderTest { @Test public void create_builder() { StatusDetectionFactory statusDetectionFactory = mock(StatusDetectionFactory.class, Mockito.RETURNS_MOCKS); + IssueExclusionsLoader issueExclusionsLoader = new IssueExclusionsLoader(mock(IssueExclusionPatternInitializer.class), mock(PatternMatcher.class)); MetadataGeneratorProvider factory = new MetadataGeneratorProvider(); - assertThat(factory.provide(new DefaultInputModule("module"), statusDetectionFactory, new FileMetadata())).isNotNull(); + assertThat(factory.provide(new DefaultInputModule("module"), statusDetectionFactory, new FileMetadata(), issueExclusionsLoader)).isNotNull(); } } diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/filesystem/MetadataGeneratorTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/filesystem/MetadataGeneratorTest.java index 9fddf40b8e1..67b455a9986 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/filesystem/MetadataGeneratorTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/filesystem/MetadataGeneratorTest.java @@ -20,6 +20,7 @@ package org.sonar.scanner.scan.filesystem; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.nio.charset.StandardCharsets; @@ -40,6 +41,9 @@ import org.sonar.api.batch.fs.internal.DefaultInputModule; import org.sonar.api.batch.fs.internal.FileMetadata; import org.sonar.api.batch.fs.internal.TestInputFileBuilder; import org.sonar.api.utils.PathUtils; +import org.sonar.scanner.issue.ignore.pattern.IssueExclusionPatternInitializer; +import org.sonar.scanner.issue.ignore.pattern.PatternMatcher; +import org.sonar.scanner.issue.ignore.scanner.IssueExclusionsLoader; public class MetadataGeneratorTest { @Rule @@ -57,7 +61,8 @@ public class MetadataGeneratorTest { public void setUp() { MockitoAnnotations.initMocks(this); metadata = new FileMetadata(); - generator = new MetadataGenerator(new DefaultInputModule("module"), statusDetection, metadata); + IssueExclusionsLoader issueExclusionsLoader = new IssueExclusionsLoader(mock(IssueExclusionPatternInitializer.class), mock(PatternMatcher.class)); + generator = new MetadataGenerator(new DefaultInputModule("module"), statusDetection, metadata, issueExclusionsLoader); } @Test diff --git a/sonar-scanner-engine/src/test/resources/org/sonar/scanner/issue/ignore/scanner/IssueExclusionsRegexpScannerTest/file-with-single-regexp-last-line.txt b/sonar-scanner-engine/src/test/resources/org/sonar/scanner/issue/ignore/scanner/IssueExclusionsRegexpScannerTest/file-with-single-regexp-last-line.txt new file mode 100644 index 00000000000..ef135ebc50c --- /dev/null +++ b/sonar-scanner-engine/src/test/resources/org/sonar/scanner/issue/ignore/scanner/IssueExclusionsRegexpScannerTest/file-with-single-regexp-last-line.txt @@ -0,0 +1,33 @@ +package org.sonar.plugins.switchoffviolations.pattern; + +import com.google.common.collect.Sets; + +import java.util.Set; + +/** + * @SONAR-IGNORE-ALL + */ +public class LineRange { + int from, to; + + public LineRange(int from, int to) { + if (to < from) { + throw new IllegalArgumentException("Line range is not valid: " + from + " must be greater than " + to); + } + this.from = from; + this.to = to; + } + + public boolean in(int lineId) { + return from <= lineId && lineId <= to; + } + + public Set<Integer> toLines() { + Set<Integer> lines = Sets.newLinkedHashSet(); + for (int index = from; index <= to; index++) { + lines.add(index); + } + return lines; + } + +}
\ No newline at end of file diff --git a/sonar-scanner-engine/src/test/resources/org/sonar/scanner/issue/ignore/scanner/IssueExclusionsRegexpScannerTest/file-with-single-regexp.txt b/sonar-scanner-engine/src/test/resources/org/sonar/scanner/issue/ignore/scanner/IssueExclusionsRegexpScannerTest/file-with-single-regexp.txt index ef135ebc50c..88ad675955f 100644 --- a/sonar-scanner-engine/src/test/resources/org/sonar/scanner/issue/ignore/scanner/IssueExclusionsRegexpScannerTest/file-with-single-regexp.txt +++ b/sonar-scanner-engine/src/test/resources/org/sonar/scanner/issue/ignore/scanner/IssueExclusionsRegexpScannerTest/file-with-single-regexp.txt @@ -4,9 +4,6 @@ import com.google.common.collect.Sets; import java.util.Set; -/** - * @SONAR-IGNORE-ALL - */ public class LineRange { int from, to; @@ -30,4 +27,5 @@ public class LineRange { return lines; } -}
\ No newline at end of file +} +// @SONAR-IGNORE-ALL
\ No newline at end of file |