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