From c9fe310c12427cb8881956bbe42e187aa0ade845 Mon Sep 17 00:00:00 2001 From: Godin Date: Thu, 21 Oct 2010 22:44:21 +0000 Subject: [PATCH] SONAR-1772: Remove old code, add tests --- .../findbugs/FindbugsConfiguration.java | 6 - .../findbugs/FindbugsMavenPluginHandler.java | 159 --------------- .../findbugs/FindbugsNativeSensor.java | 73 ------- .../plugins/findbugs/FindbugsPlugin.java | 3 +- .../plugins/findbugs/FindbugsSensor.java | 49 ++--- .../findbugs/FindbugsAntConverterTest.java | 45 +++- .../findbugs/FindbugsConfigurationTest.java | 46 +++++ .../findbugs/FindbugsExecutorTest.java | 28 ++- .../FindbugsMavenPluginHandlerTest.java | 193 ------------------ .../findbugs/FindbugsNativeSensorTest.java | 123 ----------- .../plugins/findbugs/FindbugsSensorTest.java | 69 ++++--- 11 files changed, 168 insertions(+), 626 deletions(-) delete mode 100644 plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/FindbugsMavenPluginHandler.java delete mode 100644 plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/FindbugsNativeSensor.java create mode 100644 plugins/sonar-findbugs-plugin/src/test/java/org/sonar/plugins/findbugs/FindbugsConfigurationTest.java delete mode 100644 plugins/sonar-findbugs-plugin/src/test/java/org/sonar/plugins/findbugs/FindbugsMavenPluginHandlerTest.java delete mode 100644 plugins/sonar-findbugs-plugin/src/test/java/org/sonar/plugins/findbugs/FindbugsNativeSensorTest.java diff --git a/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/FindbugsConfiguration.java b/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/FindbugsConfiguration.java index dd2321c5fb7..5541701a6e1 100644 --- a/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/FindbugsConfiguration.java +++ b/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/FindbugsConfiguration.java @@ -4,8 +4,6 @@ import org.apache.commons.lang.StringUtils; import org.sonar.api.BatchExtension; import org.sonar.api.CoreProperties; import org.sonar.api.batch.ProjectClasspath; -import org.sonar.api.batch.maven.MavenPlugin; -import org.sonar.api.batch.maven.MavenUtils; import org.sonar.api.profiles.RulesProfile; import org.sonar.api.resources.Project; import org.sonar.api.utils.SonarException; @@ -62,10 +60,6 @@ public class FindbugsConfiguration implements BatchExtension { return findbugsProject; } - protected MavenPlugin getFindbugsMavenPlugin() { - return MavenPlugin.getPlugin(project.getPom(), MavenUtils.GROUP_ID_CODEHAUS_MOJO, "findbugs-maven-plugin"); - } - public File saveIncludeConfigXml() throws IOException { StringWriter conf = new StringWriter(); exporter.exportProfile(profile, conf); diff --git a/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/FindbugsMavenPluginHandler.java b/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/FindbugsMavenPluginHandler.java deleted file mode 100644 index 37091a968f0..00000000000 --- a/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/FindbugsMavenPluginHandler.java +++ /dev/null @@ -1,159 +0,0 @@ -/* - * Sonar, open source software quality management tool. - * Copyright (C) 2009 SonarSource SA - * mailto:contact AT sonarsource DOT com - * - * Sonar is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * Sonar is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with Sonar; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 - */ -package org.sonar.plugins.findbugs; - -import java.io.File; -import java.io.IOException; -import java.io.StringWriter; - -import org.apache.commons.lang.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.sonar.api.CoreProperties; -import org.sonar.api.batch.maven.MavenPlugin; -import org.sonar.api.batch.maven.MavenPluginHandler; -import org.sonar.api.batch.maven.MavenUtils; -import org.sonar.api.profiles.RulesProfile; -import org.sonar.api.resources.Project; -import org.sonar.api.utils.SonarException; -import org.sonar.plugins.findbugs.xml.ClassFilter; -import org.sonar.plugins.findbugs.xml.FindBugsFilter; -import org.sonar.plugins.findbugs.xml.Match; - -public class FindbugsMavenPluginHandler implements MavenPluginHandler { - - private static Logger LOG = LoggerFactory.getLogger(FindbugsMavenPluginHandler.class); - - private RulesProfile profile; - private FindbugsProfileExporter exporter; - - public FindbugsMavenPluginHandler(RulesProfile profile, FindbugsProfileExporter exporter) { - this.profile = profile; - this.exporter = exporter; - } - - public String getGroupId() { - return MavenUtils.GROUP_ID_CODEHAUS_MOJO; - } - - public String getArtifactId() { - return "findbugs-maven-plugin"; - } - - public String getVersion() { - // IMPORTANT : the version of the Findbugs lib must be also updated in the pom.xml (property findbugs.version). - return "2.3.1"; - } - - public boolean isFixedVersion() { - return true; - } - - public String[] getGoals() { - return new String[] { "findbugs" }; - } - - public void configure(Project project, MavenPlugin plugin) { - configureClassesDir(project, plugin); - configureBasicParameters(project, plugin); - configureFilters(project, plugin); - } - - private void configureBasicParameters(Project project, MavenPlugin plugin) { - plugin.setParameter("xmlOutput", "true"); - plugin.setParameter("threshold", "Low"); - plugin.setParameter("skip", "false"); - plugin.setParameter("effort", getEffort(project), false); - plugin.setParameter("maxHeap", "" + getMaxHeap(project), false); - String timeout = getTimeout(project); - if (StringUtils.isNotBlank(timeout)) { - plugin.setParameter("timeout", timeout, false); - } - } - - protected void configureFilters(Project project, MavenPlugin plugin) { - try { - String existingIncludeFilterConfig = plugin.getParameter("includeFilterFile"); - String existingExcludeFilterConfig = plugin.getParameter("excludeFilterFile"); - boolean existingConfig = !StringUtils.isBlank(existingIncludeFilterConfig) || !StringUtils.isBlank(existingExcludeFilterConfig); - if (project.getReuseExistingRulesConfig()) { - LOG.warn("Reusing existing Findbugs configuration is deprecated as it's unstable and can not provide meaningful results. This feature will be removed soon."); - } - if ( !project.getReuseExistingRulesConfig() || (project.getReuseExistingRulesConfig() && !existingConfig)) { - File includeXmlFile = saveIncludeConfigXml(project); - plugin.setParameter("includeFilterFile", getPath(includeXmlFile)); - - File excludeXmlFile = saveExcludeConfigXml(project); - plugin.setParameter("excludeFilterFile", getPath(excludeXmlFile)); - } - - } catch (IOException e) { - throw new SonarException("Failed to save the findbugs XML configuration.", e); - } - } - - private String getPath(File file) throws IOException { - // the findbugs maven plugin fails on windows if the path contains backslashes - String path = file.getCanonicalPath(); - return path.replace('\\', '/'); - } - - private void configureClassesDir(Project project, MavenPlugin plugin) { - File classesDir = project.getFileSystem().getBuildOutputDir(); - if (classesDir == null || !classesDir.exists()) { - throw new SonarException("Findbugs needs sources to be compiled. " - + "Please build project or edit pom.xml to set the property before executing sonar."); - } - try { - plugin.setParameter("classFilesDirectory", classesDir.getCanonicalPath()); - } catch (Exception e) { - throw new SonarException("Invalid classes directory", e); - } - } - - private File saveIncludeConfigXml(Project project) throws IOException { - StringWriter conf = new StringWriter(); - exporter.exportProfile(profile, conf); - return project.getFileSystem().writeToWorkingDirectory(conf.toString(), "findbugs-include.xml"); - } - - private File saveExcludeConfigXml(Project project) throws IOException { - FindBugsFilter findBugsFilter = new FindBugsFilter(); - if (project.getExclusionPatterns() != null) { - for (String exclusion : project.getExclusionPatterns()) { - ClassFilter classFilter = new ClassFilter(FindbugsAntConverter.antToJavaRegexpConvertor(exclusion)); - findBugsFilter.addMatch(new Match(classFilter)); - } - } - return project.getFileSystem().writeToWorkingDirectory(findBugsFilter.toXml(), "findbugs-exclude.xml"); - } - - private String getEffort(Project project) { - return project.getConfiguration().getString(CoreProperties.FINDBUGS_EFFORT_PROPERTY, CoreProperties.FINDBUGS_EFFORT_DEFAULT_VALUE); - } - - private int getMaxHeap(Project project) { - return project.getConfiguration().getInt(CoreProperties.FINDBUGS_MAXHEAP_PROPERTY, CoreProperties.FINDBUGS_MAXHEAP_DEFAULT_VALUE); - } - - private String getTimeout(Project project) { - return project.getConfiguration().getString(CoreProperties.FINDBUGS_TIMEOUT_PROPERTY); - } -} diff --git a/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/FindbugsNativeSensor.java b/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/FindbugsNativeSensor.java deleted file mode 100644 index b6efd0131da..00000000000 --- a/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/FindbugsNativeSensor.java +++ /dev/null @@ -1,73 +0,0 @@ -package org.sonar.plugins.findbugs; - -import org.apache.commons.lang.StringUtils; -import org.sonar.api.CoreProperties; -import org.sonar.api.batch.Sensor; -import org.sonar.api.batch.SensorContext; -import org.sonar.api.profiles.RulesProfile; -import org.sonar.api.resources.JavaFile; -import org.sonar.api.resources.Project; -import org.sonar.api.rules.Rule; -import org.sonar.api.rules.RuleFinder; -import org.sonar.api.rules.Violation; -import org.sonar.api.utils.Logs; - -import java.io.File; -import java.util.List; - -/** - * EXPERIMENTAL! - * - * @since 2.4 - */ -public class FindbugsNativeSensor implements Sensor { - - private RulesProfile profile; - private RuleFinder ruleFinder; - private FindbugsExecutor executor; - - public FindbugsNativeSensor(RulesProfile profile, RuleFinder ruleFinder, FindbugsExecutor executor) { - this.profile = profile; - this.ruleFinder = ruleFinder; - this.executor = executor; - } - - public boolean shouldExecuteOnProject(Project project) { - return project.getFileSystem().hasJavaSourceFiles() - && ( !profile.getActiveRulesByRepository(FindbugsConstants.REPOSITORY_KEY).isEmpty() || project.getReuseExistingRulesConfig()) - && project.getPom() != null && !StringUtils.equalsIgnoreCase(project.getPom().getPackaging(), "ear"); - } - - public void analyse(Project project, SensorContext context) { - if (project.getReuseExistingRulesConfig()) { - Logs.INFO.warn("Reusing existing Findbugs configuration not supported anymore."); - } - File report = getFindbugsReportFile(project); - if (report == null) { - report = executor.execute(); - } - FindbugsXmlReportParser reportParser = new FindbugsXmlReportParser(report); - List fbViolations = reportParser.getViolations(); - for (FindbugsXmlReportParser.Violation fbViolation : fbViolations) { - Rule rule = ruleFinder.findByKey(FindbugsConstants.REPOSITORY_KEY, fbViolation.getType()); - JavaFile resource = new JavaFile(fbViolation.getSonarJavaFileKey()); - if (context.getResource(resource) != null) { - Violation violation = Violation.create(rule, resource).setLineId(fbViolation.getStart()).setMessage(fbViolation.getLongMessage()); - context.saveViolation(violation); - } - } - } - - protected final File getFindbugsReportFile(Project project) { - if (project.getConfiguration().getString(CoreProperties.FINDBUGS_REPORT_PATH) != null) { - return new File(project.getConfiguration().getString(CoreProperties.FINDBUGS_REPORT_PATH)); - } - return null; - } - - @Override - public String toString() { - return getClass().getSimpleName(); - } - -} diff --git a/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/FindbugsPlugin.java b/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/FindbugsPlugin.java index 0dec503b018..6d07e3a961f 100644 --- a/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/FindbugsPlugin.java +++ b/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/FindbugsPlugin.java @@ -69,10 +69,9 @@ public class FindbugsPlugin implements Plugin { public List> getExtensions() { List> list = new ArrayList>(); - list.add(FindbugsNativeSensor.class); + list.add(FindbugsSensor.class); list.add(FindbugsConfiguration.class); list.add(FindbugsExecutor.class); - // list.add(FindbugsMavenPluginHandler.class); list.add(FindbugsRuleRepository.class); list.add(FindbugsProfileExporter.class); list.add(FindbugsProfileImporter.class); diff --git a/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/FindbugsSensor.java b/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/FindbugsSensor.java index eb93d2fc218..24350cb61ee 100644 --- a/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/FindbugsSensor.java +++ b/plugins/sonar-findbugs-plugin/src/main/java/org/sonar/plugins/findbugs/FindbugsSensor.java @@ -19,40 +19,46 @@ */ package org.sonar.plugins.findbugs; -import java.io.File; -import java.util.List; - import org.apache.commons.lang.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.sonar.api.CoreProperties; import org.sonar.api.batch.Sensor; import org.sonar.api.batch.SensorContext; -import org.sonar.api.batch.maven.DependsUponMavenPlugin; -import org.sonar.api.batch.maven.MavenPluginHandler; import org.sonar.api.profiles.RulesProfile; import org.sonar.api.resources.JavaFile; import org.sonar.api.resources.Project; import org.sonar.api.rules.Rule; import org.sonar.api.rules.RuleFinder; import org.sonar.api.rules.Violation; +import org.sonar.api.utils.Logs; -public class FindbugsSensor implements Sensor, DependsUponMavenPlugin { +import java.io.File; +import java.util.List; +public class FindbugsSensor implements Sensor { private RulesProfile profile; private RuleFinder ruleFinder; - private FindbugsMavenPluginHandler pluginHandler; - private static Logger LOG = LoggerFactory.getLogger(FindbugsSensor.class); + private FindbugsExecutor executor; - public FindbugsSensor(RulesProfile profile, RuleFinder ruleFinder, FindbugsMavenPluginHandler pluginHandler) { + public FindbugsSensor(RulesProfile profile, RuleFinder ruleFinder, FindbugsExecutor executor) { this.profile = profile; this.ruleFinder = ruleFinder; - this.pluginHandler = pluginHandler; + this.executor = executor; + } + + public boolean shouldExecuteOnProject(Project project) { + return project.getFileSystem().hasJavaSourceFiles() + && ( !profile.getActiveRulesByRepository(FindbugsConstants.REPOSITORY_KEY).isEmpty() || project.getReuseExistingRulesConfig()) + && project.getPom() != null && !StringUtils.equalsIgnoreCase(project.getPom().getPackaging(), "ear"); } public void analyse(Project project, SensorContext context) { + if (project.getReuseExistingRulesConfig()) { + Logs.INFO.warn("Reusing existing Findbugs configuration not supported anymore."); + } File report = getFindbugsReportFile(project); - LOG.info("Findbugs output report: " + report.getAbsolutePath()); + if (report == null) { + report = executor.execute(); + } FindbugsXmlReportParser reportParser = new FindbugsXmlReportParser(report); List fbViolations = reportParser.getViolations(); for (FindbugsXmlReportParser.Violation fbViolation : fbViolations) { @@ -69,24 +75,11 @@ public class FindbugsSensor implements Sensor, DependsUponMavenPlugin { if (project.getConfiguration().getString(CoreProperties.FINDBUGS_REPORT_PATH) != null) { return new File(project.getConfiguration().getString(CoreProperties.FINDBUGS_REPORT_PATH)); } - return new File(project.getFileSystem().getBuildDir(), "findbugsXml.xml"); - } - - public boolean shouldExecuteOnProject(Project project) { - return project.getFileSystem().hasJavaSourceFiles() - && ( !profile.getActiveRulesByRepository(FindbugsConstants.REPOSITORY_KEY).isEmpty() || project.getReuseExistingRulesConfig()) - && project.getPom() != null && !StringUtils.equalsIgnoreCase(project.getPom().getPackaging(), "ear"); - } - - public MavenPluginHandler getMavenPluginHandler(Project project) { - if (project.getConfiguration().getString(CoreProperties.FINDBUGS_REPORT_PATH) != null) { - return null; - } - return pluginHandler; + return null; } @Override public String toString() { return getClass().getSimpleName(); } -} \ No newline at end of file +} diff --git a/plugins/sonar-findbugs-plugin/src/test/java/org/sonar/plugins/findbugs/FindbugsAntConverterTest.java b/plugins/sonar-findbugs-plugin/src/test/java/org/sonar/plugins/findbugs/FindbugsAntConverterTest.java index e47a02c72a2..d3625f052a4 100644 --- a/plugins/sonar-findbugs-plugin/src/test/java/org/sonar/plugins/findbugs/FindbugsAntConverterTest.java +++ b/plugins/sonar-findbugs-plugin/src/test/java/org/sonar/plugins/findbugs/FindbugsAntConverterTest.java @@ -19,21 +19,56 @@ */ package org.sonar.plugins.findbugs; -import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; + +import org.hamcrest.core.Is; import org.junit.Test; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + public class FindbugsAntConverterTest { @Test public void convertToJavaRegexFormat() { - assertRegex("foo", "~foo"); - assertRegex("**/*Test.java", "~(.*\\.)?[^\\\\^\\s]*Test"); + assertAntPatternEqualsToFindBugsRegExp("foo", "~foo", "foo"); + assertAntPatternEqualsToFindBugsRegExp("**/*Test.java", "~(.*\\.)?[^\\\\^\\s]*Test", "Test"); + assertAntPatternEqualsToFindBugsRegExp("**/*Test.java", "~(.*\\.)?[^\\\\^\\s]*Test", "foo.bar.Test"); } - private void assertRegex(String antRegex, String javaRegex) { - assertThat(FindbugsAntConverter.antToJavaRegexpConvertor(antRegex), is(javaRegex)); + @Test + public void shouldConvertAntToJavaRegexp() { + // see SONAR-853 + assertAntPatternEqualsToFindBugsRegExp("?", "~.", "g"); + assertAntPatternEqualsToFindBugsRegExp("*/myClass.JaVa", "~([^\\\\^\\s]*\\.)?myClass", "foo.bar.test.myClass"); + assertAntPatternEqualsToFindBugsRegExp("*/myClass.java", "~([^\\\\^\\s]*\\.)?myClass", "foo.bar.test.myClass"); + assertAntPatternEqualsToFindBugsRegExp("*/myClass2.jav", "~([^\\\\^\\s]*\\.)?myClass2", "foo.bar.test.myClass2"); + assertAntPatternEqualsToFindBugsRegExp("*/myOtherClass", "~([^\\\\^\\s]*\\.)?myOtherClass", "foo.bar.test.myOtherClass"); + assertAntPatternEqualsToFindBugsRegExp("*", "~[^\\\\^\\s]*", "ga.%#123_(*"); + assertAntPatternEqualsToFindBugsRegExp("**", "~.*", "gd.3reqg.3151];9#@!"); + assertAntPatternEqualsToFindBugsRegExp("**/generated/**", "~(.*\\.)?generated\\..*", "!@$Rq/32T$).generated.##TR.e#@!$"); + assertAntPatternEqualsToFindBugsRegExp("**/cl*nt/*", "~(.*\\.)?cl[^\\\\^\\s]*nt\\.[^\\\\^\\s]*", "!#$_.clr31r#!$(nt.!#$QRW)(."); + assertAntPatternEqualsToFindBugsRegExp("**/org/apache/commons/**", "~(.*\\.)?org\\.apache\\.commons\\..*", "org.apache.commons.httpclient.contrib.ssl"); + assertAntPatternEqualsToFindBugsRegExp("*/org/apache/commons/**", "~([^\\\\^\\s]*\\.)?org\\.apache\\.commons\\..*", "org.apache.commons.httpclient.contrib.ssl"); + assertAntPatternEqualsToFindBugsRegExp("org/apache/commons/**", "~org\\.apache\\.commons\\..*", "org.apache.commons.httpclient.contrib.ssl"); } + @Test + public void shouldntMatchThoseClassPattern() { + // see SONAR-853 + assertJavaRegexpResult("[^\\\\^\\s]", "fad f.ate 12#)", false); + } + + private void assertAntPatternEqualsToFindBugsRegExp(String antPattern, String regExp, String example) { + assertThat(FindbugsAntConverter.antToJavaRegexpConvertor(antPattern), Is.is(regExp)); + String javaRegexp = regExp.substring(1, regExp.length()); + assertJavaRegexpResult(javaRegexp, example, true); + } + + private void assertJavaRegexpResult(String javaRegexp, String example, boolean expectedResult) { + Pattern pattern = Pattern.compile(javaRegexp); + Matcher matcher = pattern.matcher(example); + assertThat(example + " tested with pattern " + javaRegexp, matcher.matches(), Is.is(expectedResult)); + } } diff --git a/plugins/sonar-findbugs-plugin/src/test/java/org/sonar/plugins/findbugs/FindbugsConfigurationTest.java b/plugins/sonar-findbugs-plugin/src/test/java/org/sonar/plugins/findbugs/FindbugsConfigurationTest.java new file mode 100644 index 00000000000..00ead6916fa --- /dev/null +++ b/plugins/sonar-findbugs-plugin/src/test/java/org/sonar/plugins/findbugs/FindbugsConfigurationTest.java @@ -0,0 +1,46 @@ +package org.sonar.plugins.findbugs; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.sonar.api.profiles.RulesProfile; +import org.sonar.api.resources.Project; +import org.sonar.api.test.SimpleProjectFileSystem; + +import java.io.File; + +public class FindbugsConfigurationTest { + + @Rule + public TemporaryFolder tempFolder = new TemporaryFolder(); + + private Project project; + private File findbugsTempDir; + + @Before + public void setup() { + project = mock(Project.class); + findbugsTempDir = tempFolder.newFolder("findbugs"); + when(project.getFileSystem()).thenReturn(new SimpleProjectFileSystem(findbugsTempDir)); + } + + @Test + public void shouldSaveConfigFiles() throws Exception { + FindbugsConfiguration conf = new FindbugsConfiguration(project, RulesProfile.create(), new FindbugsProfileExporter(), null); + + conf.saveIncludeConfigXml(); + conf.saveExcludeConfigXml(); + + File findbugsIncludeFile = new File(findbugsTempDir + "/target/sonar/findbugs-include.xml"); + File findbugsExcludeFile = new File(findbugsTempDir + "/target/sonar/findbugs-exclude.xml"); + assertThat(findbugsIncludeFile.exists(), is(true)); + assertThat(findbugsExcludeFile.exists(), is(true)); + } + +} diff --git a/plugins/sonar-findbugs-plugin/src/test/java/org/sonar/plugins/findbugs/FindbugsExecutorTest.java b/plugins/sonar-findbugs-plugin/src/test/java/org/sonar/plugins/findbugs/FindbugsExecutorTest.java index ce41df5002b..68eb3ebac32 100644 --- a/plugins/sonar-findbugs-plugin/src/test/java/org/sonar/plugins/findbugs/FindbugsExecutorTest.java +++ b/plugins/sonar-findbugs-plugin/src/test/java/org/sonar/plugins/findbugs/FindbugsExecutorTest.java @@ -1,19 +1,19 @@ package org.sonar.plugins.findbugs; -import org.apache.commons.io.FileUtils; -import org.junit.Test; -import org.sonar.api.utils.SonarException; - -import edu.umd.cs.findbugs.Project; - -import java.io.File; - import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; import static org.junit.internal.matchers.StringContains.containsString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import org.apache.commons.io.FileUtils; +import org.junit.Test; +import org.sonar.api.resources.Project; +import org.sonar.api.resources.ProjectFileSystem; +import org.sonar.api.utils.SonarException; + +import java.io.File; + public class FindbugsExecutorTest { @Test @@ -39,9 +39,19 @@ public class FindbugsExecutorTest { new FindbugsExecutor(conf).execute(); } + @Test(expected = SonarException.class) + public void shoulFailIfNoCompiledClasses() throws Exception { + Project project = mock(Project.class); + ProjectFileSystem fs = mock(ProjectFileSystem.class); + when(project.getFileSystem()).thenReturn(fs); + FindbugsConfiguration conf = new FindbugsConfiguration(project, null, null, null); + + new FindbugsExecutor(conf).execute(); + } + private FindbugsConfiguration mockConf() throws Exception { FindbugsConfiguration conf = mock(FindbugsConfiguration.class); - Project project = new Project(); + edu.umd.cs.findbugs.Project project = new edu.umd.cs.findbugs.Project(); project.addFile(new File("test-resources/classes").getCanonicalPath()); project.addSourceDir(new File("test-resources/src").getCanonicalPath()); project.setCurrentWorkingDirectory(new File("test-resources")); diff --git a/plugins/sonar-findbugs-plugin/src/test/java/org/sonar/plugins/findbugs/FindbugsMavenPluginHandlerTest.java b/plugins/sonar-findbugs-plugin/src/test/java/org/sonar/plugins/findbugs/FindbugsMavenPluginHandlerTest.java deleted file mode 100644 index 63ee8840b04..00000000000 --- a/plugins/sonar-findbugs-plugin/src/test/java/org/sonar/plugins/findbugs/FindbugsMavenPluginHandlerTest.java +++ /dev/null @@ -1,193 +0,0 @@ -/* - * Sonar, open source software quality management tool. - * Copyright (C) 2009 SonarSource SA - * mailto:contact AT sonarsource DOT com - * - * Sonar is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * Sonar is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with Sonar; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 - */ -package org.sonar.plugins.findbugs; - -import org.apache.commons.configuration.Configuration; -import org.apache.maven.project.MavenProject; -import static org.hamcrest.CoreMatchers.is; -import org.hamcrest.core.Is; -import static org.hamcrest.text.StringEndsWith.endsWith; -import static org.junit.Assert.assertThat; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import static org.mockito.Matchers.anyObject; -import static org.mockito.Matchers.anyString; -import static org.mockito.Matchers.argThat; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.*; - -import org.junit.rules.TemporaryFolder; -import org.sonar.api.CoreProperties; -import org.sonar.api.batch.maven.MavenPlugin; -import org.sonar.api.profiles.RulesProfile; -import org.sonar.api.resources.Project; -import org.sonar.api.resources.ProjectFileSystem; -import org.sonar.api.test.SimpleProjectFileSystem; -import org.sonar.api.utils.SonarException; - -import java.io.File; -import java.io.IOException; -import java.net.URISyntaxException; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public class FindbugsMavenPluginHandlerTest { - - @Rule - public TemporaryFolder tempFolder = new TemporaryFolder(); - - private Project project; - private ProjectFileSystem fs; - private File fakeSonarConfig; - private MavenPlugin plugin; - private FindbugsMavenPluginHandler handler; - private File findbugsTempDir; - - @Before - public void setup() { - project = mock(Project.class); - fs = mock(ProjectFileSystem.class); - fakeSonarConfig = mock(File.class); - plugin = mock(MavenPlugin.class); - handler = createMavenPluginHandler(); - findbugsTempDir = tempFolder.newFolder("findbugs"); - } - - @Test - public void doOverrideConfig() throws Exception { - setupConfig(); - - handler.configureFilters(project, plugin); - verify(plugin).setParameter("includeFilterFile", "fakeSonarConfig.xml"); - } - - @Test - public void doReuseExistingRulesConfig() throws Exception { - setupConfig(); - // See sonar 583 - when(project.getReuseExistingRulesConfig()).thenReturn(true); - when(plugin.getParameter("excludeFilterFile")).thenReturn("existingConfig.xml"); - - handler.configureFilters(project, plugin); - verify(plugin, never()).setParameter(eq("includeFilterFile"), anyString()); - - setupConfig(); - when(project.getReuseExistingRulesConfig()).thenReturn(true); - when(plugin.getParameter("includeFilterFile")).thenReturn("existingConfig.xml"); - - handler.configureFilters(project, plugin); - verify(plugin, never()).setParameter(eq("includeFilterFile"), anyString()); - } - - private void setupConfig() throws IOException { - when(fakeSonarConfig.getCanonicalPath()).thenReturn("fakeSonarConfig.xml"); - when(project.getFileSystem()).thenReturn(fs); - when(fs.writeToWorkingDirectory(anyString(), anyString())).thenReturn(fakeSonarConfig); - } - - @Test - public void shoulConfigurePlugin() throws URISyntaxException, IOException { - - mockProject(CoreProperties.FINDBUGS_EFFORT_DEFAULT_VALUE); - - handler.configure(project, plugin); - - verify(plugin).setParameter("skip", "false"); - verify(plugin).setParameter("xmlOutput", "true"); - verify(plugin).setParameter("threshold", "Low"); - verify(plugin).setParameter("effort", CoreProperties.FINDBUGS_EFFORT_DEFAULT_VALUE, false); - verify(plugin).setParameter(eq("classFilesDirectory"), anyString()); - verify(plugin).setParameter(eq("includeFilterFile"), argThat(endsWith("findbugs-include.xml"))); - assertFindbugsIncludeFileIsSaved(); - } - - @Test(expected = SonarException.class) - public void shoulFailIfNoCompiledClasses() throws URISyntaxException, IOException { - when(project.getFileSystem()).thenReturn(fs); - - handler.configure(project, plugin); - } - - @Test - public void shouldConfigureEffort() throws URISyntaxException, IOException { - FindbugsMavenPluginHandler handler = createMavenPluginHandler(); - mockProject("EffortSetInPom"); - MavenPlugin plugin = mock(MavenPlugin.class); - - handler.configure(project, plugin); - - verify(plugin).setParameter("effort", "EffortSetInPom", false); - } - - @Test - public void shouldConvertAntToJavaRegexp() { - // see SONAR-853 - assertAntPatternEqualsToFindBugsRegExp("?", "~.", "g"); - assertAntPatternEqualsToFindBugsRegExp("*/myClass.JaVa", "~([^\\\\^\\s]*\\.)?myClass", "foo.bar.test.myClass"); - assertAntPatternEqualsToFindBugsRegExp("*/myClass.java", "~([^\\\\^\\s]*\\.)?myClass", "foo.bar.test.myClass"); - assertAntPatternEqualsToFindBugsRegExp("*/myClass2.jav", "~([^\\\\^\\s]*\\.)?myClass2", "foo.bar.test.myClass2"); - assertAntPatternEqualsToFindBugsRegExp("*/myOtherClass", "~([^\\\\^\\s]*\\.)?myOtherClass", "foo.bar.test.myOtherClass"); - assertAntPatternEqualsToFindBugsRegExp("*", "~[^\\\\^\\s]*", "ga.%#123_(*"); - assertAntPatternEqualsToFindBugsRegExp("**", "~.*", "gd.3reqg.3151];9#@!"); - assertAntPatternEqualsToFindBugsRegExp("**/generated/**", "~(.*\\.)?generated\\..*", "!@$Rq/32T$).generated.##TR.e#@!$"); - assertAntPatternEqualsToFindBugsRegExp("**/cl*nt/*", "~(.*\\.)?cl[^\\\\^\\s]*nt\\.[^\\\\^\\s]*", "!#$_.clr31r#!$(nt.!#$QRW)(."); - assertAntPatternEqualsToFindBugsRegExp("**/org/apache/commons/**", "~(.*\\.)?org\\.apache\\.commons\\..*", "org.apache.commons.httpclient.contrib.ssl"); - assertAntPatternEqualsToFindBugsRegExp("*/org/apache/commons/**", "~([^\\\\^\\s]*\\.)?org\\.apache\\.commons\\..*", "org.apache.commons.httpclient.contrib.ssl"); - assertAntPatternEqualsToFindBugsRegExp("org/apache/commons/**", "~org\\.apache\\.commons\\..*", "org.apache.commons.httpclient.contrib.ssl"); - } - - @Test - public void shouldntMatchThoseClassPattern() { - // see SONAR-853 - assertJavaRegexpResult("[^\\\\^\\s]", "fad f.ate 12#)", false); - } - - private void assertAntPatternEqualsToFindBugsRegExp(String antPattern, String regExp, String example) { - assertThat(FindbugsAntConverter.antToJavaRegexpConvertor(antPattern), Is.is(regExp)); - String javaRegexp = regExp.substring(1, regExp.length()); - assertJavaRegexpResult(javaRegexp, example, true); - } - - private void assertJavaRegexpResult(String javaRegexp, String example, boolean expectedResult) { - Pattern pattern = Pattern.compile(javaRegexp); - Matcher matcher = pattern.matcher(example); - assertThat(example + " tested with pattern " + javaRegexp, matcher.matches(), Is.is(expectedResult)); - } - - private void assertFindbugsIncludeFileIsSaved() { - File findbugsIncludeFile = new File(findbugsTempDir + "/target/sonar/findbugs-include.xml"); - assertThat(findbugsIncludeFile.exists(), is(true)); - } - - private FindbugsMavenPluginHandler createMavenPluginHandler() { - return new FindbugsMavenPluginHandler(RulesProfile.create(), new FindbugsProfileExporter()); - } - - private void mockProject(String effort) throws URISyntaxException, IOException { - when(project.getPom()).thenReturn(new MavenProject()); - when(project.getFileSystem()).thenReturn(new SimpleProjectFileSystem(findbugsTempDir)); - - Configuration conf = mock(Configuration.class); - when(project.getConfiguration()).thenReturn(conf); - when(conf.getString(eq(CoreProperties.FINDBUGS_EFFORT_PROPERTY), anyString())).thenReturn(effort); - - } -} diff --git a/plugins/sonar-findbugs-plugin/src/test/java/org/sonar/plugins/findbugs/FindbugsNativeSensorTest.java b/plugins/sonar-findbugs-plugin/src/test/java/org/sonar/plugins/findbugs/FindbugsNativeSensorTest.java deleted file mode 100644 index 907a5c7d83e..00000000000 --- a/plugins/sonar-findbugs-plugin/src/test/java/org/sonar/plugins/findbugs/FindbugsNativeSensorTest.java +++ /dev/null @@ -1,123 +0,0 @@ -package org.sonar.plugins.findbugs; - -import org.apache.commons.configuration.Configuration; -import org.apache.maven.project.MavenProject; -import org.junit.Test; -import org.sonar.api.CoreProperties; -import org.sonar.api.batch.SensorContext; -import org.sonar.api.profiles.RulesProfile; -import org.sonar.api.resources.DefaultProjectFileSystem; -import org.sonar.api.resources.JavaFile; -import org.sonar.api.resources.Project; -import org.sonar.api.resources.Resource; -import org.sonar.api.rules.Violation; -import org.sonar.api.test.IsViolation; - -import java.io.File; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.argThat; -import static org.mockito.Mockito.*; - -public class FindbugsNativeSensorTest extends FindbugsTests { - - @Test - public void shouldExecuteWhenSomeRulesAreActive() throws Exception { - FindbugsNativeSensor sensor = new FindbugsNativeSensor(createRulesProfileWithActiveRules(), new FindbugsRuleFinder(), null); - Project project = createProject(); - assertTrue(sensor.shouldExecuteOnProject(project)); - } - - @Test - public void shouldExecuteWhenReuseExistingRulesConfig() throws Exception { - FindbugsNativeSensor analyser = new FindbugsNativeSensor(RulesProfile.create(), new FindbugsRuleFinder(), null); - Project pom = createProject(); - when(pom.getReuseExistingRulesConfig()).thenReturn(true); - assertTrue(analyser.shouldExecuteOnProject(pom)); - } - - @Test - public void shouldNotExecuteWhenNoRulesAreActive() throws Exception { - FindbugsNativeSensor analyser = new FindbugsNativeSensor(RulesProfile.create(), new FindbugsRuleFinder(), null); - Project pom = createProject(); - assertFalse(analyser.shouldExecuteOnProject(pom)); - } - - @Test - public void shouldNotExecuteOnEar() { - Project project = createProject(); - when(project.getPom().getPackaging()).thenReturn("ear"); - FindbugsNativeSensor analyser = new FindbugsNativeSensor(createRulesProfileWithActiveRules(), new FindbugsRuleFinder(), null); - assertFalse(analyser.shouldExecuteOnProject(project)); - } - - @Test - public void shouldExecuteFindbugsWhenNoReportProvided() throws Exception { - Project project = createProject(); - FindbugsExecutor executor = mock(FindbugsExecutor.class); - SensorContext context = mock(SensorContext.class); - Configuration conf = mock(Configuration.class); - File xmlFile = new File(getClass().getResource("/org/sonar/plugins/findbugs/findbugsXml.xml").toURI()); - when(project.getConfiguration()).thenReturn(conf); - when(executor.execute()).thenReturn(xmlFile); - when(context.getResource(any(Resource.class))).thenReturn(new JavaFile("org.sonar.MyClass")); - - FindbugsNativeSensor analyser = new FindbugsNativeSensor(createRulesProfileWithActiveRules(), new FindbugsRuleFinder(), executor); - analyser.analyse(project, context); - - verify(executor).execute(); - verify(context, times(3)).saveViolation(any(Violation.class)); - - Violation wanted = new Violation(null, new JavaFile("org.sonar.commons.ZipUtils")).setMessage( - "Empty zip file entry created in org.sonar.commons.ZipUtils._zip(String, File, ZipOutputStream)").setLineId(107); - - verify(context).saveViolation(argThat(new IsViolation(wanted))); - - wanted = new Violation(null, new JavaFile("org.sonar.commons.resources.MeasuresDao")).setMessage( - "The class org.sonar.commons.resources.MeasuresDao$1 could be refactored into a named _static_ inner class").setLineId(56); - - verify(context).saveViolation(argThat(new IsViolation(wanted))); - } - - @Test - public void shouldReuseReport() throws Exception { - Project project = createProject(); - FindbugsExecutor executor = mock(FindbugsExecutor.class); - SensorContext context = mock(SensorContext.class); - Configuration conf = mock(Configuration.class); - File xmlFile = new File(getClass().getResource("/org/sonar/plugins/findbugs/findbugsXml.xml").toURI()); - when(conf.getString(CoreProperties.FINDBUGS_REPORT_PATH)).thenReturn(xmlFile.getAbsolutePath()); - when(project.getConfiguration()).thenReturn(conf); - when(context.getResource(any(Resource.class))).thenReturn(new JavaFile("org.sonar.MyClass")); - - FindbugsNativeSensor analyser = new FindbugsNativeSensor(createRulesProfileWithActiveRules(), new FindbugsRuleFinder(), executor); - analyser.analyse(project, context); - - verify(executor, never()).execute(); - verify(context, times(3)).saveViolation(any(Violation.class)); - - Violation wanted = new Violation(null, new JavaFile("org.sonar.commons.ZipUtils")).setMessage( - "Empty zip file entry created in org.sonar.commons.ZipUtils._zip(String, File, ZipOutputStream)").setLineId(107); - - verify(context).saveViolation(argThat(new IsViolation(wanted))); - - wanted = new Violation(null, new JavaFile("org.sonar.commons.resources.MeasuresDao")).setMessage( - "The class org.sonar.commons.resources.MeasuresDao$1 could be refactored into a named _static_ inner class").setLineId(56); - - verify(context).saveViolation(argThat(new IsViolation(wanted))); - } - - private Project createProject() { - DefaultProjectFileSystem fileSystem = mock(DefaultProjectFileSystem.class); - when(fileSystem.hasJavaSourceFiles()).thenReturn(Boolean.TRUE); - - MavenProject mavenProject = mock(MavenProject.class); - Project project = mock(Project.class); - when(project.getFileSystem()).thenReturn(fileSystem); - when(project.getPom()).thenReturn(mavenProject); - return project; - } - -} diff --git a/plugins/sonar-findbugs-plugin/src/test/java/org/sonar/plugins/findbugs/FindbugsSensorTest.java b/plugins/sonar-findbugs-plugin/src/test/java/org/sonar/plugins/findbugs/FindbugsSensorTest.java index 0e74508fee9..fb4bac2ebf7 100644 --- a/plugins/sonar-findbugs-plugin/src/test/java/org/sonar/plugins/findbugs/FindbugsSensorTest.java +++ b/plugins/sonar-findbugs-plugin/src/test/java/org/sonar/plugins/findbugs/FindbugsSensorTest.java @@ -19,20 +19,16 @@ */ package org.sonar.plugins.findbugs; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Matchers.argThat; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import java.io.File; - import org.apache.commons.configuration.Configuration; import org.apache.maven.project.MavenProject; import org.junit.Test; @@ -46,6 +42,8 @@ import org.sonar.api.resources.Resource; import org.sonar.api.rules.Violation; import org.sonar.api.test.IsViolation; +import java.io.File; + public class FindbugsSensorTest extends FindbugsTests { @Test @@ -56,32 +54,18 @@ public class FindbugsSensorTest extends FindbugsTests { } @Test - public void shouldNotExecuteWhenNoRulesAreActive() throws Exception { + public void shouldExecuteWhenReuseExistingRulesConfig() throws Exception { FindbugsSensor analyser = new FindbugsSensor(RulesProfile.create(), new FindbugsRuleFinder(), null); Project pom = createProject(); - assertFalse(analyser.shouldExecuteOnProject(pom)); - } - - @Test - public void testGetMavenPluginHandlerWhenFindbugsReportPathExists() throws Exception { - FindbugsSensor analyser = new FindbugsSensor(RulesProfile.create(), new FindbugsRuleFinder(), mock(FindbugsMavenPluginHandler.class)); - Project pom = createProject(); - Configuration conf = mock(Configuration.class); - when(conf.getString(CoreProperties.FINDBUGS_REPORT_PATH)).thenReturn("pathToFindbugsReport"); - when(pom.getConfiguration()).thenReturn(conf); - assertThat(analyser.getMavenPluginHandler(pom), is(nullValue())); + when(pom.getReuseExistingRulesConfig()).thenReturn(true); + assertTrue(analyser.shouldExecuteOnProject(pom)); } @Test - public void testGetFindbugsReport() { - FindbugsSensor analyser = new FindbugsSensor(createRulesProfileWithActiveRules(), new FindbugsRuleFinder(), null); + public void shouldNotExecuteWhenNoRulesAreActive() throws Exception { + FindbugsSensor analyser = new FindbugsSensor(RulesProfile.create(), new FindbugsRuleFinder(), null); Project pom = createProject(); - Configuration conf = mock(Configuration.class); - when(pom.getConfiguration()).thenReturn(conf); - assertThat(analyser.getFindbugsReportFile(pom).getName(), is("findbugsXml.xml")); - - when(conf.getString(CoreProperties.FINDBUGS_REPORT_PATH)).thenReturn("myFindbugs.xml"); - assertThat(analyser.getFindbugsReportFile(pom).getName(), is("myFindbugs.xml")); + assertFalse(analyser.shouldExecuteOnProject(pom)); } @Test @@ -93,19 +77,48 @@ public class FindbugsSensorTest extends FindbugsTests { } @Test - public void testAnalyse() throws Exception { - + public void shouldExecuteFindbugsWhenNoReportProvided() throws Exception { + Project project = createProject(); + FindbugsExecutor executor = mock(FindbugsExecutor.class); SensorContext context = mock(SensorContext.class); + Configuration conf = mock(Configuration.class); + File xmlFile = new File(getClass().getResource("/org/sonar/plugins/findbugs/findbugsXml.xml").toURI()); + when(project.getConfiguration()).thenReturn(conf); + when(executor.execute()).thenReturn(xmlFile); + when(context.getResource(any(Resource.class))).thenReturn(new JavaFile("org.sonar.MyClass")); + + FindbugsSensor analyser = new FindbugsSensor(createRulesProfileWithActiveRules(), new FindbugsRuleFinder(), executor); + analyser.analyse(project, context); + + verify(executor).execute(); + verify(context, times(3)).saveViolation(any(Violation.class)); + + Violation wanted = new Violation(null, new JavaFile("org.sonar.commons.ZipUtils")).setMessage( + "Empty zip file entry created in org.sonar.commons.ZipUtils._zip(String, File, ZipOutputStream)").setLineId(107); + + verify(context).saveViolation(argThat(new IsViolation(wanted))); + + wanted = new Violation(null, new JavaFile("org.sonar.commons.resources.MeasuresDao")).setMessage( + "The class org.sonar.commons.resources.MeasuresDao$1 could be refactored into a named _static_ inner class").setLineId(56); + + verify(context).saveViolation(argThat(new IsViolation(wanted))); + } + + @Test + public void shouldReuseReport() throws Exception { Project project = createProject(); + FindbugsExecutor executor = mock(FindbugsExecutor.class); + SensorContext context = mock(SensorContext.class); Configuration conf = mock(Configuration.class); File xmlFile = new File(getClass().getResource("/org/sonar/plugins/findbugs/findbugsXml.xml").toURI()); when(conf.getString(CoreProperties.FINDBUGS_REPORT_PATH)).thenReturn(xmlFile.getAbsolutePath()); when(project.getConfiguration()).thenReturn(conf); when(context.getResource(any(Resource.class))).thenReturn(new JavaFile("org.sonar.MyClass")); - FindbugsSensor analyser = new FindbugsSensor(RulesProfile.create(), new FindbugsRuleFinder(), null); + FindbugsSensor analyser = new FindbugsSensor(createRulesProfileWithActiveRules(), new FindbugsRuleFinder(), executor); analyser.analyse(project, context); + verify(executor, never()).execute(); verify(context, times(3)).saveViolation(any(Violation.class)); Violation wanted = new Violation(null, new JavaFile("org.sonar.commons.ZipUtils")).setMessage( -- 2.39.5