diff --git a/apache-rat-core/src/main/java/org/apache/rat/OptionCollection.java b/apache-rat-core/src/main/java/org/apache/rat/OptionCollection.java index 39bf463ca..23486194f 100644 --- a/apache-rat-core/src/main/java/org/apache/rat/OptionCollection.java +++ b/apache-rat-core/src/main/java/org/apache/rat/OptionCollection.java @@ -23,10 +23,7 @@ import java.io.PrintWriter; import java.io.Serializable; import java.util.Arrays; -import java.util.Collections; import java.util.Comparator; -import java.util.Map; -import java.util.TreeMap; import java.util.function.Consumer; import java.util.function.Supplier; import java.util.stream.Collectors; @@ -88,11 +85,32 @@ private static String asString(final Object[] args) { * @param helpCmd the help command to run when necessary. * @return a ReportConfiguration or {@code null} if Help was printed. * @throws IOException on error. + * @throws ParseException on option parsing error. */ - public static ReportConfiguration parseCommands(final File workingDirectory, final String[] args, final Consumer helpCmd) throws IOException { + public static ReportConfiguration parseCommands(final File workingDirectory, final String[] args, final Consumer helpCmd) + throws IOException, ParseException { return parseCommands(workingDirectory, args, helpCmd, false); } + /** + * Parse the options into the command line. + * @param opts the option definitions. + * @param args the argument to apply the definitions to. + * @return the CommandLine + * @throws ParseException on option parsing error. + */ + //@VisibleForTesting + static CommandLine parseCommandLine(final Options opts, final String[] args) throws ParseException { + try { + return DefaultParser.builder().setDeprecatedHandler(DeprecationReporter.getLogReporter()) + .setAllowPartialMatching(true).build().parse(opts, args); + } catch (ParseException e) { + DefaultLog.getInstance().error(e.getMessage()); + DefaultLog.getInstance().error("Please use the \"--help\" option to see a list of valid commands and options.", e); + throw e; + } + } + /** * Parses the standard options to create a ReportConfiguration. * @@ -102,22 +120,14 @@ public static ReportConfiguration parseCommands(final File workingDirectory, fin * @param noArgs If {@code true} then the commands do not need extra arguments. * @return a ReportConfiguration or {@code null} if Help was printed. * @throws IOException on error. + * @throws ParseException on option parsing error. */ public static ReportConfiguration parseCommands(final File workingDirectory, final String[] args, - final Consumer helpCmd, final boolean noArgs) throws IOException { + final Consumer helpCmd, final boolean noArgs) throws IOException, ParseException { Options opts = buildOptions(); - CommandLine commandLine; - try { - commandLine = DefaultParser.builder().setDeprecatedHandler(DeprecationReporter.getLogReporter()) - .setAllowPartialMatching(true).build().parse(opts, args); - } catch (ParseException e) { - DefaultLog.getInstance().error(e.getMessage()); - DefaultLog.getInstance().error("Please use the \"--help\" option to see a list of valid commands and options.", e); - System.exit(1); - return null; // dummy return (won't be reached) to avoid Eclipse complaint about possible NPE - // for "commandLine" - } + CommandLine commandLine = parseCommandLine(buildOptions(), args); + Arg.processLogLevel(commandLine); @@ -157,13 +167,6 @@ static ReportConfiguration createConfiguration(final ArgumentContext argumentCon argumentContext.processArgs(); final ReportConfiguration configuration = argumentContext.getConfiguration(); final CommandLine commandLine = argumentContext.getCommandLine(); - if (Arg.DIR.isSelected()) { - try { - configuration.addSource(getReportable(commandLine.getParsedOptionValue(Arg.DIR.getSelected()), configuration)); - } catch (ParseException e) { - throw new ConfigurationException("Unable to set parse " + Arg.DIR.getSelected(), e); - } - } for (String s : commandLine.getArgs()) { IReportable reportable = getReportable(new File(s), configuration); if (reportable != null) { diff --git a/apache-rat-core/src/main/java/org/apache/rat/Report.java b/apache-rat-core/src/main/java/org/apache/rat/Report.java index 5f5f4cb35..33296ea67 100644 --- a/apache-rat-core/src/main/java/org/apache/rat/Report.java +++ b/apache-rat-core/src/main/java/org/apache/rat/Report.java @@ -21,6 +21,7 @@ import java.io.File; import org.apache.commons.cli.Options; +import org.apache.commons.cli.ParseException; import org.apache.rat.document.RatDocumentAnalysisException; import org.apache.rat.help.Help; import org.apache.rat.utils.DefaultLog; @@ -48,19 +49,24 @@ public static void main(final String[] args) throws Exception { System.exit(0); } - ReportConfiguration configuration = OptionCollection.parseCommands(new File("."), args, Report::printUsage); - if (configuration != null) { - configuration.validate(DefaultLog.getInstance()::error); - Reporter reporter = new Reporter(configuration); - reporter.output(); - reporter.writeSummary(DefaultLog.getInstance().asWriter()); + try { + ReportConfiguration configuration = OptionCollection.parseCommands(new File("."), args, Report::printUsage); + if (configuration != null) { + configuration.validate(DefaultLog.getInstance()::error); + Reporter reporter = new Reporter(configuration); + reporter.output(); + reporter.writeSummary(DefaultLog.getInstance().asWriter()); - if (configuration.getClaimValidator().hasErrors()) { - configuration.getClaimValidator().logIssues(reporter.getClaimsStatistic()); - throw new RatDocumentAnalysisException(format("Issues with %s", - String.join(", ", - configuration.getClaimValidator().listIssues(reporter.getClaimsStatistic())))); + if (configuration.getClaimValidator().hasErrors()) { + configuration.getClaimValidator().logIssues(reporter.getClaimsStatistic()); + throw new RatDocumentAnalysisException(format("Issues with %s", + String.join(", ", + configuration.getClaimValidator().listIssues(reporter.getClaimsStatistic())))); + } } + } catch (ParseException e) { + DefaultLog.getInstance().error("Error parsing command line options: " + e.getMessage(), e); + System.exit(1); } } diff --git a/apache-rat-core/src/test/java/org/apache/rat/OptionCollectionTest.java b/apache-rat-core/src/test/java/org/apache/rat/OptionCollectionTest.java index 87f7cd967..c5d947760 100644 --- a/apache-rat-core/src/test/java/org/apache/rat/OptionCollectionTest.java +++ b/apache-rat-core/src/test/java/org/apache/rat/OptionCollectionTest.java @@ -30,7 +30,9 @@ import java.util.TreeMap; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.DefaultParser; +import org.apache.commons.cli.DeprecatedAttributes; import org.apache.commons.cli.Option; +import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.lang3.tuple.Pair; import org.apache.rat.commandline.ArgumentContext; @@ -177,38 +179,24 @@ void cleanUp() { } @Test - public void testDeprecatedUseLogged() throws IOException { - TestingLog log = new TestingLog(); - try { - DefaultLog.setInstance(log); - String[] args = {"--dir", "target", "-a"}; - ReportConfiguration config = OptionCollection.parseCommands(testPath.toFile(), args, o -> fail("Help printed"), true); - assertThat(config).isNotNull(); - } finally { - DefaultLog.setInstance(null); - } - log.assertContainsExactly(1, "WARN: Option [-d, --dir] used. Deprecated for removal since 0.17: Use the standard '--'"); - log.assertContainsExactly(1, "WARN: Option [-a] used. Deprecated for removal since 0.17: Use --edit-license"); - } + public void testDeprecatedUseLogged() throws ParseException { + Options opts = OptionCollection.buildOptions(); + opts.addOption(Option.builder().longOpt("deprecated-option").deprecated(DeprecatedAttributes.builder().setDescription("Deprecation reason.") + .setForRemoval(true).setSince("1.0.0-SNAPSHOT").get()).build()); - @Test - public void testDirOptionCapturesDirectoryToScan() throws IOException { TestingLog log = new TestingLog(); - ReportConfiguration config; try { DefaultLog.setInstance(log); - String[] args = {"--dir", testPath.toFile().getAbsolutePath()}; - config = OptionCollection.parseCommands(testPath.toFile(), args, (o) -> { - }, true); + CommandLine commandLine = OptionCollection.parseCommandLine(opts, new String[]{"--deprecated-option", "."}); + commandLine.hasOption("--deprecated-option"); } finally { DefaultLog.setInstance(null); } - assertThat(config).isNotNull(); - log.assertContainsExactly(1,"WARN: Option [-d, --dir] used. Deprecated for removal since 0.17: Use the standard '--'"); + log.assertContainsExactly(1, "WARN: Option [--deprecated-option] used. Deprecated for removal since 1.0.0-SNAPSHOT: Deprecation reason."); } @Test - public void testShortenedOptions() throws IOException { + public void testShortenedOptions() throws IOException, ParseException { String[] args = {"--output-lic", "ALL"}; ReportConfiguration config = OptionCollection.parseCommands(testPath.toFile(), args, (o) -> { }, true); @@ -227,7 +215,7 @@ public void testDefaultConfiguration() throws ParseException { @ParameterizedTest @ValueSource(strings = { ".", "./", "target", "./target" }) - public void getReportableTest(String fName) throws IOException { + public void getReportableTest(String fName) throws IOException, ParseException { File base = new File(fName); String expected = DocumentName.FSInfo.getDefault().normalize(base.getAbsolutePath()); ReportConfiguration config = OptionCollection.parseCommands(testPath.toFile(), new String[]{fName}, o -> fail("Help called"), false); @@ -263,7 +251,7 @@ public void helpTest() { ReportConfiguration config = OptionCollection.parseCommands(testPath.toFile(), args, o -> helpCalled.set(true), true); assertThat(config).as("Should not have config").isNull(); assertThat(helpCalled.get()).as("Help was not called").isTrue(); - } catch (IOException e) { + } catch (IOException | ParseException e) { fail(e.getMessage()); } } @@ -282,7 +270,7 @@ public CliOptionsProvider() { * @return A ReportConfiguration * @throws IOException on critical error. */ - protected final ReportConfiguration generateConfig(List> args) throws IOException { + protected final ReportConfiguration generateConfig(List> args) throws IOException, ParseException { helpCalled.set(false); List sArgs = new ArrayList<>(); for (Pair pair : args) { diff --git a/apache-rat-core/src/test/java/org/apache/rat/ReporterOptionsProvider.java b/apache-rat-core/src/test/java/org/apache/rat/ReporterOptionsProvider.java index 6cf7b458a..50d4d25c5 100644 --- a/apache-rat-core/src/test/java/org/apache/rat/ReporterOptionsProvider.java +++ b/apache-rat-core/src/test/java/org/apache/rat/ReporterOptionsProvider.java @@ -39,6 +39,7 @@ import javax.xml.xpath.XPathFactory; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; +import org.apache.commons.cli.ParseException; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.Pair; @@ -62,7 +63,6 @@ import org.apache.rat.testhelpers.XmlUtils; import org.apache.rat.utils.DefaultLog; import org.apache.rat.utils.Log; -import org.junit.jupiter.params.provider.ArgumentsProvider; import org.w3c.dom.Document; import org.xml.sax.SAXException; @@ -73,7 +73,7 @@ /** * A class to provide the Options and tests to the testOptionsUpdateConfig. */ -class ReporterOptionsProvider extends AbstractOptionsProvider implements ArgumentsProvider { +class ReporterOptionsProvider extends AbstractOptionsProvider { static File sourceDir; /** @@ -84,9 +84,6 @@ class ReporterOptionsProvider extends AbstractOptionsProvider implements Argumen public ReporterOptionsProvider() { super(ReporterOptionsTest.testPath.toFile()); processTestFunctionAnnotations(); - testMap.put("addLicense", this::addLicenseTest); - testMap.remove("add-license"); - testMap.put("dir", () -> DefaultLog.getInstance().info("--dir has no valid test")); super.validate(Collections.emptyList()); } @@ -99,11 +96,11 @@ public ReporterOptionsProvider() { * @throws IOException on critical error. */ @Override - protected final ReportConfiguration generateConfig(List> args) throws IOException { + protected final ReportConfiguration generateConfig(List> args) throws IOException, ParseException { return generateConfig(args, false); } - protected final ReportConfiguration generateConfig(List> args, boolean helpExpected) throws IOException { + protected final ReportConfiguration generateConfig(List> args, boolean helpExpected) throws IOException, ParseException { if (sourceDir == null) { throw new IOException("sourceDir not set"); } @@ -121,7 +118,7 @@ private void configureSourceDir(Option option) { FileUtils.mkDir(sourceDir); } - private void validateNoArgSetup() throws IOException, RatException { + private void validateNoArgSetup() throws IOException, ParseException, RatException { // verify that without args the report is ok. TestingLog log = new TestingLog(); DefaultLog.setInstance(log); @@ -137,11 +134,6 @@ private void validateNoArgSetup() throws IOException, RatException { } - @OptionCollectionTest.TestFunction - protected void addLicenseTest() { - editLicenseTest(Arg.EDIT_ADD.find("addLicense")); - } - @OptionCollectionTest.TestFunction protected void editLicenseTest() { editLicenseTest(Arg.EDIT_ADD.find("edit-license")); @@ -181,7 +173,7 @@ private void editLicenseTest(final Option option) { " * under the License.\n" + " */\n\n" + "class NoLicense {}"); - } catch (IOException | RatException e) { + } catch (IOException | ParseException | RatException e) { fail(e.getMessage(), e); } } @@ -213,7 +205,7 @@ private void execLicensesDeniedTest(final Option option, final String[] args) { ClaimStatistic claimStatistic = reporter.execute(); ClaimValidator validator = config.getClaimValidator(); assertThat(validator.listIssues(claimStatistic)).containsExactly("UNAPPROVED"); - } catch (IOException | RatException e) { + } catch (IOException | ParseException | RatException e) { fail(e.getMessage(), e); } } @@ -248,16 +240,11 @@ private void noDefaultsTest(final Option option) { ClaimValidator validator = config.getClaimValidator(); assertThat(validator.listIssues(claimStatistic)).containsExactlyInAnyOrder("DOCUMENT_TYPES", "LICENSE_CATEGORIES", "LICENSE_NAMES", "STANDARDS"); } - } catch (IOException | RatException e) { + } catch (IOException | ParseException | RatException e) { fail(e.getMessage(), e); } } - @OptionCollectionTest.TestFunction - protected void noDefaultLicensesTest() { - noDefaultsTest(Arg.CONFIGURATION_NO_DEFAULTS.find("no-default-licenses")); - } - @OptionCollectionTest.TestFunction protected void configurationNoDefaultsTest() { noDefaultsTest(Arg.CONFIGURATION_NO_DEFAULTS.find("configuration-no-defaults")); @@ -284,7 +271,7 @@ protected void counterMaxTest() { claimStatistic = reporter.execute(); validator = config.getClaimValidator(); assertThat(validator.listIssues(claimStatistic)).isEmpty(); - } catch (IOException | RatException e) { + } catch (IOException | ParseException | RatException e) { fail(e.getMessage(), e); } } @@ -311,7 +298,7 @@ protected void counterMinTest() { claimStatistic = reporter.execute(); validator = config.getClaimValidator(); assertThat(validator.listIssues(claimStatistic)).isEmpty(); - } catch (IOException | RatException e) { + } catch (IOException | ParseException | RatException e) { fail(e.getMessage(), e); } } @@ -340,7 +327,7 @@ private void execExcludeTest(final Option option, final String[] args) { claimStatistic = reporter.execute(); assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(2); assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.IGNORED)).isEqualTo(3); - } catch (IOException | RatException e) { + } catch (IOException | ParseException | RatException e) { fail(e.getMessage(), e); } } @@ -351,21 +338,11 @@ private void excludeFileTest(final Option option) { execExcludeTest(option, new String[]{outputFile.getAbsolutePath()}); } - @OptionCollectionTest.TestFunction - protected void excludeFileTest() { - excludeFileTest(Arg.EXCLUDE_FILE.find("exclude-file")); - } - @OptionCollectionTest.TestFunction protected void inputExcludeFileTest() { excludeFileTest(Arg.EXCLUDE_FILE.find("input-exclude-file")); } - @OptionCollectionTest.TestFunction - protected void excludeTest() { - execExcludeTest(Arg.EXCLUDE.find("exclude"), EXCLUDE_ARGS); - } - @OptionCollectionTest.TestFunction protected void inputExcludeTest() { execExcludeTest(Arg.EXCLUDE.find("input-exclude"), EXCLUDE_ARGS); @@ -394,7 +371,7 @@ protected void inputExcludeSizeTest() { claimStatistic = reporter.execute(); assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(2); assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.IGNORED)).isEqualTo(1); - } catch (IOException | RatException e) { + } catch (IOException | ParseException | RatException e) { fail(e.getMessage(), e); } } @@ -429,7 +406,7 @@ protected void inputExcludeStdTest() { claimStatistic = reporter.execute(); assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(4); assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.IGNORED)).isEqualTo(5); - } catch (IOException | RatException e) { + } catch (IOException | ParseException | RatException e) { fail(e.getMessage(), e); } } @@ -488,7 +465,7 @@ protected void inputExcludeParsedScmTest() { claimStatistic = reporter.execute(); assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(3); assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.IGNORED)).isEqualTo(8); - } catch (IOException | RatException e) { + } catch (IOException | ParseException | RatException e) { fail(e.getMessage(), e); } } @@ -526,7 +503,7 @@ private void execIncludeTest(final Option option, final String[] args) { assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(3); // .gitignore is ignored by default as it is hidden but not counted assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.IGNORED)).isEqualTo(1); - } catch (IOException | RatException e) { + } catch (IOException | ParseException | RatException e) { fail(e.getMessage(), e); } } @@ -541,16 +518,6 @@ protected void inputIncludeFileTest() { includeFileTest(Arg.INCLUDE_FILE.find("input-include-file")); } - @OptionCollectionTest.TestFunction - protected void includesFileTest() { - includeFileTest(Arg.INCLUDE_FILE.find("includes-file")); - } - - @OptionCollectionTest.TestFunction - protected void includeTest() { - execIncludeTest(Arg.INCLUDE.find("include"), INCLUDE_ARGS); - } - @OptionCollectionTest.TestFunction protected void inputIncludeTest() { execIncludeTest(Arg.INCLUDE.find("input-include"), INCLUDE_ARGS); @@ -586,7 +553,7 @@ protected void inputIncludeStdTest() { claimStatistic = reporter.execute(); assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(7); assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.IGNORED)).isEqualTo(1); - } catch (IOException | RatException e) { + } catch (IOException | ParseException | RatException e) { fail(e.getMessage(), e); } } @@ -612,7 +579,7 @@ protected void inputSourceTest() { claimStatistic = reporter.execute(); assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(1); assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.IGNORED)).isEqualTo(0); - } catch (IOException | RatException e) { + } catch (IOException | ParseException | RatException e) { fail(e.getMessage(), e); } } @@ -646,7 +613,7 @@ private void execLicenseFamiliesApprovedTest(final Option option, final String[] assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(1); assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.APPROVED)).isEqualTo(1); assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.UNAPPROVED)).isEqualTo(0); - } catch (IOException | RatException e) { + } catch (IOException | ParseException | RatException e) { fail(e.getMessage(), e); } } @@ -686,7 +653,7 @@ private void execLicenseFamiliesDeniedTest(final Option option, final String[] a assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(1); assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.APPROVED)).isEqualTo(0); assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.UNAPPROVED)).isEqualTo(1); - } catch (IOException | RatException e) { + } catch (IOException | ParseException | RatException e) { fail(e.getMessage(), e); } } @@ -740,16 +707,11 @@ private void configTest(final Option option) { assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.APPROVED)).isEqualTo(1); assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.UNAPPROVED)).isEqualTo(1); - } catch (IOException | RatException e) { + } catch (IOException | ParseException | RatException e) { fail(e.getMessage(), e); } } - @OptionCollectionTest.TestFunction - protected void licensesTest() { - configTest(Arg.CONFIGURATION.find("licenses")); - } - @OptionCollectionTest.TestFunction protected void configTest() { configTest(Arg.CONFIGURATION.find("config")); @@ -780,7 +742,7 @@ protected void execLicensesApprovedTest(final Option option, String[] args) { assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.UNAPPROVED)).isEqualTo(0); - } catch (IOException | RatException e) { + } catch (IOException | ParseException | RatException e) { fail(e.getMessage(), e); } } @@ -798,38 +760,6 @@ protected void licensesApprovedTest() { new String[]{"GPL1"}); } - @OptionCollectionTest.TestFunction - protected void scanHiddenDirectoriesTest() { - Option option = Arg.INCLUDE_STD.find("scan-hidden-directories"); - Pair arg1 = ImmutablePair.of(option, null); - - try { - configureSourceDir(option); - - writeFile("apl.txt", "SPDX-License-Identifier: Apache-2.0"); - - File hiddenDir = new File(sourceDir, ".hiddendir"); - FileUtils.mkDir(hiddenDir); - FileUtils.writeFile(hiddenDir, "gpl.txt", Collections.singletonList("SPDX-License-Identifier: GPL-1.0-only")); - - ReportConfiguration config = generateConfig(); - Reporter reporter = new Reporter(config); - ClaimStatistic claimStatistic = reporter.execute(); - assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(1); - assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.APPROVED)).isEqualTo(1); - assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.UNAPPROVED)).isEqualTo(0); - - config = generateConfig(arg1); - reporter = new Reporter(config); - claimStatistic = reporter.execute(); - assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(2); - assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.APPROVED)).isEqualTo(1); - assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.UNAPPROVED)).isEqualTo(1); - } catch (IOException | RatException e) { - fail(e.getMessage(), e); - } - } - private void outTest(final Option option) { try { configureSourceDir(option); @@ -849,16 +779,11 @@ private void outTest(final Option option) { TextUtils.assertContainsExactly(1, "Apache License 2.0: 1 ", actualText); TextUtils.assertContainsExactly(1, "STANDARD: 1 ", actualText); - } catch (IOException | RatException e) { + } catch (IOException | ParseException | RatException e) { fail(e.getMessage(), e); } } - @OptionCollectionTest.TestFunction - protected void outTest() { - outTest(Arg.OUTPUT_FILE.find("out")); - } - @OptionCollectionTest.TestFunction protected void outputFileTest() { outTest(Arg.OUTPUT_FILE.find("output-file")); @@ -920,59 +845,18 @@ private void styleSheetTest(final Option option) { String actualText = baos.toString(StandardCharsets.UTF_8.name()); TextUtils.assertContainsExactly(1, "Hello world", actualText); - } catch (IOException | RatException e) { + } catch (IOException | ParseException | RatException e) { fail(e.getMessage(), e); } finally { System.setOut(origin); } } - @OptionCollectionTest.TestFunction - protected void stylesheetTest() { - styleSheetTest(Arg.OUTPUT_STYLE.find("stylesheet")); - } - @OptionCollectionTest.TestFunction protected void outputStyleTest() { styleSheetTest(Arg.OUTPUT_STYLE.find("output-style")); } - @OptionCollectionTest.TestFunction - protected void xmlTest() { - PrintStream origin = System.out; - Option option = Arg.OUTPUT_STYLE.find("xml"); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - try (PrintStream out = new PrintStream(baos)) { - System.setOut(out); - configureSourceDir(option); - // create a dummy stylesheet so that we match the stylesheet tests. - File file = writeFile("stylesheet", "\n" + - " \n" + - " Hello world\n" + - " \n" + - ""); - - ReportConfiguration config = generateConfig(ImmutablePair.of(option, null)); - Reporter reporter = new Reporter(config); - ClaimStatistic claimStatistic = reporter.output(); - assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(1); - assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.APPROVED)).isEqualTo(0); - assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.UNAPPROVED)).isEqualTo(1); - - String actualText = baos.toString(StandardCharsets.UTF_8.name()); - TextUtils.assertContainsExactly(1, "", actualText); - - try (InputStream expected = StyleSheets.getStyleSheet("xml").get(); - InputStream actual = config.getStyleSheet().get()) { - assertThat(IOUtils.contentEquals(expected, actual)).as("'xml' does not match").isTrue(); - } - } catch (IOException | RatException e) { - fail(e.getMessage(), e); - } finally { - System.setOut(origin); - } - } - @OptionCollectionTest.TestFunction protected void logLevelTest() { PrintStream origin = System.out; @@ -992,7 +876,7 @@ protected void logLevelTest() { reporter = new Reporter(config); reporter.output(); TextUtils.assertContains("DEBUG", baos.toString(StandardCharsets.UTF_8.name())); - } catch (IOException | RatException e) { + } catch (IOException | ParseException | RatException e) { fail(e.getMessage(), e); } finally { System.setOut(origin); @@ -1033,17 +917,12 @@ private void listLicenses(final Option option) { throw new IllegalArgumentException("Unexpected filter: " + filter); } } - } catch (IOException | RatException | SAXException | ParserConfigurationException | + } catch (IOException | ParseException | RatException | SAXException | ParserConfigurationException | XPathExpressionException e) { fail(e.getMessage(), e); } } - @OptionCollectionTest.TestFunction - protected void listLicensesTest() { - listLicenses(Arg.OUTPUT_LICENSES.find("list-licenses")); - } - @OptionCollectionTest.TestFunction protected void outputLicensesTest() { listLicenses(Arg.OUTPUT_LICENSES.find("output-licenses")); @@ -1082,17 +961,12 @@ private void listFamilies(final Option option) { throw new IllegalArgumentException("Unexpected filter: " + filter); } } - } catch (IOException | RatException | SAXException | ParserConfigurationException | + } catch (IOException | ParseException | RatException | SAXException | ParserConfigurationException | XPathExpressionException e) { fail(e.getMessage(), e); } } - @OptionCollectionTest.TestFunction - protected void listFamiliesTest() { - listFamilies(Arg.OUTPUT_FAMILIES.find("list-families")); - } - @OptionCollectionTest.TestFunction protected void outputFamiliesTest() { listFamilies(Arg.OUTPUT_FAMILIES.find("output-families")); @@ -1140,7 +1014,7 @@ private void archiveTest(final Option option) { throw new IllegalArgumentException("Unexpected processing " + proc); } } - } catch (IOException | RatException | SAXException | ParserConfigurationException | + } catch (IOException | ParseException| RatException | SAXException | ParserConfigurationException | XPathExpressionException e) { fail(e.getMessage(), e); } @@ -1195,7 +1069,7 @@ private void standardTest(final Option option) { throw new IllegalArgumentException("Unexpected processing " + proc); } } - } catch (IOException | RatException | SAXException | ParserConfigurationException | + } catch (IOException | ParseException | RatException | SAXException | ParserConfigurationException | XPathExpressionException e) { fail(e.getMessage(), e); } @@ -1245,26 +1119,16 @@ private void editCopyrightTest(final Option option, final Option extraOption) { TextUtils.assertNotContains(myCopyright, actualText); assertThat(newJavaFile).exists(); } - } catch (IOException | RatException e) { + } catch (IOException | ParseException | RatException e) { fail(e.getMessage(), e); } } - @OptionCollectionTest.TestFunction - protected void copyrightTest() { - editCopyrightTest(Arg.EDIT_COPYRIGHT.find("copyright"), null); - } - @OptionCollectionTest.TestFunction protected void editCopyrightTest() { editCopyrightTest(Arg.EDIT_COPYRIGHT.find("edit-copyright"), null); } - @OptionCollectionTest.TestFunction - protected void forceTest() { - editCopyrightTest(Arg.EDIT_COPYRIGHT.find("edit-copyright"), Arg.EDIT_OVERWRITE.find("force")); - } - @OptionCollectionTest.TestFunction protected void editOverwriteTest() { editCopyrightTest(Arg.EDIT_COPYRIGHT.find("edit-copyright"), Arg.EDIT_OVERWRITE.find("edit-overwrite")); @@ -1286,7 +1150,7 @@ public void helpTest() { assertThat(helpCalled.get()).as("Help was not called").isTrue(); new Help(System.out).printUsage(options); actualText = baos.toString(StandardCharsets.UTF_8.name()); - } catch (IOException e) { + } catch (IOException | ParseException e) { fail(e.getMessage(), e); } finally { System.setOut(origin); @@ -1334,7 +1198,7 @@ protected void helpLicensesTest() { configureSourceDir(option); ReportConfiguration config = generateConfig(arg1); actualText = baos.toString(StandardCharsets.UTF_8.name()); - } catch (IOException e) { + } catch (IOException | ParseException e) { fail(e.getMessage(), e); } finally { System.setOut(origin); diff --git a/apache-rat-core/src/test/java/org/apache/rat/ReporterOptionsTest.java b/apache-rat-core/src/test/java/org/apache/rat/ReporterOptionsTest.java index 9c7a389cc..575c0daea 100644 --- a/apache-rat-core/src/test/java/org/apache/rat/ReporterOptionsTest.java +++ b/apache-rat-core/src/test/java/org/apache/rat/ReporterOptionsTest.java @@ -24,6 +24,8 @@ import javax.xml.xpath.XPath; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; + +import org.apache.commons.cli.ParseException; import org.apache.rat.api.RatException; import org.apache.rat.report.claim.ClaimStatistic; import org.apache.rat.test.AbstractConfigurationOptionsProvider; @@ -98,7 +100,7 @@ void testRat362() { XmlUtils.mapOf("type", "IGNORED")); assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(0); assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.IGNORED)).isEqualTo(2); - } catch (IOException | RatException | XPathExpressionException e) { + } catch (IOException | ParseException | RatException | XPathExpressionException e) { fail(e); } } diff --git a/apache-rat-core/src/test/java/org/apache/rat/ReporterTest.java b/apache-rat-core/src/test/java/org/apache/rat/ReporterTest.java index 3de3e23e8..3ca56389e 100644 --- a/apache-rat-core/src/test/java/org/apache/rat/ReporterTest.java +++ b/apache-rat-core/src/test/java/org/apache/rat/ReporterTest.java @@ -137,7 +137,7 @@ public void testExecute() throws RatException, ParseException { @Test public void testOutputOption() throws Exception { File output = new File(tempDirectory, "test"); - CommandLine commandLine = new DefaultParser().parse(OptionCollection.buildOptions(), new String[]{"-o", output.getCanonicalPath(), basedir}); + CommandLine commandLine = new DefaultParser().parse(OptionCollection.buildOptions(), new String[]{"--output-file", output.getCanonicalPath(), basedir}); ArgumentContext ctxt = new ArgumentContext(new File("."), commandLine); ReportConfiguration config = OptionCollection.createConfiguration(ctxt); diff --git a/apache-rat-core/src/test/java/org/apache/rat/header/ArrayCharFilterTest.java b/apache-rat-core/src/test/java/org/apache/rat/header/ArrayCharFilterTest.java deleted file mode 100644 index e00a6c685..000000000 --- a/apache-rat-core/src/test/java/org/apache/rat/header/ArrayCharFilterTest.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one * - * or more contributor license agreements. See the NOTICE file * - * distributed with this work for additional information * - * regarding copyright ownership. The ASF licenses this file * - * to you under the Apache License, Version 2.0 (the * - * "License"); you may not use this file except in compliance * - * with the License. You may obtain a copy of the License at * - * * - * http://www.apache.org/licenses/LICENSE-2.0 * - * * - * Unless required by applicable law or agreed to in writing, * - * software distributed under the License is distributed on an * - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * - * KIND, either express or implied. See the License for the * - * specific language governing permissions and limitations * - * under the License. * - */ -package org.apache.rat.header; - - -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.junit.jupiter.api.BeforeEach; - -public class ArrayCharFilterTest { - - private static final char[] filtered = {'d', 'o', 'a'}; - private ArrayCharFilter filter; - - @BeforeEach - public void setUp() { - filter = new ArrayCharFilter(filtered); - } - - @Test - public void isFilteredOut() { - assertTrue(filter.isFilteredOut('a')); - assertFalse(filter.isFilteredOut('b')); - assertFalse(filter.isFilteredOut('c')); - assertTrue(filter.isFilteredOut('d')); - assertFalse(filter.isFilteredOut('e')); - assertFalse(filter.isFilteredOut('f')); - } - -} diff --git a/apache-rat-core/src/test/java/org/apache/rat/header/FilteringSequenceFactoryTest.java b/apache-rat-core/src/test/java/org/apache/rat/header/FilteringSequenceFactoryTest.java deleted file mode 100644 index 19eb9a88e..000000000 --- a/apache-rat-core/src/test/java/org/apache/rat/header/FilteringSequenceFactoryTest.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one * - * or more contributor license agreements. See the NOTICE file * - * distributed with this work for additional information * - * regarding copyright ownership. The ASF licenses this file * - * to you under the Apache License, Version 2.0 (the * - * "License"); you may not use this file except in compliance * - * with the License. You may obtain a copy of the License at * - * * - * http://www.apache.org/licenses/LICENSE-2.0 * - * * - * Unless required by applicable law or agreed to in writing, * - * software distributed under the License is distributed on an * - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * - * KIND, either express or implied. See the License for the * - * specific language governing permissions and limitations * - * under the License. * - */ -package org.apache.rat.header; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import java.io.StringReader; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -public class FilteringSequenceFactoryTest { - - private int capacity; - private FilteringSequenceFactory factory; - private SimpleCharFilter filter; - - @BeforeEach - public void setUp() { - capacity = 50; - filter = new SimpleCharFilter(); - factory = new FilteringSequenceFactory(capacity, filter); - } - - @Test - public void noFiltering() throws Exception { - final String INPUT = "Whatever"; - StringReader reader = new StringReader(INPUT); - CharSequence result = factory.filter(reader); - assertNotNull(result); - String output = result.toString(); - assertEquals(INPUT, output, "No filtering so input equals output."); - reader = new StringReader(INPUT); - result = factory.filter(reader); - assertNotNull(result); - output = result.toString(); - assertEquals(INPUT, output, "No filtering so input equals output. Independent of previous input"); - } - - @Test - public void filtering() throws Exception { - final String INPUT = "Whatever"; - StringReader reader = new StringReader(INPUT); - CharSequence result = factory.filter(reader); - assertNotNull(result); - String output = result.toString(); - assertEquals(INPUT, output, "No filtering so input equals output."); - filter.filterOut = true; - reader = new StringReader(INPUT); - result = factory.filter(reader); - assertNotNull(result); - assertEquals( 0, result.length(), "All filtered output is empty. Independent of previous input"); - } - - @Test - public void overCapacity() throws Exception { - final String INPUT = "WhateverWhateverWhateverWhateverWhateverWhateverWhateverWhateverWhateverWhatever"; - StringReader reader = new StringReader(INPUT); - CharSequence result = factory.filter(reader); - assertNotNull(result); - String output = result.toString(); - assertEquals(INPUT.substring(0, capacity), output, "No filtering so input equals output."); - } -} diff --git a/apache-rat-core/src/test/java/org/apache/rat/header/HeaderMatcherTest.java b/apache-rat-core/src/test/java/org/apache/rat/header/HeaderMatcherTest.java deleted file mode 100644 index f4b863b0e..000000000 --- a/apache-rat-core/src/test/java/org/apache/rat/header/HeaderMatcherTest.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one * - * or more contributor license agreements. See the NOTICE file * - * distributed with this work for additional information * - * regarding copyright ownership. The ASF licenses this file * - * to you under the Apache License, Version 2.0 (the * - * "License"); you may not use this file except in compliance * - * with the License. You may obtain a copy of the License at * - * * - * http://www.apache.org/licenses/LICENSE-2.0 * - * * - * Unless required by applicable law or agreed to in writing, * - * software distributed under the License is distributed on an * - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * - * KIND, either express or implied. See the License for the * - * specific language governing permissions and limitations * - * under the License. * - */ -package org.apache.rat.header; - - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import java.io.StringReader; -import java.util.regex.Pattern; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -public class HeaderMatcherTest { - - private HeaderMatcher matcher; - private SimpleCharFilter filter; - - @BeforeEach - public void setUp() { - filter = new SimpleCharFilter(); - matcher = new HeaderMatcher(filter, 20); - } - - @Test - public void simpleMatches() throws Exception { - Pattern hatPattern = Pattern.compile("(.*)hat(.*)"); - Pattern headPattern = Pattern.compile("head...."); - StringReader reader = new StringReader("The mad hatter"); - matcher.read(reader); - assertTrue(matcher.matches(hatPattern)); - assertFalse(matcher.matches(headPattern)); - reader = new StringReader("headache"); - matcher.read(reader); - assertFalse(matcher.matches(hatPattern)); - assertTrue(matcher.matches(headPattern)); - } - - @Test - public void filteredMatches() throws Exception { - Pattern capPattern = Pattern.compile("cap(.*)"); - StringReader reader = new StringReader("capped"); - matcher.read(reader); - assertTrue(matcher.matches(capPattern)); - filter.filterOut = true; - reader = new StringReader("capped"); - matcher.read(reader); - assertFalse(matcher.matches(capPattern)); - } - - @Test - public void noLines() throws Exception { - StringReader reader = new StringReader("None"); - matcher.read(reader); - assertEquals(0, matcher.lines(), "No lines read"); - } - - @Test - public void lines() throws Exception { - StringReader reader = new StringReader("One\n"); - matcher.read(reader); - assertEquals(1, matcher.lines(), "One line read"); - reader = new StringReader("One\nTwo"); - matcher.read(reader); - assertEquals( 1, matcher.lines(), "One line read"); - reader = new StringReader("One\nTwo\nThree"); - matcher.read(reader); - assertEquals( 2, matcher.lines(), "Two lines read"); - reader = new StringReader("One\nTwo\nThree\n"); - matcher.read(reader); - assertEquals( 3, matcher.lines(), "Three lines read"); - } - - @Test - public void tooManyLines() throws Exception { - StringReader reader = new StringReader("WhateverWhateverWhateverWhateverWhateverWhateverWhateverWhatever"); - matcher.read(reader); - assertEquals( -1, matcher.lines(), "Too many lines read"); - } -} diff --git a/apache-rat-core/src/test/java/org/apache/rat/header/HeaderMatcherWithBeansTest.java b/apache-rat-core/src/test/java/org/apache/rat/header/HeaderMatcherWithBeansTest.java deleted file mode 100644 index ada143f92..000000000 --- a/apache-rat-core/src/test/java/org/apache/rat/header/HeaderMatcherWithBeansTest.java +++ /dev/null @@ -1,79 +0,0 @@ - -/* - * Licensed to the Apache Software Foundation (ASF) under one * - * or more contributor license agreements. See the NOTICE file * - * distributed with this work for additional information * - * regarding copyright ownership. The ASF licenses this file * - * to you under the Apache License, Version 2.0 (the * - * "License"); you may not use this file except in compliance * - * with the License. You may obtain a copy of the License at * - * * - * http://www.apache.org/licenses/LICENSE-2.0 * - * * - * Unless required by applicable law or agreed to in writing, * - * software distributed under the License is distributed on an * - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * - * KIND, either express or implied. See the License for the * - * specific language governing permissions and limitations * - * under the License. * - */ -package org.apache.rat.header; - - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import java.io.StringReader; -import java.util.regex.Pattern; - -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -public class HeaderMatcherWithBeansTest { - - private HeaderMatcher matcher; - private SimpleCharFilter filter; - private HeaderBean[] beans; - - @BeforeEach - public void setUp() { - HeaderBean[] beans = { - new HeaderBean(), - new HeaderBean(), - new HeaderBean() - }; - this.beans = beans; - filter = new SimpleCharFilter(); - matcher = new HeaderMatcher(filter, 20, beans); - } - - @Test - public void nulls() throws Exception { - beans[0].setMatch(false); - beans[1].setMatch(true); - beans[2].setMatch(false); - StringReader reader = new StringReader("Whatever"); - matcher.read(reader); - assertFalse(beans[0].isMatch(),"State preserved"); - assertTrue( beans[1].isMatch(),"State preserved"); - assertFalse(beans[2].isMatch(), "State preserved"); - beans[0].setMatch(true); - beans[1].setMatch(false); - beans[2].setMatch(true); - assertTrue(beans[0].isMatch(), "State preserved"); - assertFalse(beans[1].isMatch(), "State preserved"); - assertTrue(beans[2].isMatch(), "State preserved"); - } - - @Test - public void matches() throws Exception { - beans[0].setHeaderPattern(Pattern.compile("What(.*)")); - beans[1].setHeaderPattern(Pattern.compile("(.*)ever")); - beans[2].setHeaderPattern(Pattern.compile("What")); - StringReader reader = new StringReader("Whatever"); - matcher.read(reader); - assertTrue(beans[0].isMatch(), "Match header pattern"); - assertTrue(beans[1].isMatch(), "Match header pattern"); - assertFalse(beans[2].isMatch(), "Match header pattern"); - } -} diff --git a/apache-rat-core/src/test/java/org/apache/rat/help/HelpTest.java b/apache-rat-core/src/test/java/org/apache/rat/help/HelpTest.java index e3e994765..474ba053e 100644 --- a/apache-rat-core/src/test/java/org/apache/rat/help/HelpTest.java +++ b/apache-rat-core/src/test/java/org/apache/rat/help/HelpTest.java @@ -25,7 +25,10 @@ import org.junit.jupiter.api.Test; import java.io.StringWriter; +import java.util.Arrays; +import java.util.List; import java.util.Set; +import java.util.stream.Collectors; import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; @@ -55,7 +58,7 @@ public void verifyAllOptionsListed() { @Test public void verifyArgumentsListed() { Options opts = OptionCollection.buildOptions(); - Set argTypes = OptionCollection.getArgumentTypes().keySet(); + Set argTypes = Arrays.stream(OptionCollection.ArgumentType.values()).map(OptionCollection.ArgumentType::getDisplayName).collect(Collectors.toSet()); StringWriter out = new StringWriter(); new Help(out).printUsage(opts); String result = out.toString(); diff --git a/apache-rat-core/src/test/java/org/apache/rat/test/AbstractConfigurationOptionsProvider.java b/apache-rat-core/src/test/java/org/apache/rat/test/AbstractConfigurationOptionsProvider.java index 622878471..3168ab9f6 100644 --- a/apache-rat-core/src/test/java/org/apache/rat/test/AbstractConfigurationOptionsProvider.java +++ b/apache-rat-core/src/test/java/org/apache/rat/test/AbstractConfigurationOptionsProvider.java @@ -21,6 +21,7 @@ import java.nio.file.FileSystems; import java.nio.file.Path; import org.apache.commons.cli.Option; +import org.apache.commons.cli.ParseException; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.tuple.ImmutablePair; @@ -100,24 +101,16 @@ public static File setup(final File baseDir) { protected AbstractConfigurationOptionsProvider(final Collection unsupportedArgs, final File baseDir) { super(setup(baseDir)); - addTest(OptionCollectionTest.OptionTest.namedTest("addLicense", this::addLicenseTest)); addTest(OptionCollectionTest.OptionTest.namedTest("config", this::configTest)); addTest(OptionCollectionTest.OptionTest.namedTest("configuration-no-defaults", this::configurationNoDefaultsTest)); - addTest(OptionCollectionTest.OptionTest.namedTest("copyright", this::copyrightTest)); addTest(OptionCollectionTest.OptionTest.namedTest("counter-min", this::counterMinTest)); addTest(OptionCollectionTest.OptionTest.namedTest("counter-max", this::counterMaxTest)); - addTest(OptionCollectionTest.OptionTest.namedTest("dir", () -> DefaultLog.getInstance().info("--dir has no valid test"))); addTest(OptionCollectionTest.OptionTest.namedTest("dry-run", this::dryRunTest)); addTest(OptionCollectionTest.OptionTest.namedTest("edit-copyright", this::editCopyrightTest)); addTest(OptionCollectionTest.OptionTest.namedTest("edit-license", this::editLicenseTest)); addTest(OptionCollectionTest.OptionTest.namedTest("edit-overwrite", this::editOverwriteTest)); - addTest(OptionCollectionTest.OptionTest.namedTest("exclude", this::excludeTest)); - addTest(OptionCollectionTest.OptionTest.namedTest("exclude-file", this::excludeFileTest)); - addTest(OptionCollectionTest.OptionTest.namedTest("force", this::forceTest)); addTest(OptionCollectionTest.OptionTest.namedTest("help", this::helpTest)); addTest(OptionCollectionTest.OptionTest.namedTest("help-licenses", this::helpLicenses)); - addTest(OptionCollectionTest.OptionTest.namedTest("include", this::includeTest)); - addTest(OptionCollectionTest.OptionTest.namedTest("includes-file", this::includesFileTest)); addTest(OptionCollectionTest.OptionTest.namedTest("input-exclude", this::inputExcludeTest)); addTest(OptionCollectionTest.OptionTest.namedTest("input-exclude-file", this::inputExcludeFileTest)); addTest(OptionCollectionTest.OptionTest.namedTest("input-exclude-parsed-scm", this::inputExcludeParsedScmTest)); @@ -131,25 +124,17 @@ protected AbstractConfigurationOptionsProvider(final Collection unsuppor addTest(OptionCollectionTest.OptionTest.namedTest("license-families-approved-file", this::licenseFamiliesApprovedFileTest)); addTest(OptionCollectionTest.OptionTest.namedTest("license-families-denied", this::licenseFamiliesDeniedTest)); addTest(OptionCollectionTest.OptionTest.namedTest("license-families-denied-file", this::licenseFamiliesDeniedFileTest)); - addTest(OptionCollectionTest.OptionTest.namedTest("licenses", this::licensesTest)); addTest(OptionCollectionTest.OptionTest.namedTest("licenses-approved", this::licensesApprovedTest)); addTest(OptionCollectionTest.OptionTest.namedTest("licenses-approved-file", this::licensesApprovedFileTest)); addTest(OptionCollectionTest.OptionTest.namedTest("licenses-denied", this::licensesDeniedTest)); addTest(OptionCollectionTest.OptionTest.namedTest("licenses-denied-file", this::licensesDeniedFileTest)); - addTest(OptionCollectionTest.OptionTest.namedTest("list-families", this::listFamiliesTest)); - addTest(OptionCollectionTest.OptionTest.namedTest("list-licenses", this::listLicensesTest)); addTest(OptionCollectionTest.OptionTest.namedTest("log-level", this::logLevelTest)); - addTest(OptionCollectionTest.OptionTest.namedTest("no-default-licenses", this::noDefaultsTest)); - addTest(OptionCollectionTest.OptionTest.namedTest("out", this::outTest)); addTest(OptionCollectionTest.OptionTest.namedTest("output-archive", this::outputArchiveTest)); addTest(OptionCollectionTest.OptionTest.namedTest("output-families", this::outputFamiliesTest)); addTest(OptionCollectionTest.OptionTest.namedTest("output-file", this::outputFileTest)); addTest(OptionCollectionTest.OptionTest.namedTest("output-licenses", this::outputLicensesTest)); addTest(OptionCollectionTest.OptionTest.namedTest("output-standard", this::outputStandardTest)); addTest(OptionCollectionTest.OptionTest.namedTest("output-style", this::outputStyleTest)); - addTest(OptionCollectionTest.OptionTest.namedTest("scan-hidden-directories", this::scanHiddenDirectoriesTest)); - addTest(OptionCollectionTest.OptionTest.namedTest("stylesheet", this::styleSheetTest)); - addTest(OptionCollectionTest.OptionTest.namedTest("xml", this::xmlTest)); super.validate(unsupportedArgs); } @@ -171,7 +156,7 @@ private void execExcludeTest(final Option option, final String[] args) { DocumentName docName = mkDocName(fname); assertThat(excluder.matches(docName)).as(() -> dump(option, fname, excluder, docName)).isFalse(); } - } catch (IOException e) { + } catch (IOException | ParseException e) { fail(e.getMessage()); } } @@ -181,18 +166,10 @@ private void excludeFileTest(final Option option) { execExcludeTest(option, new String[]{outputFile.getAbsolutePath()}); } - protected void excludeFileTest() { - excludeFileTest(Arg.EXCLUDE_FILE.find("exclude-file")); - } - protected void inputExcludeFileTest() { excludeFileTest(Arg.EXCLUDE_FILE.find("input-exclude-file")); } - protected void excludeTest() { - execExcludeTest(Arg.EXCLUDE.find("exclude"), EXCLUDE_ARGS); - } - protected void inputExcludeTest() { execExcludeTest(Arg.EXCLUDE.find("input-exclude"), EXCLUDE_ARGS); } @@ -213,7 +190,7 @@ protected void inputExcludeStdTest() { DocumentName docName = mkDocName(fname); assertThat(excluder.matches(docName)).as(() -> dump(option, fname, excluder, docName)).isTrue(); } - } catch (IOException e) { + } catch (IOException | ParseException e) { fail(e.getMessage()); } } @@ -249,7 +226,7 @@ protected void inputExcludeParsedScmTest() { DocumentName docName = mkDocName(fname); assertThat(excluder.matches(docName)).as(() -> dump(option, fname, excluder, docName)).isTrue(); } - } catch (IOException e) { + } catch (IOException | ParseException e) { fail(e.getMessage()); } } @@ -275,7 +252,7 @@ private void inputExcludeSizeTest() { DocumentName docName = mkDocName(fname); assertThat(excluder.matches(docName)).as(() -> dump(option, fname, excluder, docName)).isTrue(); } - } catch (IOException e) { + } catch (IOException | ParseException e) { fail(e.getMessage()); } } @@ -297,7 +274,7 @@ private void execIncludeTest(final Option option, final String[] args) { DocumentName docName = mkDocName(fname); assertThat(excluder.matches(docName)).as(() -> dump(option, fname, excluder, docName)).isTrue(); } - } catch (IOException e) { + } catch (IOException | ParseException e) { fail(e.getMessage()); } } @@ -311,13 +288,6 @@ protected void inputIncludeFileTest() { includeFileTest(Arg.INCLUDE_FILE.find("input-include-file")); } - protected void includesFileTest() { - includeFileTest(Arg.INCLUDE_FILE.find("includes-file")); - } - - protected void includeTest() { - execIncludeTest(Arg.INCLUDE.find("include"), INCLUDE_ARGS); - } protected void inputIncludeTest() { execIncludeTest(Arg.INCLUDE.find("input-include"), INCLUDE_ARGS); @@ -341,7 +311,7 @@ protected void inputIncludeStdTest() { DocumentName docName = mkDocName(fname); assertThat(excluder.matches(docName)).as(() -> dump(option, fname, excluder, docName)).isTrue(); } - } catch (IOException e) { + } catch (IOException | ParseException e) { fail(e.getMessage()); } } @@ -351,7 +321,7 @@ protected void inputSourceTest() { try { ReportConfiguration config = generateConfig(ImmutablePair.of(option, new String[]{baseDir.getAbsolutePath()})); assertThat(config.hasSource()).isTrue(); - } catch (IOException e) { + } catch (IOException | ParseException e) { fail(e.getMessage()); } } @@ -363,7 +333,7 @@ protected void execLicensesApprovedTest(final Option option, String[] args) { ReportConfiguration config = generateConfig(arg1); SortedSet result = config.getLicenseIds(LicenseSetFactory.LicenseFilter.APPROVED); assertThat(result).contains("one", "two"); - } catch (IOException e) { + } catch (IOException | ParseException e) { fail(e.getMessage()); } @@ -376,7 +346,7 @@ protected void execLicensesApprovedTest(final Option option, String[] args) { ReportConfiguration config = generateConfig(arg1, arg2); SortedSet result = config.getLicenseIds(LicenseSetFactory.LicenseFilter.APPROVED); assertThat(result).containsExactly("one", "two"); - } catch (IOException e) { + } catch (IOException | ParseException e) { fail(e.getMessage()); } } @@ -387,7 +357,7 @@ protected void helpLicenses() { try (PrintStream out = new PrintStream(output)) { System.setOut(out); generateConfig(ImmutablePair.of(HELP_LICENSES.option(), null)); - } catch (IOException e) { + } catch (IOException | ParseException e) { fail(e.getMessage()); } finally { System.setOut(origin); @@ -415,7 +385,7 @@ private void execLicensesDeniedTest(final Option option, final String[] args) { assertThat(config.getLicenseIds(LicenseSetFactory.LicenseFilter.ALL)).contains("ILLUMOS"); SortedSet result = config.getLicenseIds(LicenseSetFactory.LicenseFilter.APPROVED); assertThat(result).doesNotContain("ILLUMOS"); - } catch (IOException e) { + } catch (IOException | ParseException e) { fail(e.getMessage()); } } @@ -437,7 +407,7 @@ private void execLicenseFamiliesApprovedTest(final Option option, final String[] ReportConfiguration config = generateConfig(arg1); SortedSet result = config.getLicenseCategories(LicenseSetFactory.LicenseFilter.APPROVED); assertThat(result).contains(catz); - } catch (IOException e) { + } catch (IOException | ParseException e) { fail(e.getMessage()); } @@ -446,7 +416,7 @@ private void execLicenseFamiliesApprovedTest(final Option option, final String[] ReportConfiguration config = generateConfig(arg1, arg2); SortedSet result = config.getLicenseCategories(LicenseSetFactory.LicenseFilter.APPROVED); assertThat(result).containsExactly(catz); - } catch (IOException e) { + } catch (IOException | ParseException e) { fail(e.getMessage()); } } @@ -469,7 +439,7 @@ private void execLicenseFamiliesDeniedTest(final Option option, final String[] a assertThat(config.getLicenseCategories(LicenseSetFactory.LicenseFilter.ALL)).contains(gpl); SortedSet result = config.getLicenseCategories(LicenseSetFactory.LicenseFilter.APPROVED); assertThat(result).doesNotContain(gpl); - } catch (IOException e) { + } catch (IOException | ParseException e) { fail(e.getMessage()); } } @@ -502,7 +472,7 @@ protected void counterMaxTest() { config = generateConfig(ImmutablePair.of(option, args)); assertThat(config.getClaimValidator().getMax(ClaimStatistic.Counter.UNAPPROVED)).isEqualTo(5); assertThat(config.getClaimValidator().getMax(ClaimStatistic.Counter.IGNORED)).isEqualTo(0); - } catch (IOException e) { + } catch (IOException | ParseException e) { fail(e.getMessage()); } } @@ -524,7 +494,7 @@ protected void counterMinTest() { config = generateConfig(ImmutablePair.of(option, args)); assertThat(config.getClaimValidator().getMin(ClaimStatistic.Counter.UNAPPROVED)).isEqualTo(5); assertThat(config.getClaimValidator().getMin(ClaimStatistic.Counter.IGNORED)).isEqualTo(0); - } catch (IOException e) { + } catch (IOException | ParseException e) { fail(e.getMessage()); } } @@ -546,15 +516,11 @@ private void configTest(final Option option) { assertThat(set).hasSize(2); assertThat(LicenseSetFactory.search("ONE", "ONE", set)).isPresent(); assertThat(LicenseSetFactory.search("TWO", "TWO", set)).isPresent(); - } catch (IOException e) { + } catch (IOException | ParseException e) { fail(e.getMessage()); } } - protected void licensesTest() { - configTest(Arg.CONFIGURATION.find("licenses")); - } - protected void configTest() { configTest(Arg.CONFIGURATION.find("config")); } @@ -565,15 +531,11 @@ private void noDefaultsTest(final Option arg) { assertThat(config.getLicenses(LicenseSetFactory.LicenseFilter.ALL)).isEmpty(); config = generateConfig(ImmutablePair.nullPair()); assertThat(config.getLicenses(LicenseSetFactory.LicenseFilter.ALL)).isNotEmpty(); - } catch (IOException e) { + } catch (IOException | ParseException e) { fail(e.getMessage()); } } - protected void noDefaultsTest() { - noDefaultsTest(Arg.CONFIGURATION_NO_DEFAULTS.find("no-default-licenses")); - } - protected void configurationNoDefaultsTest() { noDefaultsTest(Arg.CONFIGURATION_NO_DEFAULTS.find("configuration-no-defaults")); } @@ -584,7 +546,7 @@ protected void dryRunTest() { assertThat(config.isDryRun()).isTrue(); config = generateConfig(ImmutablePair.nullPair()); assertThat(config.isDryRun()).isFalse(); - } catch (IOException e) { + } catch (IOException | ParseException e) { fail(e.getMessage()); } } @@ -597,19 +559,14 @@ private void editCopyrightTest(final Option option) { Pair arg2 = ImmutablePair.of(Arg.EDIT_ADD.find("edit-license"), null); config = generateConfig(arg1, arg2); assertThat(config.getCopyrightMessage()).isEqualTo("MyCopyright"); - } catch (IOException e) { - e.printStackTrace(); + } catch (IOException | ParseException e) { if (e.getCause() != null) { - fail(e.getMessage() + ": " + e.getCause().getMessage()); + fail(e.getMessage() + ": " + e.getCause().getMessage(), e); } - fail(e.getMessage()); + fail(e.getMessage(), e); } } - protected void copyrightTest() { - editCopyrightTest(Arg.EDIT_COPYRIGHT.find("copyright")); - } - protected void editCopyrightTest() { editCopyrightTest(Arg.EDIT_COPYRIGHT.find("edit-copyright")); } @@ -620,15 +577,11 @@ private void editLicenseTest(final Option option) { assertThat(config.isAddingLicenses()).isTrue(); config = generateConfig(ImmutablePair.nullPair()); assertThat(config.isAddingLicenses()).isFalse(); - } catch (IOException e) { + } catch (IOException | ParseException e) { fail(e.getMessage()); } } - protected void addLicenseTest() { - editLicenseTest(Arg.EDIT_ADD.find("addLicense")); - } - protected void editLicenseTest() { editLicenseTest(Arg.EDIT_ADD.find("edit-license")); } @@ -642,15 +595,11 @@ private void overwriteTest(final Option option) { config = generateConfig(arg1, arg2); assertThat(config.isAddingLicensesForced()).isTrue(); - } catch (IOException e) { + } catch (IOException | ParseException e) { fail(e.getMessage()); } } - protected void forceTest() { - overwriteTest(Arg.EDIT_OVERWRITE.find("force")); - } - protected void editOverwriteTest() { overwriteTest(Arg.EDIT_OVERWRITE.find("edit-overwrite")); } @@ -665,7 +614,7 @@ protected void logLevelTest() { args[0] = level.name(); generateConfig(ImmutablePair.of(option, args)); assertThat(DefaultLog.getInstance().getLevel()).isEqualTo(level); - } catch (IOException e) { + } catch (IOException | ParseException e) { fail(e.getMessage()); } } @@ -682,7 +631,7 @@ private void archiveTest(final Option option) { ReportConfiguration config = generateConfig(ImmutablePair.of(option, args)); assertThat(config.getArchiveProcessing()).isEqualTo(proc); } - } catch (IOException e) { + } catch (IOException | ParseException e) { fail(e.getMessage()); } } @@ -698,16 +647,12 @@ private void listFamilies(final Option option) { args[0] = filter.name(); ReportConfiguration config = generateConfig(ImmutablePair.of(option, args)); assertThat(config.listFamilies()).isEqualTo(filter); - } catch (IOException e) { + } catch (IOException | ParseException e) { fail(e.getMessage()); } } } - protected void listFamiliesTest() { - listFamilies(Arg.OUTPUT_FAMILIES.find("list-families")); - } - protected void outputFamiliesTest() { listFamilies(Arg.OUTPUT_FAMILIES.find("output-families")); } @@ -727,15 +672,11 @@ private void outTest(final Option option) { } catch (IOException e) { throw new RuntimeException(e); } - } catch (IOException e) { + } catch (IOException | ParseException e) { fail(e.getMessage()); } } - protected void outTest() { - outTest(Arg.OUTPUT_FILE.find("out")); - } - protected void outputFileTest() { outTest(Arg.OUTPUT_FILE.find("output-file")); } @@ -747,16 +688,12 @@ private void listLicenses(final Option option) { args[0] = filter.name(); ReportConfiguration config = generateConfig(ImmutablePair.of(option, args)); assertThat(config.listLicenses()).isEqualTo(filter); - } catch (IOException e) { + } catch (IOException | ParseException e) { fail(e.getMessage()); } } } - protected void listLicensesTest() { - listLicenses(Arg.OUTPUT_LICENSES.find("list-licenses")); - } - protected void outputLicensesTest() { listLicenses(Arg.OUTPUT_LICENSES.find("output-licenses")); } @@ -769,7 +706,7 @@ private void standardTest(final Option option) { ReportConfiguration config = generateConfig(ImmutablePair.of(option, args)); assertThat(config.getStandardProcessing()).isEqualTo(proc); } - } catch (IOException e) { + } catch (IOException | ParseException e) { fail(e.getMessage()); } } @@ -799,38 +736,13 @@ private void styleSheetTest(final Option option) { assertThat(IOUtils.contentEquals(expected, actual)).as(() -> String.format("'%s' does not match", sheet)).isTrue(); } } - } catch (IOException e) { + } catch (IOException | ParseException e) { fail(e.getMessage()); } } - protected void styleSheetTest() { - styleSheetTest(Arg.OUTPUT_STYLE.find("stylesheet")); - } - protected void outputStyleTest() { styleSheetTest(Arg.OUTPUT_STYLE.find("output-style")); } - protected void scanHiddenDirectoriesTest() { - try { - ReportConfiguration config = generateConfig(ImmutablePair.of(Arg.INCLUDE_STD.find("scan-hidden-directories"), null)); - DocumentNameMatcher excluder = config.getDocumentExcluder(baseName()); - assertThat(excluder.matches(mkDocName(".file"))).as(".file").isTrue(); - } catch (IOException e) { - fail(e.getMessage()); - } - } - - protected void xmlTest() { - try { - ReportConfiguration config = generateConfig(ImmutablePair.of(Arg.OUTPUT_STYLE.find("xml"), null)); - try (InputStream expected = StyleSheets.getStyleSheet("xml").get(); - InputStream actual = config.getStyleSheet().get()) { - assertThat(IOUtils.contentEquals(expected, actual)).as("'xml' does not match").isTrue(); - } - } catch (IOException e) { - fail(e.getMessage()); - } - } } diff --git a/apache-rat-core/src/test/java/org/apache/rat/test/AbstractOptionsProvider.java b/apache-rat-core/src/test/java/org/apache/rat/test/AbstractOptionsProvider.java index dac4b4150..7c70f3f77 100644 --- a/apache-rat-core/src/test/java/org/apache/rat/test/AbstractOptionsProvider.java +++ b/apache-rat-core/src/test/java/org/apache/rat/test/AbstractOptionsProvider.java @@ -31,6 +31,7 @@ import java.util.TreeMap; import java.util.stream.Stream; import org.apache.commons.cli.Option; +import org.apache.commons.cli.ParseException; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.tuple.Pair; import org.apache.rat.OptionCollectionTest; @@ -135,7 +136,7 @@ private void verifyAllMethodsDefinedAndNeeded(final Collection unsupport } @SafeVarargs - protected final ReportConfiguration generateConfig(final Pair... args) throws IOException { + protected final ReportConfiguration generateConfig(final Pair... args) throws IOException, ParseException { List> options = Arrays.asList(args); return generateConfig(options); } @@ -148,7 +149,7 @@ protected final ReportConfiguration generateConfig(final Pair. * @return The generated ReportConfiguration. * @throws IOException on error. */ - protected abstract ReportConfiguration generateConfig(final List> args) throws IOException; + protected abstract ReportConfiguration generateConfig(final List> args) throws IOException, ParseException; /** * Converts each {@code Pair} into the option string and its arguments. diff --git a/apache-rat-plugin/src/main/java/org/apache/rat/mp/AbstractRatMojo.java b/apache-rat-plugin/src/main/java/org/apache/rat/mp/AbstractRatMojo.java index c3e38a8d5..29ec8c664 100644 --- a/apache-rat-plugin/src/main/java/org/apache/rat/mp/AbstractRatMojo.java +++ b/apache-rat-plugin/src/main/java/org/apache/rat/mp/AbstractRatMojo.java @@ -27,6 +27,7 @@ import java.util.Map; import org.apache.commons.cli.Option; +import org.apache.commons.cli.ParseException; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; @@ -254,7 +255,7 @@ protected ReportConfiguration getConfiguration() throws MojoExecutionException { new org.apache.rat.help.Licenses(config, new PrintWriter(log.asWriter())).printHelp(); } reportConfiguration = config; - } catch (IOException e) { + } catch (IOException | ParseException e) { throw new MojoExecutionException(e); } }