sonar java plugin: unit tests
authorGustavo Martin Morcuende <gu.martinm@gmail.com>
Mon, 22 Aug 2016 19:28:23 +0000 (21:28 +0200)
committerGustavo Martin Morcuende <gu.martinm@gmail.com>
Mon, 22 Aug 2016 19:28:23 +0000 (21:28 +0200)
Sonar/Plugins/sonar-custom-java-plugin/pom.xml
Sonar/Plugins/sonar-custom-java-plugin/src/main/java/de/example/custom/java/checks/CheckList.java
Sonar/Plugins/sonar-custom-java-plugin/src/main/java/de/example/custom/java/checks/ParameterCheck.java
Sonar/Plugins/sonar-custom-java-plugin/src/main/java/de/example/plugins/custom/java/CustomProfile.java
Sonar/Plugins/sonar-custom-java-plugin/src/test/files/checks/NoSpringServiceAnnotationInstanceFieldCheck.java [new file with mode: 0644]
Sonar/Plugins/sonar-custom-java-plugin/src/test/java/de/example/custom/java/checks/CheckListTest.java [new file with mode: 0644]
Sonar/Plugins/sonar-custom-java-plugin/src/test/java/de/example/custom/java/checks/ParameterCheckTest.java
Sonar/Plugins/sonar-custom-java-plugin/src/test/java/de/example/custom/java/checks/SpringServiceInstanceFieldCheckTest.java
Sonar/Plugins/sonar-custom-java-plugin/src/test/java/de/example/plugins/custom/java/CustomPluginTest.java [new file with mode: 0644]
Sonar/Plugins/sonar-custom-java-plugin/src/test/java/de/example/plugins/custom/java/CustomProfileTest.java [new file with mode: 0644]
Sonar/Plugins/sonar-custom-java-plugin/src/test/java/de/example/plugins/custom/java/CustomRulesCheckRegistrarTest.java [new file with mode: 0644]

index 46a5ffa..05a04de 100644 (file)
     <sonar.apiVersion>5.6.1</sonar.apiVersion>
     <java.plugin.version>4.0</java.plugin.version>
     <jdk.min.version>1.8</jdk.min.version>
+        <maven.javadoc.version>2.10.4</maven.javadoc.version>
+        <maven.source.version>3.0.1</maven.source.version>
+    <!-- Be careful these two paths must match the ones configured in SONARQUBE JaCoCo plugin -->
+    <jacoco.it.execution.data.file>${project.basedir}/target/jacoco-it.exec</jacoco.it.execution.data.file>
+    <jacoco.ut.execution.data.file>${project.basedir}/target/jacoco.exec</jacoco.ut.execution.data.file>
+
+    <skip.unit.tests>false</skip.unit.tests>
+    <skip.integration.tests>true</skip.integration.tests>
     <sonar.pluginKey>customjavaplugin</sonar.pluginKey>
   </properties>
 
@@ -49,7 +57,7 @@
       <version>${java.plugin.version}</version>
       <scope>test</scope>
     </dependency>
-       <dependency>
+    <dependency>
                <groupId>org.easytesting</groupId>
                <artifactId>fest-assert</artifactId>
                <version>1.4</version>
   </dependencies>
 
   <build>
+
+               <pluginManagement>
+                       <plugins>
+              <plugin>
+                  <groupId>org.apache.maven.plugins</groupId>
+                  <artifactId>maven-site-plugin</artifactId>
+                  <version>3.5.1</version>
+                  <dependencies>
+                      <dependency><!-- add support for ssh/scp -->
+                          <groupId>org.apache.maven.wagon</groupId>
+                          <artifactId>wagon-ssh</artifactId>
+                          <version>2.10</version>
+                      </dependency>
+                  </dependencies>
+              </plugin>
+                       </plugins>
+               </pluginManagement>
+
     <plugins>
       <plugin>
         <groupId>org.sonarsource.sonar-packaging-maven-plugin</groupId>
           <encoding>${project.build.sourceEncoding}</encoding>
         </configuration>
       </plugin>
+       <plugin>
+                               <groupId>org.apache.maven.plugins</groupId>
+                               <artifactId>maven-resources-plugin</artifactId>
+                               <version>2.7</version>
+                               <configuration>
+                                       <encoding>${project.build.sourceEncoding}</encoding>
+                               </configuration>
+                       </plugin>
+            <plugin>
+                <artifactId>maven-site-plugin</artifactId>
+                <executions>
+                    <execution>
+                        <id>attach-descriptor</id>
+                        <goals>
+                            <goal>attach-descriptor</goal>
+                        </goals>
+                    </execution>
+                </executions>
+            </plugin>
+                       <plugin>
+                               <groupId>org.apache.maven.plugins</groupId>
+                               <artifactId>maven-jar-plugin</artifactId>
+                               <version>2.6</version>
+                               <configuration>
+                                       <archive>
+                                               <manifestEntries>
+                                                       <Specification-Title>${project.description}</Specification-Title>
+                                                       <Specification-Version>${project.version}</Specification-Version>
+                                                       <Specification-Vendor>${project.organization.name}</Specification-Vendor>
+                                                       <Implementation-Title>${project.description}</Implementation-Title>
+                                                       <Implementation-Version>${project.version}</Implementation-Version>
+                                                       <Implementation-Vendor>${project.organization.name}</Implementation-Vendor>
+                                               </manifestEntries>
+                                       </archive>
+                               </configuration>
+                       </plugin>
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-javadoc-plugin</artifactId>
+                <version>${maven.javadoc.version}</version>
+                <configuration>
+                    <quiet>true</quiet>
+                    <docencoding>${project.build.sourceEncoding}</docencoding>
+                    <charset>${project.build.sourceEncoding}</charset>
+                    <encoding>${project.build.sourceEncoding}</encoding>
+                    <additionalparam>-Xdoclint:none</additionalparam>
+                </configuration>
+            </plugin>
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-source-plugin</artifactId>
+                <version>${maven.source.version}</version>
+                <executions>
+                    <execution>
+                        <id>attach-sources</id>
+                        <phase>package</phase>
+                        <goals>
+                            <goal>jar-no-fork</goal>
+                        </goals>
+                    </execution>
+                </executions>
+            </plugin>
+            <plugin>
+                <groupId>org.jacoco</groupId>
+                <artifactId>jacoco-maven-plugin</artifactId>
+                <version>0.7.7.201606060606</version>
+                <executions>
+                    <!-- Prepares the property pointing to the JaCoCo runtime agent which 
+                        is passed as VM argument when Maven the Surefire plugin is executed. -->
+                    <execution>
+                        <id>pre-unit-test</id>
+                        <goals>
+                            <goal>prepare-agent</goal>
+                        </goals>
+                        <configuration>
+                            <!-- Sets the path to the file which contains the execution data. -->
+                            <destFile>${jacoco.ut.execution.data.file}</destFile>
+                            <!-- Sets the name of the property containing the settings for JaCoCo 
+                                runtime agent. -->
+                            <propertyName>surefireArgLine</propertyName>
+                        </configuration>
+                    </execution>
+                    <!-- Ensures that the code coverage report for unit tests is created 
+                        after unit tests have been run. -->
+                    <execution>
+                        <id>post-unit-test</id>
+                        <phase>test</phase>
+                        <goals>
+                            <goal>report</goal>
+                        </goals>
+                        <configuration>
+                            <!-- Sets the path to the file which contains the execution data. -->
+                            <dataFile>${jacoco.ut.execution.data.file}</dataFile>
+                            <!-- Sets the output directory for the code coverage report. -->
+                            <outputDirectory>${project.reporting.outputDirectory}/jacoco-ut</outputDirectory>
+                        </configuration>
+                    </execution>
+                    <!-- Prepares the property pointing to the JaCoCo runtime agent which 
+                        is passed as VM argument when Maven the Failsafe plugin is executed. -->
+                    <execution>
+                        <id>pre-integration-test</id>
+                        <phase>pre-integration-test</phase>
+                        <goals>
+                            <goal>prepare-agent</goal>
+                        </goals>
+                        <configuration>
+                            <!-- Sets the path to the file which contains the execution data. -->
+                            <destFile>${jacoco.it.execution.data.file}</destFile>
+                            <!-- Sets the name of the property containing the settings for JaCoCo 
+                                runtime agent. -->
+                            <propertyName>failsafeArgLine</propertyName>
+                        </configuration>
+                    </execution>
+                    <!-- Ensures that the code coverage report for integration tests after 
+                        integration tests have been run. -->
+                    <execution>
+                        <id>post-integration-test</id>
+                        <phase>post-integration-test</phase>
+                        <goals>
+                            <goal>report</goal>
+                        </goals>
+                        <configuration>
+                            <!-- Sets the path to the file which contains the execution data. -->
+                            <dataFile>${jacoco.it.execution.data.file}</dataFile>
+                            <!-- Sets the output directory for the code coverage report. -->
+                            <outputDirectory>${project.reporting.outputDirectory}/jacoco-it</outputDirectory>
+                        </configuration>
+                    </execution>
+                </executions>
+            </plugin>
+            <plugin>
+                <groupId>org.eclipse.m2e</groupId>
+                <artifactId>lifecycle-mapping</artifactId>
+                <version>1.0.0</version>
+                <configuration>
+                    <lifecycleMappingMetadata>
+                        <pluginExecutions>
+                            <pluginExecution>
+                                <pluginExecutionFilter>
+                                    <groupId>org.jacoco</groupId>
+                                    <artifactId>jacoco-maven-plugin</artifactId>
+                                    <versionRange>[0.5,)
+                                    </versionRange>
+                                    <goals>
+                                        <goal>prepare-agent</goal>
+                                    </goals>
+                                </pluginExecutionFilter>
+                                <action>
+                                    <!-- m2e doesn't know what to do with jacoco, let's ignore it or 
+                                        annoying error markers appear see http://wiki.eclipse.org/M2E_plugin_execution_not_covered -->
+                                    <ignore />
+                                </action>
+                            </pluginExecution>
+                        </pluginExecutions>
+                    </lifecycleMappingMetadata>
+                </configuration>
+            </plugin>
+               <!-- Used for unit tests -->
+               <plugin>
+                       <groupId>org.apache.maven.plugins</groupId>
+                       <artifactId>maven-surefire-plugin</artifactId>
+                       <version>2.19.1</version>
+                       <dependencies>
+                               <dependency>
+                                       <groupId>org.apache.maven.surefire</groupId>
+                                       <artifactId>surefire-junit47</artifactId>
+                                       <version>2.19.1</version>
+                               </dependency>
+                       </dependencies>
+                       <configuration>
+                               <!-- Sets the VM argument line used when unit tests are run. -->
+                               <argLine>-Dfile.encoding=${project.build.sourceEncoding}
+                                       ${surefireArgLine}</argLine>
+                               <!-- Skips unit tests if the value of skip.unit.tests property is true -->
+                               <skipTests>${skip.unit.tests}</skipTests>
+                               <!-- Excludes integration tests when unit tests are run. -->
+                               <excludes>
+                                       <exclude>**/*IT.java</exclude>
+                                       <exclude>**/*IntegrationTest.java</exclude>
+                               </excludes>
+                       </configuration>
+               </plugin>
     </plugins>
   </build>
+  
+    <reporting>
+        <plugins>
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-project-info-reports-plugin</artifactId>
+                <version>2.9</version>
+            </plugin>
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-javadoc-plugin</artifactId>
+                <version>${maven.javadoc.version}</version>
+                <reportSets>
+                    <reportSet>
+                        <id>html</id>
+                        <configuration>
+
+                            <doctitle>API for ${project.name} ${project.version}</doctitle>
+                            <windowtitle>API for ${project.name} ${project.version}</windowtitle>
+                        </configuration>
+                        <reports>
+                            <report>javadoc</report>
+                            <report>aggregate</report>
+                        </reports>
+                    </reportSet>
+                </reportSets>
+            </plugin>
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-surefire-report-plugin</artifactId>
+                <version>2.19.1</version>
+                <reportSets>
+                    <reportSet>
+                        <reports>
+                            <report>report-only</report>
+                        </reports>
+                    </reportSet>
+                </reportSets>
+            </plugin>
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-jxr-plugin</artifactId>
+                <version>2.5</version>
+            </plugin>
+        </plugins>
+    </reporting>
 
 </project>
index 4ced8a5..0851d0f 100644 (file)
@@ -18,6 +18,7 @@ public final class CheckList {
                                .addAll(getJavaChecks())
                                .addAll(getJavaTestChecks())
                                .addAll(getXmlChecks())
+                               .addAll(getMavenChecks())
                                .build();
        }
 
index 372bbf4..95feff7 100644 (file)
@@ -26,8 +26,6 @@ public class ParameterCheck extends IssuableSubscriptionVisitor {
 
        @Override
        public void visitNode(Tree tree) {
-               LOG.info("Visiting Node");
-
                MethodTree method = (MethodTree) tree;
                
                if (method.parameters().size() == 1) {
index 270fe70..3df2c08 100644 (file)
@@ -25,7 +25,7 @@ public class CustomProfile extends ProfileDefinition {
                Profile jsonProfile = gson.fromJson(readResource(resource), Profile.class);
                RulesProfile profile = RulesProfile.create(jsonProfile.getName(), Java.KEY);
                
-               for (String key : jsonProfile.ruleKeys) {
+               for (String key : jsonProfile.getRuleKeys()) {
                        Rule rule = Rule.create(CheckList.REPOSITORY_KEY, key);
                        profile.activateRule(rule, null);
                }
@@ -42,8 +42,8 @@ public class CustomProfile extends ProfileDefinition {
        }
 
        private static class Profile {
-               String name;
-               List<String> ruleKeys;
+               private String name;
+               private List<String> ruleKeys;
                
                public String getName() {
                        return name;
diff --git a/Sonar/Plugins/sonar-custom-java-plugin/src/test/files/checks/NoSpringServiceAnnotationInstanceFieldCheck.java b/Sonar/Plugins/sonar-custom-java-plugin/src/test/files/checks/NoSpringServiceAnnotationInstanceFieldCheck.java
new file mode 100644 (file)
index 0000000..254e4a4
--- /dev/null
@@ -0,0 +1,15 @@
+
+public class NoService {
+       private static final Integer FIELD1;
+       
+       private final Integer field2;
+       
+       private Integer field3;
+       
+       public static final Integer field4;
+       
+       public final Integer field5;
+       
+       public Integer field6;
+
+}
diff --git a/Sonar/Plugins/sonar-custom-java-plugin/src/test/java/de/example/custom/java/checks/CheckListTest.java b/Sonar/Plugins/sonar-custom-java-plugin/src/test/java/de/example/custom/java/checks/CheckListTest.java
new file mode 100644 (file)
index 0000000..306e897
--- /dev/null
@@ -0,0 +1,29 @@
+package de.example.custom.java.checks;
+
+import static org.junit.Assert.*;
+import static org.hamcrest.CoreMatchers.*;
+
+import java.io.File;
+import java.util.Collection;
+
+import org.apache.commons.io.FileUtils;
+import org.junit.Test;
+
+public class CheckListTest {
+
+         @Test
+         public void whenRetrievingJavaChecksThenGetRightNumberOfClasses() {
+           int count = 0;
+           Collection<File> files = FileUtils.listFiles(
+                       new File("src/main/java/de/example/custom/java/checks/"),
+                       new String[] {"java"},
+                       true);
+           for (File file : files) {
+             if (file.getName().endsWith("Check.java")) {
+               count++;
+             }
+           }
+           assertThat(CheckList.getChecks().size(), is(count));
+         }
+
+}
index 4c60044..983efa4 100644 (file)
@@ -6,7 +6,7 @@ import org.sonar.java.checks.verifier.JavaCheckVerifier;
 public class ParameterCheckTest {
 
        @Test
-       public void test() {
+       public void whenCheckingFunctionParametersThenGenerateIssues() {
                JavaCheckVerifier.verify("src/test/files/checks/ParameterCheck.java", new ParameterCheck());
        }
 }
index b373241..5ba3b12 100644 (file)
@@ -6,14 +6,20 @@ import org.sonar.java.checks.verifier.JavaCheckVerifier;
 public class SpringServiceInstanceFieldCheckTest {
          private static final String NAMED_ANNOTATION = "src/test/files/checks/SpringServiceNamedAnnotationInstanceFieldCheck.java";
          private static final String SPRING_SERVICE_ANNOTATION = "src/test/files/checks/SpringServiceAnnotationInstanceFieldCheck.java";
+         private static final String NO_SPRING_SERVICE_ANNOTATION = "src/test/files/checks/NoSpringServiceAnnotationInstanceFieldCheck.java";
 
          @Test
-         public void whenNamedAnnotationAndNoStaticOrFinalField() {
+         public void whenNamedAnnotationAndNoStaticOrFinalFieldThenGenerateIssues() {
            JavaCheckVerifier.verify(NAMED_ANNOTATION, new SpringServiceInstanceFieldCheck());
          }
          
          @Test
-         public void whenSpringServiceAnnotationAndNoStaticOrFinalField() {
+         public void whenSpringServiceAnnotationAndNoStaticOrFinalFieldThenGenerateIssues() {
            JavaCheckVerifier.verify(SPRING_SERVICE_ANNOTATION, new SpringServiceInstanceFieldCheck());
          }
+         
+         @Test
+         public void whenNoSpringServiceOrNamedAnnotationThenNoIssues() {
+           JavaCheckVerifier.verifyNoIssue(NO_SPRING_SERVICE_ANNOTATION, new SpringServiceInstanceFieldCheck());
+         }
 }
diff --git a/Sonar/Plugins/sonar-custom-java-plugin/src/test/java/de/example/plugins/custom/java/CustomPluginTest.java b/Sonar/Plugins/sonar-custom-java-plugin/src/test/java/de/example/plugins/custom/java/CustomPluginTest.java
new file mode 100644 (file)
index 0000000..296a57b
--- /dev/null
@@ -0,0 +1,22 @@
+package de.example.plugins.custom.java;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+
+import org.junit.Test;
+import org.sonar.api.Plugin;
+import org.sonar.api.SonarQubeVersion;
+
+public class CustomPluginTest {
+
+       @Test
+       public void whenCreatingCustomJavaPluginThenRetrieveRightNumberOfExtensions() {
+               CustomPlugin javaPlugin = new CustomPlugin();
+               Plugin.Context context = new Plugin.Context(SonarQubeVersion.V5_6);
+               
+               javaPlugin.define(context);
+
+               assertThat(context.getExtensions().size(), is(3));
+       }
+
+}
diff --git a/Sonar/Plugins/sonar-custom-java-plugin/src/test/java/de/example/plugins/custom/java/CustomProfileTest.java b/Sonar/Plugins/sonar-custom-java-plugin/src/test/java/de/example/plugins/custom/java/CustomProfileTest.java
new file mode 100644 (file)
index 0000000..ea4da21
--- /dev/null
@@ -0,0 +1,42 @@
+package de.example.plugins.custom.java;
+
+import static org.hamcrest.CoreMatchers.*;
+import static org.junit.Assert.*;
+
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import org.junit.Test;
+import org.sonar.api.profiles.RulesProfile;
+import org.sonar.api.rules.ActiveRule;
+import org.sonar.plugins.java.Java;
+
+import de.example.custom.java.checks.CheckList;
+
+public class CustomProfileTest {
+
+       @Test
+       public void whenCreatingJavaCustomProfileThenGenerateProfileWithRules() {
+               CustomProfile profile = new CustomProfile();
+               
+               RulesProfile rulesProfile = profile.createProfile(null);
+               
+               List<ActiveRule> activeRules = rulesProfile.getActiveRulesByRepository(CheckList.REPOSITORY_KEY);
+               Set<String> ruleKeys = getRuleKeys(activeRules);
+               assertThat(ruleKeys, hasItem("GUJ0002"));
+               assertThat(ruleKeys, hasItem("GUJ0002"));
+               assertThat(ruleKeys.size(), is(2));
+               assertThat(rulesProfile.getLanguage(), is(Java.KEY));
+               assertThat(rulesProfile.getName(), is("Custom Java Profile"));
+       }
+
+       private Set<String> getRuleKeys(List<ActiveRule> activeRules) {
+               Set<String> keys = new HashSet<>();
+               for (ActiveRule activeRule : activeRules) {
+                       keys.add(activeRule.getRuleKey());
+               }
+               
+               return keys;
+       }
+}
diff --git a/Sonar/Plugins/sonar-custom-java-plugin/src/test/java/de/example/plugins/custom/java/CustomRulesCheckRegistrarTest.java b/Sonar/Plugins/sonar-custom-java-plugin/src/test/java/de/example/plugins/custom/java/CustomRulesCheckRegistrarTest.java
new file mode 100644 (file)
index 0000000..1c07e4b
--- /dev/null
@@ -0,0 +1,33 @@
+package de.example.plugins.custom.java;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.*;
+
+import java.util.List;
+
+import org.junit.Test;
+import org.sonar.plugins.java.api.CheckRegistrar;
+import org.sonar.plugins.java.api.CheckRegistrar.RegistrarContext;
+import org.sonar.plugins.java.api.JavaCheck;
+
+import com.google.common.collect.Lists;
+
+import de.example.custom.java.checks.CheckList;
+
+public class CustomRulesCheckRegistrarTest {
+
+       @Test
+       public void whenCreatingCustomJavaCheckRegistrarThenGenerateClassWithSuccess() {
+               CustomRulesCheckRegistrar registrar = new CustomRulesCheckRegistrar();
+               RegistrarContext registrarContext = new CheckRegistrar.RegistrarContext();
+               
+               registrar.register(registrarContext);
+               
+               List<Class<? extends JavaCheck>> checkClasses =  Lists.newArrayList(registrarContext.checkClasses());
+               List<Class<? extends JavaCheck>> testCheckClasses =  Lists.newArrayList(registrarContext.testCheckClasses());
+               assertThat(checkClasses.size(), is(2));
+               assertThat(testCheckClasses.size(), is(0));
+               assertThat(registrarContext.repositoryKey(), is(CheckList.REPOSITORY_KEY));
+       }
+
+}