View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.maven.plugins.pmd;
20  
21  import javax.xml.parsers.DocumentBuilder;
22  import javax.xml.parsers.DocumentBuilderFactory;
23  
24  import java.io.BufferedReader;
25  import java.io.File;
26  import java.io.FileReader;
27  import java.io.IOException;
28  import java.util.Locale;
29  
30  import org.apache.commons.lang3.StringUtils;
31  import org.codehaus.plexus.util.FileUtils;
32  import org.w3c.dom.Document;
33  
34  /**
35   * @author <a href="mailto:oching@apache.org">Maria Odea Ching</a>
36   * @version $Id$
37   */
38  public class CpdReportTest extends AbstractPmdReportTestCase {
39      /**
40       * {@inheritDoc}
41       */
42      @Override
43      protected void setUp() throws Exception {
44          super.setUp();
45          Locale.setDefault(Locale.ENGLISH);
46          FileUtils.deleteDirectory(new File(getBasedir(), "target/test/unit"));
47      }
48  
49      /**
50       * Test CPDReport given the default configuration
51       *
52       * @throws Exception
53       */
54      public void testDefaultConfiguration() throws Exception {
55          File generatedReport =
56                  generateReport("cpd", "default-configuration/cpd-default-configuration-plugin-config.xml");
57          assertTrue(FileUtils.fileExists(generatedReport.getAbsolutePath()));
58  
59          // check if the CPD files were generated
60          File generatedFile = new File(getBasedir(), "target/test/unit/default-configuration/target/cpd.xml");
61          assertTrue(FileUtils.fileExists(generatedFile.getAbsolutePath()));
62  
63          // check the contents of cpd.html
64          String str = readFile(generatedReport);
65          assertTrue(lowerCaseContains(str, "AppSample.java"));
66          assertTrue(lowerCaseContains(str, "App.java"));
67          assertTrue(lowerCaseContains(str, "public String dup( String str )"));
68          assertTrue(lowerCaseContains(str, "tmp = tmp + str.substring( i, i + 1);"));
69  
70          // the version should be logged
71          String output = CapturingPrintStream.getOutput();
72          assertTrue(output.contains("PMD version: " + AbstractPmdReport.getPmdVersion()));
73      }
74  
75      /**
76       * Test CPDReport with the text renderer given as "format=txt"
77       *
78       * @throws Exception
79       */
80      public void testTxtFormat() throws Exception {
81          generateReport("cpd", "custom-configuration/cpd-txt-format-configuration-plugin-config.xml");
82  
83          // check if the CPD files were generated
84          File generatedFile = new File(getBasedir(), "target/test/unit/custom-configuration/target/cpd.xml");
85          assertTrue(FileUtils.fileExists(generatedFile.getAbsolutePath()));
86          generatedFile = new File(getBasedir(), "target/test/unit/custom-configuration/target/cpd.txt");
87          assertTrue(FileUtils.fileExists(generatedFile.getAbsolutePath()));
88  
89          // check the contents of cpd.txt
90          String str = readFile(generatedFile);
91          // Contents that should NOT be in the report
92          assertFalse(lowerCaseContains(str, "public static void main( String[] args )"));
93          // Contents that should be in the report
94          assertTrue(lowerCaseContains(str, "public void duplicateMethod( int i )"));
95      }
96  
97      /**
98       * Test CPDReport using custom configuration
99       *
100      * @throws Exception
101      */
102     public void testCustomConfiguration() throws Exception {
103         File generatedReport = generateReport("cpd", "custom-configuration/cpd-custom-configuration-plugin-config.xml");
104         assertTrue(FileUtils.fileExists(generatedReport.getAbsolutePath()));
105 
106         // check if the CPD files were generated
107         File generatedFile = new File(getBasedir(), "target/test/unit/custom-configuration/target/cpd.csv");
108         assertTrue(FileUtils.fileExists(generatedFile.getAbsolutePath()));
109 
110         String str = readFile(generatedReport);
111         // Contents that should NOT be in the report
112         assertFalse(lowerCaseContains(str, "/Sample.java"));
113         assertFalse(lowerCaseContains(str, "public void duplicateMethod( int i )"));
114         // Contents that should be in the report
115         assertTrue(lowerCaseContains(str, "AnotherSample.java"));
116         assertTrue(lowerCaseContains(str, "public static void main( String[] args )"));
117         assertTrue(lowerCaseContains(str, "private String unusedMethod("));
118     }
119 
120     /**
121      * Test CPDReport with invalid format
122      *
123      * @throws Exception
124      */
125     public void testInvalidFormat() throws Exception {
126         try {
127             File testPom = new File(
128                     getBasedir(), "src/test/resources/unit/invalid-format/cpd-invalid-format-plugin-config.xml");
129             AbstractPmdReport mojo = createReportMojo("cpd", testPom);
130             setVariableValueToObject(
131                     mojo, "compileSourceRoots", mojo.getProject().getCompileSourceRoots());
132             generateReport(mojo, testPom);
133 
134             fail("MavenReportException must be thrown");
135         } catch (Exception e) {
136             assertTrue(true);
137         }
138     }
139 
140     /**
141      * Read the contents of the specified file object into a string
142      *
143      * @param file the file to be read
144      * @return a String object that contains the contents of the file
145      * @throws java.io.IOException
146      */
147     private String readFile(File file) throws IOException {
148         String strTmp;
149         StringBuilder str = new StringBuilder((int) file.length());
150         try (BufferedReader in = new BufferedReader(new FileReader(file))) {
151             while ((strTmp = in.readLine()) != null) {
152                 str.append(' ');
153                 str.append(strTmp);
154             }
155         }
156 
157         return str.toString();
158     }
159 
160     public void testWriteNonHtml() throws Exception {
161         generateReport("cpd", "default-configuration/cpd-default-configuration-plugin-config.xml");
162 
163         // check if the CPD files were generated
164         File generatedFile = new File(getBasedir(), "target/test/unit/default-configuration/target/cpd.xml");
165         assertTrue(FileUtils.fileExists(generatedFile.getAbsolutePath()));
166 
167         DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
168         Document pmdCpdDocument = builder.parse(generatedFile);
169         assertNotNull(pmdCpdDocument);
170 
171         String str = readFile(generatedFile);
172         assertTrue(lowerCaseContains(str, "AppSample.java"));
173         assertTrue(lowerCaseContains(str, "App.java"));
174         assertTrue(lowerCaseContains(str, "public String dup( String str )"));
175         assertTrue(lowerCaseContains(str, "tmp = tmp + str.substring( i, i + 1);"));
176     }
177 
178     /**
179      * verify the cpd.xml file is included in the site when requested.
180      * @throws Exception
181      */
182     public void testIncludeXmlInSite() throws Exception {
183         generateReport("cpd", "default-configuration/cpd-report-include-xml-in-site-plugin-config.xml");
184 
185         File generatedFile = new File(getBasedir(), "target/test/unit/default-configuration/target/cpd.xml");
186         assertTrue(FileUtils.fileExists(generatedFile.getAbsolutePath()));
187 
188         DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
189         Document pmdCpdDocument = builder.parse(generatedFile);
190         assertNotNull(pmdCpdDocument);
191 
192         String str = readFile(generatedFile);
193         assertTrue(str.contains("</pmd-cpd>"));
194 
195         File siteReport = new File(getBasedir(), "target/test/unit/default-configuration/target/site/cpd.xml");
196         assertTrue(FileUtils.fileExists(siteReport.getAbsolutePath()));
197         String siteReportContent = readFile(siteReport);
198         assertTrue(siteReportContent.contains("</pmd-cpd>"));
199         assertEquals(str, siteReportContent);
200     }
201 
202     public void testSkipEmptyReportConfiguration() throws Exception {
203         // verify the generated files do not exist because PMD was skipped
204         File generatedReport = generateReport("cpd", "empty-report/cpd-skip-empty-report-plugin-config.xml");
205         assertFalse(FileUtils.fileExists(generatedReport.getAbsolutePath()));
206     }
207 
208     public void testEmptyReportConfiguration() throws Exception {
209         // verify the generated files do exist, even if there are no violations
210         File generatedReport = generateReport("cpd", "empty-report/cpd-empty-report-plugin-config.xml");
211         assertTrue(FileUtils.fileExists(generatedReport.getAbsolutePath()));
212 
213         String str = readFile(generatedReport);
214         assertFalse(lowerCaseContains(str, "Hello.java"));
215         assertTrue(str.contains("CPD found no problems in your source code."));
216     }
217 
218     public void testCpdEncodingConfiguration() throws Exception {
219         String originalEncoding = System.getProperty("file.encoding");
220         try {
221             System.setProperty("file.encoding", "UTF-16");
222 
223             generateReport("cpd", "default-configuration/cpd-default-configuration-plugin-config.xml");
224 
225             // check if the CPD files were generated
226             File generatedFile = new File(getBasedir(), "target/test/unit/default-configuration/target/cpd.xml");
227             assertTrue(FileUtils.fileExists(generatedFile.getAbsolutePath()));
228             String str = readFile(generatedFile);
229             assertTrue(lowerCaseContains(str, "AppSample.java"));
230         } finally {
231             System.setProperty("file.encoding", originalEncoding);
232         }
233     }
234 
235     public void testCpdJavascriptConfiguration() throws Exception {
236         generateReport("cpd", "default-configuration/cpd-javascript-plugin-config.xml");
237 
238         // verify  the generated file to exist and violations are reported
239         File generatedFile = new File(getBasedir(), "target/test/unit/default-configuration/target/cpd.xml");
240         assertTrue(FileUtils.fileExists(generatedFile.getAbsolutePath()));
241         String str = readFile(generatedFile);
242         assertTrue(lowerCaseContains(str, "Sample.js"));
243         assertTrue(lowerCaseContains(str, "SampleDup.js"));
244     }
245 
246     public void testCpdJspConfiguration() throws Exception {
247         generateReport("cpd", "default-configuration/cpd-jsp-plugin-config.xml");
248 
249         // verify  the generated file to exist and violations are reported
250         File generatedFile = new File(getBasedir(), "target/test/unit/default-configuration/target/cpd.xml");
251         assertTrue(FileUtils.fileExists(generatedFile.getAbsolutePath()));
252         String str = readFile(generatedFile);
253         assertTrue(lowerCaseContains(str, "sample.jsp"));
254         assertTrue(lowerCaseContains(str, "sampleDup.jsp"));
255     }
256 
257     public void testExclusionsConfiguration() throws Exception {
258         generateReport("cpd", "default-configuration/cpd-report-cpd-exclusions-configuration-plugin-config.xml");
259 
260         // verify  the generated file to exist and no duplications are reported
261         File generatedFile = new File(getBasedir(), "target/test/unit/default-configuration/target/cpd.xml");
262         assertTrue(FileUtils.fileExists(generatedFile.getAbsolutePath()));
263         String str = readFile(generatedFile);
264         assertEquals(0, StringUtils.countMatches(str, "<duplication"));
265     }
266 }