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.util.ArrayList;
27  import java.util.Iterator;
28  import java.util.List;
29  import java.util.Locale;
30  
31  import javax.xml.parsers.DocumentBuilder;
32  import javax.xml.parsers.DocumentBuilderFactory;
33  
34  import net.sourceforge.pmd.cpd.CPD;
35  import net.sourceforge.pmd.cpd.CPDConfiguration;
36  import net.sourceforge.pmd.cpd.JavaLanguage;
37  import net.sourceforge.pmd.cpd.Mark;
38  import net.sourceforge.pmd.cpd.Match;
39  import net.sourceforge.pmd.cpd.TokenEntry;
40  
41  import org.codehaus.plexus.util.FileUtils;
42  import org.w3c.dom.Document;
43  
44  /**
45   * @author <a href="mailto:oching@apache.org">Maria Odea Ching</a>
46   * @version $Id: CpdReportTest.html 956788 2015-07-03 06:40:21Z dennisl $
47   */
48  public class CpdReportTest
49      extends AbstractPmdReportTest
50  {
51      /**
52       * {@inheritDoc}
53       */
54      @Override
55      protected void setUp()
56          throws Exception
57      {
58          super.setUp();
59          FileUtils.deleteDirectory( new File( getBasedir(), "target/test/unit" ) );
60      }
61  
62      /**
63       * Test CPDReport given the default configuration
64       *
65       * @throws Exception
66       */
67      public void testDefaultConfiguration()
68          throws Exception
69      {
70          File testPom =
71              new File( getBasedir(),
72                        "src/test/resources/unit/default-configuration/cpd-default-configuration-plugin-config.xml" );
73          CpdReport mojo = (CpdReport) lookupMojo( "cpd", testPom );
74          mojo.execute();
75  
76          // check if the CPD files were generated
77          File generatedFile = new File( getBasedir(), "target/test/unit/default-configuration/target/cpd.xml" );
78          assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) );
79  
80          generatedFile = new File( getBasedir(), "target/test/unit/default-configuration/target/site/cpd.html" );
81          renderer( mojo, generatedFile );
82          assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) );
83  
84          // check the contents of cpd.html
85          String str = readFile( new File( getBasedir(), "target/test/unit/default-configuration/target/site/cpd.html" ) );
86          assertTrue( str.toLowerCase().contains( "AppSample.java".toLowerCase() ) );
87  
88          str = readFile( new File( getBasedir(), "target/test/unit/default-configuration/target/site/cpd.html" ) );
89          assertTrue( str.toLowerCase().contains( "App.java".toLowerCase() ) );
90  
91          str = readFile( new File( getBasedir(), "target/test/unit/default-configuration/target/site/cpd.html" ) );
92          assertTrue( str.toLowerCase().contains( "public String dup( String str )".toLowerCase() ) );
93  
94          str = readFile( new File( getBasedir(), "target/test/unit/default-configuration/target/site/cpd.html" ) );
95          assertTrue( str.toLowerCase().contains( "tmp = tmp + str.substring( i, i + 1);".toLowerCase() ) );
96  
97      }
98  
99      /**
100      * Test CPDReport using custom configuration
101      *
102      * @throws Exception
103      */
104     public void testCustomConfiguration()
105         throws Exception
106     {
107         File testPom =
108             new File( getBasedir(),
109                       "src/test/resources/unit/custom-configuration/cpd-custom-configuration-plugin-config.xml" );
110         CpdReport mojo = (CpdReport) lookupMojo( "cpd", testPom );
111         mojo.execute();
112 
113         // check if the CPD files were generated
114         File generatedFile = new File( getBasedir(), "target/test/unit/custom-configuration/target/cpd.csv" );
115         assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) );
116 
117         generatedFile = new File( getBasedir(), "target/test/unit/custom-configuration/target/site/cpd.html" );
118         renderer( mojo, generatedFile );
119         assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) );
120 
121         // Contents that should NOT be in the report
122         String str = readFile( new File( getBasedir(), "target/test/unit/custom-configuration/target/site/cpd.html" ) );
123         assertTrue( !str.toLowerCase().contains( "/Sample.java".toLowerCase() ) );
124 
125         str = readFile( new File( getBasedir(), "target/test/unit/custom-configuration/target/site/cpd.html" ) );
126         assertTrue( !str.toLowerCase().contains( "public void duplicateMethod( int i )".toLowerCase() ) );
127 
128         // Contents that should be in the report
129         str = readFile( new File( getBasedir(), "target/test/unit/custom-configuration/target/site/cpd.html" ) );
130         assertTrue( str.toLowerCase().contains( "AnotherSample.java".toLowerCase() ) );
131 
132         str = readFile( new File( getBasedir(), "target/test/unit/custom-configuration/target/site/cpd.html" ) );
133         assertTrue( str.toLowerCase().contains( "public static void main( String[] args )".toLowerCase() ) );
134 
135         str = readFile( new File( getBasedir(), "target/test/unit/custom-configuration/target/site/cpd.html" ) );
136         assertTrue( str.toLowerCase().contains( "private String unusedMethod(".toLowerCase() ) );
137 
138     }
139 
140     /**
141      * Test CPDReport with invalid format
142      *
143      * @throws Exception
144      */
145     public void testInvalidFormat()
146         throws Exception
147     {
148         try
149         {
150             File testPom =
151                 new File( getBasedir(), "src/test/resources/unit/invalid-format/cpd-invalid-format-plugin-config.xml" );
152             CpdReport mojo = (CpdReport) lookupMojo( "cpd", testPom );
153             setVariableValueToObject( mojo, "compileSourceRoots", mojo.project.getCompileSourceRoots() );
154             mojo.execute();
155 
156             fail( "MavenReportException must be thrown" );
157         }
158         catch ( Exception e )
159         {
160             assertTrue( true );
161         }
162 
163     }
164 
165     /**
166      * Read the contents of the specified file object into a string
167      *
168      * @param file the file to be read
169      * @return a String object that contains the contents of the file
170      * @throws java.io.IOException
171      */
172     private String readFile( File file )
173         throws IOException
174     {
175         String strTmp;
176         StringBuilder str = new StringBuilder( (int) file.length() );
177         BufferedReader in = new BufferedReader( new FileReader( file ) );
178 
179         while ( ( strTmp = in.readLine() ) != null )
180         {
181             str.append( ' ' );
182             str.append( strTmp );
183         }
184         in.close();
185 
186         return str.toString();
187     }
188 
189     public void testWriteNonHtml()
190         throws Exception
191     {
192         File testPom =
193             new File( getBasedir(),
194                       "src/test/resources/unit/default-configuration/cpd-default-configuration-plugin-config.xml" );
195         CpdReport mojo = (CpdReport) lookupMojo( "cpd", testPom );
196         assertNotNull( mojo );
197 
198         TokenEntry tFirstEntry = new TokenEntry( "public java", "MyClass.java", 34 );
199         TokenEntry tSecondEntry = new TokenEntry( "public java", "MyClass3.java", 55 );
200         List<Match> tList = new ArrayList<Match>();
201         Mark tFirstMark = new Mark( tFirstEntry );
202         Mark tSecondMark = new Mark( tSecondEntry );
203         tFirstMark.setSoureCodeSlice( "// ----- ACCESSEURS  avec �l�ments -----" );
204         Match tMatch = new Match( 2, tFirstMark, tSecondMark );
205         tList.add( tMatch );
206 
207         CPDConfiguration cpdConfiguration = new CPDConfiguration();
208         cpdConfiguration.setMinimumTileSize( 100 );
209         cpdConfiguration.setLanguage( new JavaLanguage() );
210         cpdConfiguration.setEncoding( "UTF-8" );
211         CPD tCpd = new MockCpd( cpdConfiguration, tList.iterator() );
212 
213         tCpd.go();
214         mojo.writeNonHtml( tCpd );
215 
216         File tReport = new File( "target/test/unit/default-configuration/target/cpd.xml" );
217         // parseDocument( new BufferedInputStream( new FileInputStream( report ) ) );
218 
219         DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
220         Document pmdCpdDocument = builder.parse( tReport );
221         assertNotNull( pmdCpdDocument );
222     }
223 
224     public void testSkipEmptyReportConfiguration()
225         throws Exception
226     {
227         File testPom =
228             new File( getBasedir(), "src/test/resources/unit/empty-report/cpd-skip-empty-report-plugin-config.xml" );
229         CpdReport mojo = (CpdReport) lookupMojo( "cpd", testPom );
230         mojo.execute();
231 
232         // verify the generated files do not exist because PMD was skipped
233         File generatedFile = new File( getBasedir(), "target/test/unit/empty-report/target/site/cpd.html" );
234         assertFalse( FileUtils.fileExists( generatedFile.getAbsolutePath() ) );
235     }
236 
237     public void testEmptyReportConfiguration()
238         throws Exception
239     {
240         File testPom =
241             new File( getBasedir(), "src/test/resources/unit/empty-report/cpd-empty-report-plugin-config.xml" );
242         CpdReport mojo = (CpdReport) lookupMojo( "cpd", testPom );
243         mojo.execute();
244 
245         // verify the generated files do exist, even if there are no violations
246         File generatedFile = new File( getBasedir(), "target/test/unit/empty-report/target/site/cpd.html" );
247         assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) );
248         String str = readFile( new File( getBasedir(), "target/test/unit/empty-report/target/site/cpd.html" ) );
249         assertTrue( !str.toLowerCase().contains( "Hello.java".toLowerCase() ) );
250     }
251 
252     public void testCpdEncodingConfiguration()
253         throws Exception
254     {
255         String originalEncoding = System.getProperty( "file.encoding" );
256         try
257         {
258             System.setProperty( "file.encoding", "UTF-16" );
259 
260             File testPom =
261                 new File( getBasedir(),
262                           "src/test/resources/unit/default-configuration/cpd-default-configuration-plugin-config.xml" );
263             CpdReport mojo = (CpdReport) lookupMojo( "cpd", testPom );
264             mojo.execute();
265 
266             // check if the CPD files were generated
267             File generatedFile = new File( getBasedir(), "target/test/unit/default-configuration/target/cpd.xml" );
268             assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) );
269             String str = readFile( generatedFile );
270             assertTrue( str.toLowerCase().contains( "AppSample.java".toLowerCase() ) );
271         }
272         finally
273         {
274             System.setProperty( "file.encoding", originalEncoding );
275         }
276     }
277 
278     public void testCpdJavascriptConfiguration()
279         throws Exception
280     {
281         File testPom =
282                 new File( getBasedir(), "src/test/resources/unit/default-configuration/cpd-javascript-plugin-config.xml" );
283             CpdReport mojo = (CpdReport) lookupMojo( "cpd", testPom );
284             mojo.execute();
285 
286             // verify  the generated file to exist and violations are reported
287             File generatedFile = new File( getBasedir(), "target/test/unit/default-configuration/target/cpd.xml" );
288             assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) );
289             String str = readFile( generatedFile );
290             assertTrue( str.toLowerCase(Locale.ROOT).contains( "Sample.js".toLowerCase(Locale.ROOT) ) );
291             assertTrue( str.toLowerCase(Locale.ROOT).contains( "SampleDup.js".toLowerCase(Locale.ROOT) ) );
292     }
293 
294     public void testCpdJspConfiguration()
295             throws Exception
296     {
297         File testPom =
298                 new File( getBasedir(), "src/test/resources/unit/default-configuration/cpd-jsp-plugin-config.xml" );
299             CpdReport mojo = (CpdReport) lookupMojo( "cpd", testPom );
300             mojo.execute();
301 
302             // verify  the generated file to exist and violations are reported
303             File generatedFile = new File( getBasedir(), "target/test/unit/default-configuration/target/cpd.xml" );
304             assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) );
305             String str = readFile( generatedFile );
306             assertTrue( str.toLowerCase(Locale.ROOT).contains( "sample.jsp".toLowerCase(Locale.ROOT) ) );
307             assertTrue( str.toLowerCase(Locale.ROOT).contains( "sampleDup.jsp".toLowerCase(Locale.ROOT) ) );
308     }
309 
310     public static class MockCpd
311         extends CPD
312     {
313 
314         private Iterator<Match> matches;
315 
316         public MockCpd( CPDConfiguration configuration, Iterator<Match> tMatch )
317         {
318             super( configuration );
319             matches = tMatch;
320         }
321 
322         @Override
323         public Iterator<Match> getMatches()
324         {
325             return matches;
326         }
327 
328     }
329 
330 }