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.rat;
20  
21  import static org.assertj.core.api.Assertions.assertThat;
22  import static org.assertj.core.api.Assertions.assertThatThrownBy;
23  import static org.mockito.Mockito.mock;
24  import static org.mockito.Mockito.when;
25  
26  import java.io.BufferedReader;
27  import java.io.ByteArrayOutputStream;
28  import java.io.File;
29  import java.io.IOException;
30  import java.io.InputStream;
31  import java.io.InputStreamReader;
32  import java.io.OutputStream;
33  import java.io.PrintWriter;
34  import java.net.URI;
35  import java.net.URISyntaxException;
36  import java.net.URL;
37  import java.util.ArrayList;
38  import java.util.Arrays;
39  import java.util.List;
40  import java.util.SortedSet;
41  import java.util.function.Function;
42  
43  import org.apache.commons.io.filefilter.DirectoryFileFilter;
44  import org.apache.rat.ReportConfiguration.NoCloseOutputStream;
45  import org.apache.rat.analysis.IHeaderMatcher;
46  import org.apache.rat.config.AddLicenseHeaders;
47  import org.apache.rat.config.exclusion.StandardCollection;
48  import org.apache.rat.configuration.XMLConfigurationReaderTest;
49  import org.apache.rat.document.DocumentName;
50  import org.apache.rat.document.DocumentNameMatcher;
51  import org.apache.rat.license.ILicense;
52  import org.apache.rat.license.ILicenseFamily;
53  import org.apache.rat.license.LicenseSetFactory.LicenseFilter;
54  import org.apache.rat.report.IReportable;
55  import org.apache.rat.testhelpers.TestingLog;
56  import org.apache.rat.testhelpers.TestingLicense;
57  import org.apache.rat.testhelpers.TestingMatcher;
58  import org.apache.rat.utils.DefaultLog;
59  import org.apache.rat.utils.Log.Level;
60  import org.apache.rat.utils.ReportingSet.Options;
61  import org.junit.jupiter.api.AfterEach;
62  import org.junit.jupiter.api.BeforeEach;
63  import org.junit.jupiter.api.Test;
64  import org.junit.jupiter.api.io.TempDir;
65  import org.mockito.Mockito;
66  
67  public class ReportConfigurationTest {
68  
69      private ReportConfiguration underTest;
70      private TestingLog log;
71  
72      @TempDir
73      private File tempDir;
74  
75      @BeforeEach
76      public void setup() {
77          log = new TestingLog();
78          DefaultLog.setInstance(log);
79          underTest = new ReportConfiguration();
80      }
81  
82      @AfterEach
83      public void cleanup() {
84          DefaultLog.setInstance(null);
85      }
86  
87      @Test
88      public void testAddIncludedFilter() {
89          DocumentName dirName = DocumentName.builder(tempDir).build();
90          underTest.addExcludedFilter(DirectoryFileFilter.INSTANCE);
91          DocumentNameMatcher excluder = underTest.getDocumentExcluder(dirName);
92  
93          assertThat(excluder.toString()).isEqualTo("not(DirectoryFileFilter)");
94          assertThat(excluder.matches(DocumentName.builder(tempDir).build())).isFalse();
95  
96          File f = new File(tempDir, "foo.txt");
97          assertThat(excluder.matches(DocumentName.builder(f).build())).isTrue();
98      }
99  
100     @Test
101     public void testAddFamilies() {
102         ILicenseFamily fam1 = ILicenseFamily.builder().setLicenseFamilyCategory("FOO").setLicenseFamilyName("found on overview").build();
103         ILicenseFamily fam2 = ILicenseFamily.builder().setLicenseFamilyCategory("BAR").setLicenseFamilyName("big and round").build();
104         underTest.addFamilies(Arrays.asList(fam1, fam2));
105         SortedSet<String> result = underTest.getLicenseIds(LicenseFilter.ALL);
106         assertThat(result).contains(ILicenseFamily.makeCategory("FOO"));
107         assertThat(result).contains(ILicenseFamily.makeCategory("BAR"));
108         assertThat(result).hasSize(2);
109     }
110 
111     @Test
112     public void testAddApprovedLicenseId() {
113         underTest.addApprovedLicenseId("FOO");
114         SortedSet<String> result = underTest.getLicenseIds(LicenseFilter.APPROVED);
115         assertThat(result).hasSize(1).contains("FOO");
116     }
117     @Test
118     public void testAddAndRemoveApproveLicenseCategories() {
119         List<String> expected = new ArrayList<>();
120         underTest.addLicense(new TestingLicense("Unapproved"));
121 
122         assertThat(underTest.getLicenseCategories(LicenseFilter.APPROVED)).isEmpty();
123 
124         TestingLicense license = new TestingLicense("TheCat");
125         underTest.addLicense(license);
126         underTest.addApprovedLicenseCategory(license.getFamily());
127         expected.add("TheCa");
128         SortedSet<String> result = underTest.getLicenseCategories(LicenseFilter.APPROVED);
129         assertThat(expected).hasSize(result.size()).containsAll(result);
130         SortedSet<ILicenseFamily> families = underTest.getLicenseFamilies(LicenseFilter.APPROVED);
131         assertThat(expected).hasSize(families.size());
132         SortedSet<ILicense> licenses = underTest.getLicenses(LicenseFilter.APPROVED);
133         assertThat(expected).hasSize(licenses.size());
134 
135         underTest.addLicense(new TestingLicense("ACat"));
136         underTest.addApprovedLicenseCategory("ACat");
137         expected.add("ACat ");
138         result = underTest.getLicenseCategories(LicenseFilter.APPROVED);
139         assertThat(expected).hasSize(result.size()).containsAll(result);
140         families = underTest.getLicenseFamilies(LicenseFilter.APPROVED);
141         assertThat(expected).hasSize(families.size());
142         licenses = underTest.getLicenses(LicenseFilter.APPROVED);
143         assertThat(expected).hasSize(licenses.size());
144 
145         String[] cats = {"Spot ", "Felix"};
146         underTest.addLicense(new TestingLicense("Spot"));
147         underTest.addLicense(new TestingLicense("Felix"));
148         underTest.addApprovedLicenseCategories(Arrays.asList(cats));
149         expected.addAll(Arrays.asList(cats));
150         result = underTest.getLicenseCategories(LicenseFilter.APPROVED);
151         assertThat(expected).hasSize(result.size()).containsAll(result);
152         families = underTest.getLicenseFamilies(LicenseFilter.APPROVED);
153         assertThat(expected).hasSize(families.size());
154         licenses = underTest.getLicenses(LicenseFilter.APPROVED);
155         assertThat(expected).hasSize(licenses.size());
156 
157         underTest.removeApprovedLicenseCategory("Spot ");
158         expected.remove("Spot ");
159         result = underTest.getLicenseCategories(LicenseFilter.APPROVED);
160         assertThat(expected).hasSize(result.size()).containsAll(result);
161         families = underTest.getLicenseFamilies(LicenseFilter.APPROVED);
162         assertThat(expected).hasSize(families.size());
163         licenses = underTest.getLicenses(LicenseFilter.APPROVED);
164         assertThat(expected).hasSize(licenses.size());
165 
166         cats[0] = "TheCa";
167         underTest.removeApprovedLicenseCategories(Arrays.asList(cats));
168         expected.removeAll(Arrays.asList(cats));
169         result = underTest.getLicenseCategories(LicenseFilter.APPROVED);
170         assertThat(expected).hasSize(result.size()).containsAll(result);
171         families = underTest.getLicenseFamilies(LicenseFilter.APPROVED);
172         assertThat(expected).hasSize(families.size());
173         licenses = underTest.getLicenses(LicenseFilter.APPROVED);
174         assertThat(expected).hasSize(licenses.size());
175     }
176 
177     @Test
178     public void testRemoveBeforeAddApproveLicenseCategories() {
179         underTest.addLicense( new TestingLicense("TheCat"));
180         assertThat(underTest.getLicenseCategories(LicenseFilter.APPROVED)).isEmpty();
181         assertThat(underTest.getLicenseFamilies(LicenseFilter.APPROVED)).isEmpty();
182         assertThat(underTest.getLicenses(LicenseFilter.APPROVED)).isEmpty();
183         
184         underTest.removeApprovedLicenseCategory("TheCat");
185         assertThat(underTest.getLicenseCategories(LicenseFilter.APPROVED)).isEmpty();
186         assertThat(underTest.getLicenseFamilies(LicenseFilter.APPROVED)).isEmpty();
187         assertThat(underTest.getLicenses(LicenseFilter.APPROVED)).isEmpty();
188 
189         underTest.addApprovedLicenseCategory("TheCat");
190         assertThat(underTest.getLicenseCategories(LicenseFilter.APPROVED)).isEmpty();
191         assertThat(underTest.getLicenseFamilies(LicenseFilter.APPROVED)).isEmpty();
192         assertThat(underTest.getLicenses(LicenseFilter.APPROVED)).isEmpty();
193     }
194 
195     @Test
196     public void testAddAndRemoveApproveLicenseIds() {
197         List<String> expected = new ArrayList<>();
198         underTest.addLicense(new TestingLicense("Unapproved"));
199 
200         assertThat(underTest.getLicenseIds(LicenseFilter.APPROVED)).isEmpty();
201 
202         TestingLicense license = new TestingLicense("TheCat");
203         underTest.addLicense(license);
204         underTest.addApprovedLicenseId(license.getId());
205         expected.add("TheCat");
206         SortedSet<String> result = underTest.getLicenseIds(LicenseFilter.APPROVED);
207         assertThat(result).hasSize(expected.size()).containsAll(expected);
208         SortedSet<ILicense> licenses = underTest.getLicenses(LicenseFilter.APPROVED);
209         assertThat(licenses).hasSize(expected.size());
210 
211         underTest.addLicense(new TestingLicense("ACat"));
212         underTest.addApprovedLicenseId("ACat");
213         expected.add("ACat");
214         result = underTest.getLicenseIds(LicenseFilter.APPROVED);
215         assertThat(result).hasSize(expected.size()).containsAll(expected);
216         licenses = underTest.getLicenses(LicenseFilter.APPROVED);
217         assertThat(licenses).hasSize(expected.size());
218 
219         String[] cats = {"Spot", "Felix"};
220         underTest.addLicense(new TestingLicense("Spot"));
221         underTest.addLicense(new TestingLicense("Felix"));
222         underTest.addApprovedLicenseIds(Arrays.asList(cats));
223         expected.addAll(Arrays.asList(cats));
224         result = underTest.getLicenseIds(LicenseFilter.APPROVED);
225         assertThat(result).hasSize(expected.size()).containsAll(expected);
226         licenses = underTest.getLicenses(LicenseFilter.APPROVED);
227         assertThat(licenses).hasSize(expected.size());
228 
229         underTest.removeApprovedLicenseId("Spot");
230         expected.remove("Spot");
231         result = underTest.getLicenseIds(LicenseFilter.APPROVED);
232         assertThat(result).hasSize(expected.size()).containsAll(expected);
233         licenses = underTest.getLicenses(LicenseFilter.APPROVED);
234         assertThat(licenses).hasSize(expected.size());
235 
236         cats[0] = "TheCat";
237         underTest.removeApprovedLicenseIds(Arrays.asList(cats));
238         expected.removeAll(Arrays.asList(cats));
239         result = underTest.getLicenseIds(LicenseFilter.APPROVED);
240         assertThat(result).hasSize(expected.size()).containsAll(expected);
241         licenses = underTest.getLicenses(LicenseFilter.APPROVED);
242         assertThat(licenses).hasSize(expected.size());
243     }
244 
245     /**
246      * Sets up underTest to have a set of licenses named after
247      * <a href="https://en.wikipedia.org/wiki/List_of_fictional_cats_in_comics"></a>cartoon cats</a>
248      * all in the license family 'catz'
249      */
250     private void addCatz() {
251         underTest.addLicense(new TestingLicense("catz", "Garfield"));
252         underTest.addLicense(new TestingLicense("catz", "Felix"));
253         underTest.addLicense(new TestingLicense("catz", "Arlene"));
254         underTest.addLicense(new TestingLicense("catz", "Nermal"));
255         underTest.addLicense(new TestingLicense("catz", "Hobbes"));
256         underTest.addLicense(new TestingLicense("catz", "Heathcliff"));
257         underTest.addLicense(new TestingLicense("catz", "Catbert"));
258     }
259 
260     /**
261      * Sets up underTest to have a set of licenses named after
262      * <a href="https://en.wikipedia.org/wiki/List_of_fictional_dogs_in_comics"></a>cartoon cats</a>cartoon dogs</a>
263      * all in the license family 'dogz'
264      */
265     private void addDogz() {
266         underTest.addLicense(new TestingLicense("dogz", "Odie"));
267         underTest.addLicense(new TestingLicense("dogz", "Snoopy"));
268         underTest.addLicense(new TestingLicense("dogz", "Scamp"));
269         underTest.addLicense(new TestingLicense("dogz", "Marmaduke"));
270         underTest.addLicense(new TestingLicense("dogz", "Rosebud"));
271         underTest.addLicense(new TestingLicense("dogz", "Spike"));
272         underTest.addLicense(new TestingLicense("dogz", "Dogbert"));
273     }
274 
275     @Test
276     public void removeFamilyAddLicense() {
277         addCatz();
278         underTest.addApprovedLicenseCategory("catz");
279         underTest.removeApprovedLicenseCategory("catz");
280         assertThat(underTest.getLicenses(LicenseFilter.APPROVED)).isEmpty();
281         underTest.addApprovedLicenseId("Garfield");
282         assertThat(underTest.getLicenses(LicenseFilter.APPROVED).size()).isEqualTo(1);
283     }
284 
285     @Test
286     public void addFamilyRemoveLicense() {
287         addCatz();
288         underTest.addApprovedLicenseCategory("catz");
289         assertThat(underTest.getLicenses(LicenseFilter.APPROVED).size()).isEqualTo(7);
290         underTest.removeApprovedLicenseId("Catbert");
291         assertThat(underTest.getLicenses(LicenseFilter.APPROVED).size()).isEqualTo(6);
292     }
293 
294     @Test
295     public void removeFamilyRemoveLicense() {
296         addCatz();
297         addDogz();
298         underTest.addApprovedLicenseCategory("catz");
299         underTest.addApprovedLicenseCategory("dogz");
300         assertThat(underTest.getLicenses(LicenseFilter.APPROVED).size()).isEqualTo(14);
301         underTest.removeApprovedLicenseCategory("dogz");
302         underTest.removeApprovedLicenseId("Catbert");
303         assertThat(underTest.getLicenses(LicenseFilter.APPROVED).size()).isEqualTo(6);
304     }
305 
306     @Test
307     public void addFamilyAddLicense() {
308         addCatz();
309         addDogz();
310         underTest.addApprovedLicenseCategory("catz");
311         assertThat(underTest.getLicenses(LicenseFilter.APPROVED).size()).isEqualTo(7);
312         underTest.addApprovedLicenseId("Dogbert");
313         assertThat(underTest.getLicenses(LicenseFilter.APPROVED).size()).isEqualTo(8);
314     }
315 
316     @Test
317     public void testRemoveBeforeAddApproveLicenseIds() {
318         underTest.addLicense( new TestingLicense("TheCat"));
319         assertThat(underTest.getLicenseIds(LicenseFilter.APPROVED)).isEmpty();
320         assertThat(underTest.getLicenses(LicenseFilter.APPROVED)).isEmpty();
321 
322         underTest.removeApprovedLicenseId("TheCat");
323         assertThat(underTest.getLicenseIds(LicenseFilter.APPROVED)).isEmpty();
324         assertThat(underTest.getLicenses(LicenseFilter.APPROVED)).isEmpty();
325 
326         underTest.addApprovedLicenseId("TheCat");
327         assertThat(underTest.getLicenseIds(LicenseFilter.APPROVED)).isEmpty();
328         assertThat(underTest.getLicenses(LicenseFilter.APPROVED)).isEmpty();
329     }
330 
331     private ILicense testingLicense(String category, String name) {
332         ILicenseFamily family = ILicenseFamily.builder().setLicenseFamilyCategory(category).setLicenseFamilyName(name)
333                 .build();
334         return new TestingLicense( category, new TestingMatcher(), family );
335     }
336 
337     @Test
338     public void testAddLicense() {
339         List<ILicense> expected = new ArrayList<>();
340         assertThat(underTest.getLicenses(LicenseFilter.ALL)).isEmpty();
341 
342         ILicense lic1 = testingLicense("TheCat", "TheName");
343         expected.add(lic1);
344         underTest.addLicense(lic1);
345         SortedSet<ILicense> result = underTest.getLicenses(LicenseFilter.ALL);
346         assertThat(expected).hasSize(result.size()).containsAll(result);
347 
348         ILicense[] lics = { testingLicense("Spot", "Data's cat"), testingLicense("Felix", "Cartoon cat") };
349         expected.addAll(Arrays.asList(lics));
350         underTest.addLicenses(Arrays.asList(lics));
351         result = underTest.getLicenses(LicenseFilter.ALL);
352         assertThat(expected).hasSize(result.size()).containsAll(result);
353     }
354 
355     @Test
356     public void copyrightMessageTest() {
357         assertThat(underTest.getCopyrightMessage()).isNull();
358         underTest.setCopyrightMessage("This is the message");
359         assertThat(underTest.getCopyrightMessage()).isEqualTo("This is the message");
360     }
361 
362     DocumentName mkDocumentName(File f) {
363         return DocumentName.builder(f).setBaseName(tempDir).build();
364     }
365     @Test
366     public void exclusionTest() {
367         DocumentName baseDir = DocumentName.builder(tempDir).build();
368         DocumentName foo = mkDocumentName(new File(tempDir,"foo"));
369         assertThat(underTest.getDocumentExcluder(baseDir).matches(foo)).isTrue();
370 
371         underTest.setFrom(Defaults.builder().build());
372 
373         File f = new File(tempDir, ".hiddenDir");
374         assertThat(f.mkdir()).as(() -> "Could not create directory " + f).isTrue();
375         DocumentName hiddenDir = mkDocumentName(new File(tempDir, ".hiddenDir"));
376         DocumentNameMatcher excluder = underTest.getDocumentExcluder(baseDir);
377         assertThat(excluder.matches(hiddenDir)).isFalse();
378 
379         underTest.addIncludedCollection(StandardCollection.HIDDEN_DIR);
380         assertThat(underTest.getDocumentExcluder(baseDir).matches(hiddenDir)).isTrue();
381 
382         underTest.addExcludedCollection(StandardCollection.HIDDEN_DIR);
383         assertThat(underTest.getDocumentExcluder(baseDir).matches(hiddenDir)).isTrue();
384 
385         underTest.addExcludedFilter(DirectoryFileFilter.DIRECTORY);
386 
387         File file = new File(tempDir, "newDir");
388         assertThat(file.mkdirs()).as(() -> "Could not create directory " + file).isTrue();
389         assertThat(underTest.getDocumentExcluder(baseDir).matches(mkDocumentName(file))).isFalse();
390     }
391 
392     @Test
393     public void archiveProcessingTest() {
394         assertThat(underTest.getArchiveProcessing()).isEqualTo(ReportConfiguration.Processing.NOTIFICATION);
395 
396         underTest.setFrom(Defaults.builder().build());
397         assertThat(underTest.getArchiveProcessing()).isEqualTo(ReportConfiguration.Processing.NOTIFICATION);
398 
399         underTest.setArchiveProcessing(ReportConfiguration.Processing.ABSENCE);
400         assertThat(underTest.getArchiveProcessing()).isEqualTo(ReportConfiguration.Processing.ABSENCE);
401 
402         underTest.setArchiveProcessing(ReportConfiguration.Processing.PRESENCE);
403         assertThat(underTest.getArchiveProcessing()).isEqualTo(ReportConfiguration.Processing.PRESENCE);
404 
405         underTest.setArchiveProcessing(null);
406         assertThat(underTest.getArchiveProcessing()).isEqualTo(ReportConfiguration.Processing.NOTIFICATION);
407     }
408 
409     @Test
410     public void licenseFamiliesTest() {
411         assertThat(underTest.getLicenseFamilies(LicenseFilter.ALL)).isEmpty();
412         assertThat(underTest.getLicenseFamilies(LicenseFilter.APPROVED)).isEmpty();
413         assertThat(underTest.getLicenseFamilies(LicenseFilter.NONE)).isEmpty();
414 
415         ILicense[] lics = { testingLicense("TheCat", "TheName"), testingLicense("Spot", "Data's cat"),
416                 testingLicense("Felix", "Cartoon cat") };
417         underTest.addLicenses(Arrays.asList(lics));
418 
419         assertThat(underTest.getLicenseFamilies(LicenseFilter.ALL)).hasSize(lics.length);
420         assertThat(underTest.getLicenseFamilies(LicenseFilter.APPROVED)).isEmpty();
421         assertThat(underTest.getLicenseFamilies(LicenseFilter.NONE)).isEmpty();
422 
423         underTest.addApprovedLicenseCategory(lics[1].getLicenseFamily());
424         assertThat(underTest.getLicenseFamilies(LicenseFilter.ALL)).hasSize(lics.length);
425         SortedSet<ILicenseFamily> result = underTest.getLicenseFamilies(LicenseFilter.APPROVED);
426         assertThat(result).hasSize(1);
427         assertThat(result.first()).isEqualTo(lics[1].getLicenseFamily());
428         assertThat(underTest.getLicenseFamilies(LicenseFilter.NONE)).isEmpty();
429     }
430 
431     @Test
432     public void licensesTest() {
433         assertThat(underTest.getLicenses(LicenseFilter.ALL)).isEmpty();
434         assertThat(underTest.getLicenses(LicenseFilter.APPROVED)).isEmpty();
435         assertThat(underTest.getLicenses(LicenseFilter.NONE)).isEmpty();
436 
437         ILicense[] lics = { testingLicense("TheCat", "TheName"), testingLicense("Spot", "Data's cat"),
438                 testingLicense("Felix", "Cartoon cat") };
439         underTest.addLicenses(Arrays.asList(lics));
440 
441         assertThat(underTest.getLicenses(LicenseFilter.ALL)).hasSize(lics.length);
442         assertThat(underTest.getLicenses(LicenseFilter.APPROVED)).isEmpty();
443         assertThat(underTest.getLicenses(LicenseFilter.NONE)).isEmpty();
444 
445         underTest.addApprovedLicenseCategory(lics[1].getLicenseFamily());
446         assertThat(underTest.getLicenses(LicenseFilter.ALL)).hasSize(lics.length);
447         SortedSet<ILicense> result = underTest.getLicenses(LicenseFilter.APPROVED);
448         assertThat(result).hasSize(1);
449         assertThat(result.first()).isEqualTo(lics[1]);
450         assertThat(underTest.getLicenseFamilies(LicenseFilter.NONE)).isEmpty();
451     }
452 
453     @Test
454     public void outputTest() throws IOException {
455         assertThat(underTest.getOutput().get()).isExactlyInstanceOf(NoCloseOutputStream.class);
456         assertThat(underTest.getWriter()).isNotNull();
457 
458         ByteArrayOutputStream stream = new ByteArrayOutputStream();
459         underTest.setOut(() -> stream);
460         assertThat(underTest.getOutput().get()).isEqualTo(stream);
461         PrintWriter writer = underTest.getWriter().get();
462         assertThat(writer).isNotNull();
463         writer.write('a');
464         writer.flush();
465         assertThat(stream.toByteArray()[0]).isEqualTo((byte) 'a');
466     }
467 
468     @Test
469     public void reportableTest() {
470         assertThat(underTest.hasSource()).isFalse();
471         IReportable reportable = mock(IReportable.class);
472         underTest.addSource(reportable);
473         assertThat(underTest.hasSource()).isTrue();
474         assertThatThrownBy(() -> underTest.addSource((IReportable)null)).isExactlyInstanceOf(ConfigurationException.class)
475                 .hasMessageContaining("Reportable may not be null.");
476     }
477 
478     @Test
479     public void stylesheetTest() throws IOException, URISyntaxException {
480         URL url = this.getClass().getResource("ReportConfigurationTestFile");
481         assertThat(url).isNotNull();
482 
483         assertThat(underTest.getStyleSheet()).isNull();
484         InputStream stream = mock(InputStream.class);
485         underTest.setStyleSheet(() -> stream);
486         assertThat(underTest.getStyleSheet().get()).isEqualTo(stream);
487 
488         File file = mock(File.class);
489         URI asUri = url.toURI();
490         assertThat(asUri).isNotNull();
491         when(file.toURI()).thenReturn(asUri);
492         underTest.setStyleSheet(file);
493         BufferedReader d = new BufferedReader(new InputStreamReader(underTest.getStyleSheet().get()));
494         assertThat(d.readLine()).isEqualTo("/*");
495         assertThat(d.readLine()).isEqualTo(" * Licensed to the Apache Software Foundation (ASF) under one   *");
496     }
497 
498     @Test
499     public void testFlags() {
500         assertThat(underTest.isAddingLicenses()).isFalse();
501         assertThat(underTest.isAddingLicensesForced()).isFalse();
502 
503         underTest.setAddLicenseHeaders(AddLicenseHeaders.TRUE);
504         assertThat(underTest.isAddingLicenses()).isTrue();
505         assertThat(underTest.isAddingLicensesForced()).isFalse();
506 
507         underTest.setAddLicenseHeaders(AddLicenseHeaders.FALSE);
508         assertThat(underTest.isAddingLicenses()).isFalse();
509         assertThat(underTest.isAddingLicensesForced()).isFalse();
510 
511         underTest.setAddLicenseHeaders(AddLicenseHeaders.FORCED);
512         assertThat(underTest.isAddingLicenses()).isTrue();
513         assertThat(underTest.isAddingLicensesForced()).isTrue();
514     }
515 
516     @Test
517     public void testValidate() {
518         final StringBuilder sb = new StringBuilder();
519         String msg = "At least one source must be specified";
520         assertThatThrownBy(() -> underTest.validate(sb::append)).isExactlyInstanceOf(ConfigurationException.class)
521                 .hasMessageContaining(msg);
522         assertThat(sb.toString()).isEqualTo(msg);
523 
524 
525         sb.setLength(0);
526         msg = "You must specify at least one license";
527         underTest.addSource(mock(IReportable.class));
528 
529         assertThatThrownBy(() -> underTest.validate(sb::append)).isExactlyInstanceOf(ConfigurationException.class)
530                 .hasMessageContaining(msg);
531         assertThat(sb.toString()).isEqualTo(msg);
532 
533         sb.setLength(0);
534         underTest.addLicense(testingLicense("valid", "Validation testing license"));
535         underTest.validate(sb::append);
536         assertThat(sb.length()).isEqualTo(0);
537     }
538     
539     @Test
540     public void testSetOut() throws IOException {
541         ReportConfiguration config = new ReportConfiguration();
542         try (OutputStreamInterceptor osi = new OutputStreamInterceptor()) {
543             config.setOut(() -> osi);
544             assertThat(osi.closeCount).isEqualTo(0);
545             try (OutputStream os = config.getOutput().get()) {
546                 assertThat(os).isNotNull();
547                 assertThat(osi.closeCount).isEqualTo(0);
548             }
549             assertThat(osi.closeCount).isEqualTo(1);
550             try (OutputStream os = config.getOutput().get()) {
551                 assertThat(os).isNotNull();
552                 assertThat(osi.closeCount).isEqualTo(1);
553             }
554             assertThat(osi.closeCount).isEqualTo(2);
555         }
556     }
557     
558     @Test
559     public void logFamilyCollisionTest() {
560         // setup
561         underTest.addFamily(ILicenseFamily.builder().setLicenseFamilyCategory("CAT").setLicenseFamilyName("name"));
562         assertThat(log.getCaptured()).doesNotContain("CAT");
563        
564         // verify default collision logs WARNING
565         underTest.addFamily(ILicenseFamily.builder().setLicenseFamilyCategory("CAT").setLicenseFamilyName("name2"));
566         assertThat(log.getCaptured().contains("WARN")).as("default value not WARN").isTrue();
567         assertThat(log.getCaptured().contains("CAT")).as("'CAT' not found").isTrue();
568         
569         // verify level setting works.
570         for (Level l : Level.values()) {
571           log.clear();
572           underTest.logFamilyCollisions(l);
573           underTest.addFamily(ILicenseFamily.builder().setLicenseFamilyCategory("CAT").setLicenseFamilyName("name2"));
574           assertThat(log.getCaptured().contains("CAT")).as("'CAT' not found").isTrue();
575           assertThat(log.getCaptured().contains(l.name())).as("logging not set to "+l).isTrue();
576         }
577     }
578     
579     @Test
580     public void familyDuplicateOptionsTest() {
581         underTest.addFamily(ILicenseFamily.builder().setLicenseFamilyCategory("CAT").setLicenseFamilyName("name"));
582         assertThat(log.getCaptured()).doesNotContain("CAT");
583         
584         // verify default second setting ignores change
585         underTest.addFamily(ILicenseFamily.builder().setLicenseFamilyCategory("CAT").setLicenseFamilyName("name2"));
586         assertThat(log.getCaptured()).contains("CAT");
587         assertThat(underTest.getLicenseFamilies(LicenseFilter.ALL).stream()
588                 .filter(s -> s.getFamilyCategory().equals("CAT  ")).map(ILicenseFamily::getFamilyName).findFirst())
589                 .contains("name");
590         
591         underTest.familyDuplicateOption(Options.OVERWRITE);
592         // verify second setting ignores change
593         underTest.addFamily(ILicenseFamily.builder().setLicenseFamilyCategory("CAT").setLicenseFamilyName("name2"));
594         assertThat(log.getCaptured()).contains("CAT");
595         assertThat(underTest.getLicenseFamilies(LicenseFilter.ALL).stream()
596                 .filter(s -> s.getFamilyCategory().equals("CAT  ")).map(ILicenseFamily::getFamilyName).findFirst())
597                 .contains("name2");
598 
599         // verify fail throws exception
600         underTest.familyDuplicateOption(Options.FAIL);
601         assertThatThrownBy(()->underTest.addFamily(ILicenseFamily.builder().setLicenseFamilyCategory("CAT").setLicenseFamilyName("name2")))
602                 .isExactlyInstanceOf(IllegalArgumentException.class);
603 
604         underTest.familyDuplicateOption(Options.IGNORE);
605     }
606 
607     @Test
608     public void logLicenseCollisionTest() {
609         // setup
610         ILicenseFamily family = ILicenseFamily.builder().setLicenseFamilyCategory("CAT").setLicenseFamilyName("family name").build();
611         IHeaderMatcher matcher = Mockito.mock(IHeaderMatcher.class);
612         when(matcher.getId()).thenReturn("Macher ID");
613         underTest.addFamily(family);
614         underTest.addLicense(ILicense.builder().setId("ID").setName("license name").setFamily(family.getFamilyCategory())
615                 .setMatcher( matcher )
616                 .setLicenseFamilies(underTest.getLicenseFamilies(LicenseFilter.ALL))
617                 .build());
618         
619         // verify default collision logs WARN
620         underTest.addLicense(ILicense.builder().setId("ID").setName("license name2").setFamily(family.getFamilyCategory())
621                 .setMatcher( matcher ).setLicenseFamilies(underTest.getLicenseFamilies(LicenseFilter.ALL))
622                 .build());
623         assertThat(log.getCaptured()).contains("WARN");
624         
625         log.clear();
626         underTest.logLicenseCollisions(Level.ERROR);
627         
628         // verify second setting changes logs issue
629         underTest.addLicense(ILicense.builder().setId("ID").setName("license name2").setFamily(family.getFamilyCategory())
630                 .setMatcher( matcher ).setLicenseFamilies(underTest.getLicenseFamilies(LicenseFilter.ALL))
631                 .build());
632         assertThat(log.getCaptured()).contains("ERROR");
633     }
634     
635     @Test
636     public void licenseDuplicateOptionsTest() {
637         // setup
638         ILicenseFamily family = ILicenseFamily.builder().setLicenseFamilyCategory("CAT").setLicenseFamilyName("family name").build();
639         IHeaderMatcher matcher = Mockito.mock(IHeaderMatcher.class);
640         when(matcher.getId()).thenReturn("Macher ID");
641         underTest.addFamily(family);
642         Function<String,ILicense> makeLicense = s -> ILicense.builder().setId("ID").setName(s).setFamily(family.getFamilyCategory())
643                 .setMatcher( matcher ).setLicenseFamilies(underTest.getLicenseFamilies(LicenseFilter.ALL))
644                 .build();
645                 
646         underTest.addLicense(makeLicense.apply("license name"));
647         
648         // verify default second setting ignores change
649         underTest.addLicense(makeLicense.apply("license name2"));
650         assertThat(log.getCaptured()).contains("WARN");
651         assertThat(underTest.getLicenses(LicenseFilter.ALL).stream().map(ILicense::getName).findFirst())
652                 .contains("license name");
653         
654         underTest.licenseDuplicateOption(Options.OVERWRITE);
655         underTest.addLicense(makeLicense.apply("license name2"));
656         assertThat(underTest.getLicenses(LicenseFilter.ALL).stream().map(ILicense::getName).findFirst())
657                 .contains("license name2");
658 
659         // verify fail throws exception
660         underTest.licenseDuplicateOption(Options.FAIL);
661         assertThatThrownBy(()-> underTest.addLicense(makeLicense.apply("another name")))
662                 .isExactlyInstanceOf(IllegalArgumentException.class);
663     }
664 
665     /**
666      * Validates that the configuration contains the default approved licenses.
667      * @param config The configuration to test.
668      */
669     public static void validateDefaultApprovedLicenses(ReportConfiguration config) {
670         validateDefaultApprovedLicenses(config, 0);
671     }
672     
673     /**
674      * Validates that the configuration contains the default approved licenses.
675      * @param config The configuration to test.
676      */
677     public static void validateDefaultApprovedLicenses(ReportConfiguration config, int additionalIdCount) {
678         assertThat(config.getLicenseCategories(LicenseFilter.APPROVED)).hasSize(XMLConfigurationReaderTest.APPROVED_IDS.length + additionalIdCount);
679         for (String s : XMLConfigurationReaderTest.APPROVED_IDS) {
680             assertThat(config.getLicenseCategories(LicenseFilter.APPROVED)).contains(ILicenseFamily.makeCategory(s));
681         }
682     }
683 
684     /**
685      * Validates that the configuration contains the default license families.
686      * @param config the configuration to test.
687      */
688     public static void validateDefaultLicenseFamilies(ReportConfiguration config, String...additionalIds) {
689         assertThat(config.getLicenseFamilies(LicenseFilter.ALL)).hasSize(XMLConfigurationReaderTest.EXPECTED_IDS.length + additionalIds.length);
690         List<String> expected = new ArrayList<>();
691         expected.addAll(Arrays.asList(XMLConfigurationReaderTest.EXPECTED_IDS));
692         expected.addAll(Arrays.asList(additionalIds));
693         for (ILicenseFamily family : config.getLicenseFamilies(LicenseFilter.ALL)) {
694             assertThat(expected).contains(family.getFamilyCategory().trim());
695         }
696     }
697 
698     /**
699      * Validates that the configuration contains the default licenses.
700      * @param config the configuration to test.
701      */
702     public static void validateDefaultLicenses(ReportConfiguration config, String...additionalLicenses) {
703         assertThat(config.getLicenses(LicenseFilter.ALL)).hasSize(XMLConfigurationReaderTest.EXPECTED_LICENSES.length + additionalLicenses.length);
704         List<String> expected = new ArrayList<>();
705         expected.addAll(Arrays.asList(XMLConfigurationReaderTest.EXPECTED_LICENSES));
706         expected.addAll(Arrays.asList(additionalLicenses));
707         for (ILicense license : config.getLicenses(LicenseFilter.ALL)) {
708             assertThat(expected).contains(license.getId());
709         }
710     }
711     
712     /**
713      * Validates that the configuration matches the default.
714      * @param config The configuration to test.
715      */
716     public static void validateDefault(ReportConfiguration config) {
717         assertThat(config.isAddingLicenses()).isFalse();
718         assertThat(config.isAddingLicensesForced()).isFalse();
719         assertThat(config.getCopyrightMessage()).isNull();
720         assertThat(config.getStyleSheet()).withFailMessage("Stylesheet should not be null").isNotNull();
721 
722         validateDefaultApprovedLicenses(config);
723         validateDefaultLicenseFamilies(config);
724         validateDefaultLicenses(config);
725     }
726 
727     /**
728      * A class to act as an output stream and count the number of close operations.
729      */
730     static class OutputStreamInterceptor extends OutputStream {
731         int closeCount = 0;
732 
733         @Override
734         public void write(int arg0) {
735             throw new UnsupportedOperationException();
736         }
737         
738         @Override
739         public void close() {
740             ++closeCount;
741         }
742     }
743 }