View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.rat.mp;
18  
19  import static java.nio.charset.StandardCharsets.UTF_8;
20  import static org.apache.rat.mp.RatTestHelpers.ensureRatReportIsCorrect;
21  import static org.apache.rat.mp.RatTestHelpers.getSourceDirectory;
22  import static org.apache.rat.mp.RatTestHelpers.newArtifactFactory;
23  import static org.apache.rat.mp.RatTestHelpers.newArtifactRepository;
24  import static org.apache.rat.mp.RatTestHelpers.newSiteRenderer;
25  import static org.assertj.core.api.Assertions.assertThat;
26  
27  import java.io.File;
28  
29  import org.apache.commons.io.FileUtils;
30  import org.apache.rat.ReportConfiguration;
31  import org.apache.rat.ReportConfigurationTest;
32  import org.apache.rat.license.ILicenseFamily;
33  import org.apache.rat.license.LicenseFamilySetFactory;
34  import org.apache.rat.license.LicenseSetFactory;
35  import org.apache.rat.license.LicenseSetFactory.LicenseFilter;
36  import org.apache.rat.testhelpers.TextUtils;
37  import org.apache.rat.walker.NameBasedHiddenFileFilter;
38  
39  /**
40   * Test case for the {@link RatCheckMojo} and {@link RatReportMojo}.
41   */
42  public class RatCheckMojoTest extends BetterAbstractMojoTestCase {
43  
44      /**
45       * Creates a new instance of {@link RatCheckMojo}.
46       *
47       * @param pDir The directory, where to look for a pom.xml file.
48       * @return The configured Mojo.
49       * @throws Exception An error occurred while creating the Mojo.
50       */
51      private RatCheckMojo newRatCheckMojo(String pDir) throws Exception {
52          return (RatCheckMojo) newRatMojo(pDir, "check", false);
53      }
54  
55      /**
56       * Creates a new instance of {@link AbstractRatMojo}.
57       *
58       * @param pDir The directory, where to look for a pom.xml file.
59       * @param pGoal The goal, which the Mojo must implement.
60       * @param pCreateCopy if {@code true} copy the directory contents and return the
61       * copy location.
62       * @return The configured Mojo.
63       * @throws Exception An error occurred while creating the Mojo.
64       */
65      private AbstractRatMojo newRatMojo(String pDir, String pGoal, boolean pCreateCopy) throws Exception {
66          final File baseDir = new File(getBasedir());
67          final File testBaseDir = getSourceDirectory(getBasedir(), pDir, pCreateCopy, baseDir);
68          final File testPom = new File(testBaseDir, "pom.xml");
69          final File buildDirectory = new File(new File(baseDir, "target/test"), pDir);
70          AbstractRatMojo mojo = (AbstractRatMojo) lookupConfiguredMojo(testPom, pGoal);
71          assertNotNull(mojo);
72  
73          assertNotNull("The mojo is missing its MavenProject, which will result in an NPE during rat runs.",
74                  mojo.getProject());
75  
76          if (mojo instanceof RatReportMojo) {
77              setVariableValueToObject(mojo, "localRepository", newArtifactRepository(getContainer()));
78              setVariableValueToObject(mojo, "factory", newArtifactFactory());
79              setVariableValueToObject(mojo, "siteRenderer", newSiteRenderer(getContainer()));
80          } else if (mojo instanceof RatCheckMojo) {
81              final File ratTxtFile = new File(buildDirectory, "rat.txt");
82              FileUtils.write(ratTxtFile, "", UTF_8); // Ensure the output file exists and is empty (rerunning the test will append)
83              setVariableValueToObject(mojo, "reportFile", ratTxtFile);
84          }
85          return mojo;
86      }
87  
88      /**
89       * Reads the location of the rat text file from the Mojo.
90       *
91       * @param pMojo The configured Mojo.
92       * @return Value of the "reportFile" property.
93       * @throws Exception An error occurred while reading the property.
94       */
95      private File getRatTxtFile(RatCheckMojo pMojo) throws Exception {
96          return (File) getVariableValueFromObject(pMojo, "reportFile");
97      }
98  
99      private String getDir(RatCheckMojo mojo) {
100         return mojo.getProject().getBasedir().getAbsolutePath().replace("\\","/") + "/";
101     }
102     /**
103      * Runs a check, which should expose no problems.
104      *
105      * @throws Exception The test failed.
106      */
107     public void testIt1() throws Exception {
108 
109         final RatCheckMojo mojo = newRatCheckMojo("it1");
110         final File ratTxtFile = getRatTxtFile(mojo);
111         final String[] expected = { " AL +\\Q" + getDir(mojo) + "pom.xml\\E", "Notes: 0", "Binaries: 0", "Archives: 0",
112                 "Standards: 1$", "Apache Licensed: 1$", "Generated Documents: 0", "^0 Unknown Licenses" };
113 
114         ReportConfiguration config = mojo.getConfiguration();
115         ReportConfigurationTest.validateDefault(config);
116 
117         mojo.execute();
118         ensureRatReportIsCorrect(ratTxtFile, expected, TextUtils.EMPTY);
119     }
120 
121     /**
122      * Runs a check, which should detect a problem.
123      *
124      * @throws Exception The test failed.
125      */
126     public void testIt2() throws Exception {
127 
128         final RatCheckMojo mojo = newRatCheckMojo("it2");
129         final File ratTxtFile = getRatTxtFile(mojo);
130         final String dir = getDir(mojo);
131         final String[] expected = { "^Files with unapproved licenses:\\s+\\Q" + dir + "src.txt\\E\\s+", "Notes: 0",
132                 "Binaries: 0", "Archives: 0", "Standards: 2$", "Apache Licensed: 1$", "Generated Documents: 0",
133                 "^1 Unknown Licenses", " AL +\\Q" + dir + "pom.xml\\E$", "\\Q!????? " + dir + "src.txt\\E$",
134                 "^== File: \\Q" + dir + "src.txt\\E$" };
135         try {
136             mojo.execute();
137             fail("Expected RatCheckException");
138         } catch (RatCheckException e) {
139             final String msg = e.getMessage();
140             assertTrue("report filename was not contained in '" + msg + "'", msg.contains(ratTxtFile.getName()));
141             assertFalse("no null allowed in '" + msg + "'", (msg.toUpperCase().contains("NULL")));
142             ensureRatReportIsCorrect(ratTxtFile, expected, TextUtils.EMPTY);
143         }
144     }
145 
146     /**
147      * Tests adding license headers.
148      */
149     public void testIt3() throws Exception {
150         final RatCheckMojo mojo = (RatCheckMojo) newRatMojo("it3", "check", true);
151         final File ratTxtFile = getRatTxtFile(mojo);
152         final String dir = getDir(mojo);
153         final String[] expected = { "^Files with unapproved licenses:\\s+\\Q" + dir + "src.apt\\E\\s+", "Notes: 0",
154                 "Binaries: 0", "Archives: 0", "Standards: 2$", "Apache Licensed: 1$", "Generated Documents: 0",
155                 "^1 Unknown Licenses", " AL +\\Q" + dir + "pom.xml\\E$", "\\Q!????? " + dir + "src.apt\\E$",
156                 "^== File: \\Q" + dir + "src.apt\\E$" };
157 
158         ReportConfiguration config = mojo.getConfiguration();
159         assertTrue("should be adding licenses", config.isAddingLicenses());
160 
161         mojo.execute();
162 
163         ensureRatReportIsCorrect(ratTxtFile, expected, TextUtils.EMPTY);
164     }
165 
166     /**
167      * Tests defining licenses in configuration
168      */
169     public void testIt5() throws Exception {
170         final RatCheckMojo mojo = (RatCheckMojo) newRatMojo("it5", "check", true);
171         final File ratTxtFile = getRatTxtFile(mojo);
172         final String[] expected = { "Notes: 0", "Binaries: 0", "Archives: 0", "Standards: 0$", "Apache Licensed: 0$",
173                 "Generated Documents: 0", "^0 Unknown Licenses" };
174 
175         ReportConfiguration config = mojo.getConfiguration();
176         assertFalse("Should not be adding licenses", config.isAddingLicenses());
177         assertFalse("Should not be forcing licenses", config.isAddingLicensesForced());
178         assertTrue("Should be styling report", config.isStyleReport());
179 
180         ReportConfigurationTest.validateDefaultApprovedLicenses(config, 1);
181         assertTrue(config.getApprovedLicenseCategories().contains(ILicenseFamily.makeCategory("YAL")));
182         ReportConfigurationTest.validateDefaultLicenseFamilies(config, "YAL");
183         assertNotNull(LicenseFamilySetFactory.search("YAL", config.getLicenseFamilies(LicenseFilter.all)));
184         ReportConfigurationTest.validateDefaultLicenses(config, "MyLicense", "CpyrT", "RegxT", "SpdxT", "TextT", 
185                 "Not", "All", "Any");
186         assertNotNull(LicenseSetFactory.search("MyLicense", config.getLicenses(LicenseFilter.all)));
187         assertNull("Should not have inputFileFilter", config.getInputFileFilter());
188         mojo.execute();
189 
190         ensureRatReportIsCorrect(ratTxtFile, expected, TextUtils.EMPTY);
191     }
192     
193     /**
194      * Runs a check, which should expose no problems.
195      *
196      * @throws Exception The test failed.
197      */
198     public void testRAT_343() throws Exception {
199         final RatCheckMojo mojo = newRatCheckMojo("RAT-343");
200         final File ratTxtFile = getRatTxtFile(mojo);
201         // POM reports as BSD because it has the BSD string in and that gets found before AL match
202         final String[] expected = { " BSD +\\Q" + getDir(mojo) + "pom.xml\\E", "Notes: 0", "Binaries: 0", "Archives: 0",
203                 "Standards: 1$", "Apache Licensed: 0$", "Generated Documents: 0", "^0 Unknown Licenses" };
204 
205         ReportConfiguration config = mojo.getConfiguration();
206         // validate configuration
207         assertThat(config.isAddingLicenses()).isFalse();
208         assertThat(config.isAddingLicensesForced()).isFalse();
209         assertThat(config.getCopyrightMessage()).isNull();
210         assertThat(config.getInputFileFilter()).isNull();
211         assertThat(config.isStyleReport()).isTrue();
212         assertThat(config.getStyleSheet()).isNotNull().withFailMessage("Stylesheet should not be null");
213         assertThat(config.getDirectoryFilter()).isNotNull().withFailMessage("Directory filter should not be null");
214         assertThat(config.getDirectoryFilter()).isExactlyInstanceOf(NameBasedHiddenFileFilter.class);
215         
216         ReportConfigurationTest.validateDefaultApprovedLicenses(config, 1);
217         ReportConfigurationTest.validateDefaultLicenseFamilies(config, "BSD", "CC BY");
218         ReportConfigurationTest.validateDefaultLicenses(config, "BSD", "CC BY");
219 
220         mojo.execute();
221         ensureRatReportIsCorrect(ratTxtFile, expected, TextUtils.EMPTY);
222     }
223 
224     /**
225      * Tests verifying gitignore parsing
226      */
227     public void testRAT335GitIgnore() throws Exception {
228         final RatCheckMojo mojo = newRatCheckMojo("RAT-335-GitIgnore");
229         final File ratTxtFile = getRatTxtFile(mojo);
230         final String dir = getDir(mojo);
231         final String[] expected = {
232             "Notes: 1",
233             "Binaries: 0",
234             "Archives: 0",
235             "Standards: 5$",
236             "Apache Licensed: 2$",
237             "Generated Documents: 0",
238             "^3 Unknown Licenses",
239             " AL +\\Q" + dir + "pom.xml\\E$",
240             "\\Q!????? " + dir + "dir1/dir1.md\\E$",
241             "\\Q!????? " + dir + "dir2/dir2.txt\\E$",
242             "\\Q!????? " + dir + "dir3/file3.log\\E$",
243             "^== File: \\Q" + dir + "dir1/dir1.md\\E$",
244             "^== File: \\Q" + dir + "dir2/dir2.txt\\E$",
245             "^== File: \\Q" + dir + "dir3/file3.log\\E$"
246         };
247         try {
248             mojo.execute();
249             fail("Expected RatCheckException");
250         } catch (RatCheckException e) {
251             final String msg = e.getMessage();
252             assertTrue("report filename was not contained in '" + msg + "'", msg.contains(ratTxtFile.getName()));
253             assertFalse("no null allowed in '" + msg + "'", (msg.toUpperCase().contains("NULL")));
254             ensureRatReportIsCorrect(ratTxtFile, expected, TextUtils.EMPTY);
255         }
256     }
257 }