View Javadoc
1   package org.apache.maven.plugin.pmd;
2   
3   /*
4    * Licensed to the Apache Software Foundation (ASF) under one
5    * or more contributor license agreements.  See the NOTICE file
6    * distributed with this work for additional information
7    * regarding copyright ownership.  The ASF licenses this file
8    * to you under the Apache License, Version 2.0 (the
9    * "License"); you may not use this file except in compliance
10   * with the License.  You may obtain a copy of the License at
11   *
12   *  http://www.apache.org/licenses/LICENSE-2.0
13   *
14   * Unless required by applicable law or agreed to in writing,
15   * software distributed under the License is distributed on an
16   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17   * KIND, either express or implied.  See the License for the
18   * specific language governing permissions and limitations
19   * under the License.
20   */
21  
22  import java.io.BufferedReader;
23  import java.io.File;
24  import java.io.FileReader;
25  import java.io.IOException;
26  import java.net.URL;
27  import java.util.Locale;
28  
29  import org.apache.commons.io.IOUtils;
30  import org.codehaus.plexus.util.FileUtils;
31  import org.codehaus.plexus.util.IOUtil;
32  
33  import com.github.tomakehurst.wiremock.WireMockServer;
34  import com.github.tomakehurst.wiremock.client.WireMock;
35  
36  /**
37   * @author <a href="mailto:oching@apache.org">Maria Odea Ching</a>
38   * @version $Id: PmdReportTest.html 938498 2015-01-31 17:43:24Z michaelo $
39   */
40  public class PmdReportTest
41      extends AbstractPmdReportTest
42  {
43      /**
44       * {@inheritDoc}
45       */
46      @Override
47      protected void setUp()
48          throws Exception
49      {
50          super.setUp();
51          FileUtils.deleteDirectory( new File( getBasedir(), "target/test/unit" ) );
52      }
53  
54      public void testDefaultConfiguration()
55          throws Exception
56      {
57          FileUtils.copyDirectoryStructure( new File( getBasedir(),
58                                                      "src/test/resources/unit/default-configuration/jxr-files" ),
59                                            new File( getBasedir(), "target/test/unit/default-configuration/target/site" ) );
60  
61          File testPom =
62              new File( getBasedir(),
63                        "src/test/resources/unit/default-configuration/default-configuration-plugin-config.xml" );
64          PmdReport mojo = (PmdReport) lookupMojo( "pmd", testPom );
65          mojo.execute();
66  
67          // check if the PMD files were generated
68          File generatedFile = new File( getBasedir(), "target/test/unit/default-configuration/target/pmd.xml" );
69          assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) );
70  
71          // check if the rulesets, that have been applied, have been copied
72          generatedFile = new File( getBasedir(), "target/test/unit/default-configuration/target/java-basic.xml" );
73          assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) );
74  
75          generatedFile = new File( getBasedir(), "target/test/unit/default-configuration/target/java-imports.xml" );
76          assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) );
77  
78          generatedFile = new File( getBasedir(), "target/test/unit/default-configuration/target/java-unusedcode.xml" );
79          assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) );
80  
81          generatedFile = new File( getBasedir(), "target/test/unit/default-configuration/target/site/pmd.html" );
82          renderer( mojo, generatedFile );
83          assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) );
84  
85          // check if there's a link to the JXR files
86          String str = readFile( new File( getBasedir(), "target/test/unit/default-configuration/target/site/pmd.html" ) );
87  
88          assertTrue( str.contains( "/xref/def/configuration/App.html#L31" ) );
89  
90          assertTrue( str.contains( "/xref/def/configuration/AppSample.html#L45" ) );
91      }
92  
93      public void testJavascriptConfiguration()
94          throws Exception
95      {
96          File testPom =
97              new File( getBasedir(),
98                        "src/test/resources/unit/default-configuration/javascript-configuration-plugin-config.xml" );
99          PmdReport mojo = (PmdReport) lookupMojo( "pmd", testPom );
100         mojo.execute();
101 
102         // check if the PMD files were generated
103         File generatedFile = new File( getBasedir(), "target/test/unit/default-configuration/target/pmd.xml" );
104         assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) );
105 
106         // these are the rulesets, that have been applied...
107         generatedFile = new File( getBasedir(), "target/test/unit/default-configuration/target/ecmascript-basic.xml" );
108         assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) );
109 
110         generatedFile = new File( getBasedir(), "target/test/unit/default-configuration/target/ecmascript-braces.xml" );
111         assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) );
112 
113         generatedFile =
114             new File( getBasedir(), "target/test/unit/default-configuration/target/ecmascript-unnecessary.xml" );
115         assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) );
116 
117         generatedFile = new File( getBasedir(), "target/test/unit/default-configuration/target/site/pmd.html" );
118         renderer( mojo, generatedFile );
119         assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) );
120 
121         String str = readFile( generatedFile );
122         assertTrue( str.contains( "Avoid using global variables" ) );
123     }
124 
125     public void testFileURL()
126         throws Exception
127     {
128         FileUtils.copyDirectoryStructure( new File( getBasedir(),
129                                                     "src/test/resources/unit/default-configuration/jxr-files" ),
130                                           new File( getBasedir(), "target/test/unit/default-configuration/target/site" ) );
131 
132         File testPom =
133             new File( getBasedir(),
134                       "src/test/resources/unit/default-configuration/default-configuration-plugin-config.xml" );
135         PmdReport mojo = (PmdReport) lookupMojo( "pmd", testPom );
136 
137         // Additional test case for MPMD-174 (http://jira.codehaus.org/browse/MPMD-174).
138         WireMockServer mockServer = new WireMockServer( 3456 );
139         mockServer.start();
140 
141         String sonarRuleset =
142             IOUtils.toString( getClass().getClassLoader().getResourceAsStream( "unit/default-configuration/rulesets/sonar-way-ruleset.xml" ) );
143 
144         String sonarMainPageHtml =
145             IOUtils.toString( getClass().getClassLoader().getResourceAsStream( "unit/default-configuration/rulesets/sonar-main-page.html" ) );
146 
147         final String sonarBaseUrl = "/profiles";
148         final String sonarProfileUrl = sonarBaseUrl + "/export?format=pmd&language=java&name=Sonar%2520way";
149         final String sonarExportRulesetUrl = "http://localhost:" + mockServer.port() + sonarProfileUrl;
150 
151         mockServer.stubFor( WireMock.get( WireMock.urlEqualTo( sonarBaseUrl ) ).willReturn( WireMock.aResponse().withStatus( 200 ).withHeader( "Content-Type",
152                                                                                                                                                "text/html" ).withBody( sonarMainPageHtml ) ) );
153 
154         mockServer.stubFor( WireMock.get( WireMock.urlEqualTo( sonarProfileUrl ) ).willReturn( WireMock.aResponse().withStatus( 200 ).withHeader( "Content-Type",
155                                                                                                                                                   "text/xml" ).withBody( sonarRuleset ) ) );
156 
157         URL url = getClass().getClassLoader().getResource( "rulesets/java/basic.xml" );
158         URL url2 = getClass().getClassLoader().getResource( "rulesets/java/unusedcode.xml" );
159         URL url3 = getClass().getClassLoader().getResource( "rulesets/java/imports.xml" );
160         mojo.setRulesets( new String[] { url.toString(), url2.toString(), url3.toString(), sonarExportRulesetUrl } );
161 
162         mojo.execute();
163 
164         // check if the PMD files were generated
165         File generatedFile = new File( getBasedir(), "target/test/unit/default-configuration/target/pmd.xml" );
166         assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) );
167 
168         generatedFile = new File( getBasedir(), "target/test/unit/default-configuration/target/basic.xml" );
169         assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) );
170 
171         generatedFile = new File( getBasedir(), "target/test/unit/default-configuration/target/imports.xml" );
172         assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) );
173 
174         generatedFile = new File( getBasedir(), "target/test/unit/default-configuration/target/unusedcode.xml" );
175         assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) );
176 
177         generatedFile =
178             new File( getBasedir(),
179                       "target/test/unit/default-configuration/target/export_format_pmd_language_java_name_Sonar_2520way.xml" );
180         assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) );
181 
182         generatedFile = new File( getBasedir(), "target/test/unit/default-configuration/target/site/pmd.html" );
183         renderer( mojo, generatedFile );
184         assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) );
185 
186         // check if there's a link to the JXR files
187         String str = readFile( new File( getBasedir(), "target/test/unit/default-configuration/target/site/pmd.html" ) );
188 
189         assertTrue( str.contains( "/xref/def/configuration/App.html#L31" ) );
190 
191         assertTrue( str.contains( "/xref/def/configuration/AppSample.html#L45" ) );
192 
193         mockServer.stop();
194     }
195 
196     /**
197      * With custom rulesets
198      *
199      * @throws Exception
200      */
201     public void testCustomConfiguration()
202         throws Exception
203     {
204         File testPom =
205             new File( getBasedir(),
206                       "src/test/resources/unit/custom-configuration/custom-configuration-plugin-config.xml" );
207 
208         PmdReport mojo = (PmdReport) lookupMojo( "pmd", testPom );
209         mojo.execute();
210 
211         // check the generated files
212         File generatedFile = new File( getBasedir(), "target/test/unit/custom-configuration/target/pmd.csv" );
213         assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) );
214 
215         generatedFile = new File( getBasedir(), "target/test/unit/custom-configuration/target/custom.xml" );
216         assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) );
217 
218         generatedFile = new File( getBasedir(), "target/test/unit/custom-configuration/target/site/pmd.html" );
219         renderer( mojo, generatedFile );
220         renderer( mojo, generatedFile );
221         assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) );
222 
223         // check if custom ruleset was applied
224         String str = readFile( new File( getBasedir(), "target/test/unit/custom-configuration/target/site/pmd.html" ) );
225         assertTrue( str.toLowerCase().contains( "Avoid using if statements without curly braces".toLowerCase() ) );
226 
227         // Must be false as IfElseStmtsMustUseBraces is excluded!
228         assertFalse( str.toLowerCase().contains( "Avoid using if...else statements without curly braces".toLowerCase() ) );
229 
230         assertTrue( "unnecessary constructor should not be triggered because of low priority",
231                     !str.toLowerCase().contains( "Avoid unnecessary constructors - the compiler will generate these for you".toLowerCase() ) );
232 
233         // veryLongVariableNameWithViolation is really too long
234         assertTrue( str.toLowerCase().contains( "veryLongVariableNameWithViolation".toLowerCase() ) );
235         // notSoLongVariableName should not be reported
236         assertFalse( str.toLowerCase().contains( "notSoLongVariableName".toLowerCase() ) );
237     }
238 
239     /**
240      * Verify skip parameter
241      *
242      * @throws Exception
243      */
244     public void testSkipConfiguration()
245         throws Exception
246     {
247         File testPom = new File( getBasedir(), "src/test/resources/unit/custom-configuration/skip-plugin-config.xml" );
248         PmdReport mojo = (PmdReport) lookupMojo( "pmd", testPom );
249         mojo.execute();
250 
251         // verify the generated files do not exist because PMD was skipped
252         File generatedFile = new File( getBasedir(), "target/test/unit/skip-configuration/target/pmd.csv" );
253         assertFalse( FileUtils.fileExists( generatedFile.getAbsolutePath() ) );
254 
255         generatedFile = new File( getBasedir(), "target/test/unit/custom-configuration/target/custom.xml" );
256         assertFalse( FileUtils.fileExists( generatedFile.getAbsolutePath() ) );
257 
258         generatedFile = new File( getBasedir(), "target/test/unit/custom-configuration/target/site/pmd.html" );
259         assertFalse( FileUtils.fileExists( generatedFile.getAbsolutePath() ) );
260     }
261 
262     public void testSkipEmptyReportConfiguration()
263         throws Exception
264     {
265         File testPom =
266             new File( getBasedir(), "src/test/resources/unit/empty-report/skip-empty-report-plugin-config.xml" );
267         PmdReport mojo = (PmdReport) lookupMojo( "pmd", testPom );
268         mojo.execute();
269 
270         // verify the generated files do not exist because PMD was skipped
271         File generatedFile = new File( getBasedir(), "target/test/unit/empty-report/target/site/pmd.html" );
272         assertFalse( FileUtils.fileExists( generatedFile.getAbsolutePath() ) );
273     }
274 
275     public void testEmptyReportConfiguration()
276         throws Exception
277     {
278         File testPom = new File( getBasedir(), "src/test/resources/unit/empty-report/empty-report-plugin-config.xml" );
279         PmdReport mojo = (PmdReport) lookupMojo( "pmd", testPom );
280         mojo.execute();
281 
282         // verify the generated files do exist, even if there are no violations
283         File generatedFile = new File( getBasedir(), "target/test/unit/empty-report/target/site/pmd.html" );
284         assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) );
285         String str = readFile( new File( getBasedir(), "target/test/unit/empty-report/target/site/pmd.html" ) );
286         assertTrue( !str.toLowerCase().contains( "Hello.java".toLowerCase() ) );
287     }
288 
289     public void testInvalidFormat()
290         throws Exception
291     {
292         try
293         {
294             File testPom =
295                 new File( getBasedir(), "src/test/resources/unit/invalid-format/invalid-format-plugin-config.xml" );
296             PmdReport mojo = (PmdReport) lookupMojo( "pmd", testPom );
297             setVariableValueToObject( mojo, "compileSourceRoots", mojo.project.getCompileSourceRoots() );
298             mojo.executeReport( Locale.ENGLISH );
299 
300             fail( "Must throw MavenReportException." );
301         }
302         catch ( Exception e )
303         {
304             assertTrue( true );
305         }
306     }
307 
308     public void testInvalidTargetJdk()
309         throws Exception
310     {
311         try
312         {
313             File testPom =
314                 new File( getBasedir(), "src/test/resources/unit/invalid-format/invalid-target-jdk-plugin-config.xml" );
315             PmdReport mojo = (PmdReport) lookupMojo( "pmd", testPom );
316             mojo.execute();
317 
318             fail( "Must throw MavenReportException." );
319         }
320         catch ( Exception e )
321         {
322             assertTrue( true );
323         }
324     }
325 
326     /**
327      * Read the contents of the specified file object into a string
328      *
329      * @param file the file to be read
330      * @return a String object that contains the contents of the file
331      * @throws java.io.IOException
332      */
333     private String readFile( File file )
334         throws IOException
335     {
336         String strTmp;
337         StringBuilder str = new StringBuilder( (int) file.length() );
338         FileReader reader = null;
339         BufferedReader in = null;
340         try
341         {
342             reader = new FileReader( file );
343             in = new BufferedReader( reader );
344 
345             while ( ( strTmp = in.readLine() ) != null )
346             {
347                 str.append( ' ' );
348                 str.append( strTmp );
349             }
350             in.close();
351         }
352         finally
353         {
354             IOUtil.close( in );
355             IOUtil.close( reader );
356         }
357 
358         return str.toString();
359     }
360 
361     /**
362      * Verify the correct working of the localtionTemp method
363      *
364      * @throws Exception
365      */
366     public void testLocationTemp()
367         throws Exception
368     {
369 
370         File testPom =
371             new File( getBasedir(),
372                       "src/test/resources/unit/default-configuration/default-configuration-plugin-config.xml" );
373         PmdReport mojo = (PmdReport) lookupMojo( "pmd", testPom );
374 
375         assertEquals( "locationTemp is not correctly encoding filename",
376                       "export_format_pmd_language_java_name_some_2520name.xml",
377                       mojo.getLocationTemp( "http://nemo.sonarsource.org/sonar/profiles/export?format=pmd&language=java&name=some%2520name" ) );
378 
379     }
380 
381     /**
382      * Verify that suppressMarker works
383      *
384      * @throws Exception
385      */
386     public void testSuppressMarkerConfiguration()
387         throws Exception
388     {
389         File testPom =
390             new File( getBasedir(),
391                       "src/test/resources/unit/default-configuration/pmd-with-suppressMarker-plugin-config.xml" );
392         PmdReport mojo = (PmdReport) lookupMojo( "pmd", testPom );
393         mojo.execute();
394 
395         // check if the PMD files were generated
396         File generatedFile = new File( getBasedir(), "target/test/unit/default-configuration/target/pmd.xml" );
397         assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) );
398 
399         String str = readFile( new File( getBasedir(), "target/test/unit/default-configuration/target/pmd.xml" ) );
400 
401         // check that there is no violation reported for "unusedVar2" - as it is suppressed
402         assertFalse( str.contains( "Avoid unused private fields such as 'unusedVar2'." ) );
403     }
404 
405     public void testJspConfiguration()
406             throws Exception
407     {
408         File testPom = new File( getBasedir(),
409                 "src/test/resources/unit/default-configuration/jsp-configuration-plugin-config.xml" );
410         PmdReport mojo = (PmdReport) lookupMojo( "pmd", testPom );
411         mojo.execute();
412 
413         // check if the PMD files were generated
414         File generatedFile = new File( getBasedir(), "target/test/unit/default-configuration/target/pmd.xml" );
415         assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) );
416 
417         // these are the rulesets, that have been applied...
418         generatedFile = new File( getBasedir(), "target/test/unit/default-configuration/target/jsp-basic.xml" );
419         assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) );
420 
421         generatedFile = new File( getBasedir(), "target/test/unit/default-configuration/target/site/pmd.html" );
422         renderer( mojo, generatedFile );
423         assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) );
424 
425         String str = readFile( generatedFile );
426         assertTrue(str.contains("JSP file should use UTF-8 encoding"));
427         assertTrue(str.contains("Using unsanitized JSP expression can lead to Cross Site Scripting (XSS) attacks"));
428         assertTrue(str.contains("Avoid having style information in JSP files."));
429     }
430 
431 
432 }