This is an automated email from the ASF dual-hosted git repository. claude pushed a commit to branch feature/restructure in repository https://gitbox.apache.org/repos/asf/creadur-rat.git
commit e10542206d5a4634267da252013e88196c25c8be Author: Claude Warren <[email protected]> AuthorDate: Fri Dec 26 12:25:41 2025 +0000 generated maven test code --- .../testhelpers/data/OptionTestDataProvider.java | 3 +- .../testhelpers/data/ReportTestDataProvider.java | 7 +- .../org/apache/rat/testhelpers/data/TestData.java | 45 +- apache-rat-plugin-parent/impl/pom.xml | 15 +- .../java/org/apache/rat/maven/RatCheckMojo.java | 15 +- .../java/org/apache/rat/maven/RatReportMojo.java | 4 +- .../org/apache/rat/maven/RatCheckMojoTest.java | 475 ++++++++++++++++++++ .../java/org/apache/rat/maven/SettingsStub.java | 16 + .../apache/rat/mp/BetterAbstractMojoTestCase.java | 250 +++++------ .../test/java/org/apache/rat/mp/MavenOption.java | 182 ++++---- .../java/org/apache/rat/mp/OptionMojoTest.java | 344 +++++++-------- .../java/org/apache/rat/mp/RatCheckMojoTest.java | 484 --------------------- .../java/org/apache/rat/mp/RatTestHelpers.java | 418 +++++++++--------- .../java/org/apache/rat/maven/CodeGenerator.java | 8 +- .../java/org/apache/rat/maven/TestGenerator.java | 52 ++- .../resources/org/apache/rat/maven/TestJava.vm | 20 +- .../resources/org/apache/rat/maven/TestMethod.vm | 15 +- .../rat/maven/{TestGenerator.vm => TestPom.vm} | 6 + .../resources/org/apache/rat/maven/TestStub.vm | 78 ++++ 19 files changed, 1300 insertions(+), 1137 deletions(-) diff --git a/apache-rat-core/src/test/java/org/apache/rat/testhelpers/data/OptionTestDataProvider.java b/apache-rat-core/src/test/java/org/apache/rat/testhelpers/data/OptionTestDataProvider.java index bdb4b03d..40f9968f 100644 --- a/apache-rat-core/src/test/java/org/apache/rat/testhelpers/data/OptionTestDataProvider.java +++ b/apache-rat-core/src/test/java/org/apache/rat/testhelpers/data/OptionTestDataProvider.java @@ -190,8 +190,7 @@ public class OptionTestDataProvider { DocumentName docName = validatorData.mkDocName(fname); assertThat(excluder.matches(docName)).as(() -> dump(option, fname, excluder, docName)).isFalse(); } - }) { - }; + }); return Collections.singletonList(test1); } diff --git a/apache-rat-core/src/test/java/org/apache/rat/testhelpers/data/ReportTestDataProvider.java b/apache-rat-core/src/test/java/org/apache/rat/testhelpers/data/ReportTestDataProvider.java index 82adb3d0..3c07b1dc 100644 --- a/apache-rat-core/src/test/java/org/apache/rat/testhelpers/data/ReportTestDataProvider.java +++ b/apache-rat-core/src/test/java/org/apache/rat/testhelpers/data/ReportTestDataProvider.java @@ -404,7 +404,7 @@ public class ReportTestDataProvider { }); // verify exclude removes the files - TestData test2 = new TestData("includeTestProof", Collections.singletonList(ImmutablePair.of(excludeOption, OptionTestDataProvider.EXCLUDE_ARGS)), + TestData test2 = new TestData(DataUtils.asDirName(option), Collections.singletonList(ImmutablePair.of(excludeOption, OptionTestDataProvider.EXCLUDE_ARGS)), setup, validatorData -> { assertThat(validatorData.getStatistic().getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(1); @@ -459,7 +459,7 @@ public class ReportTestDataProvider { ImmutablePair<Option, String[]> excludes = ImmutablePair.of(Arg.EXCLUDE.find("input-exclude"), new String[]{"*~more", "*~"}); - TestData test1 = new TestData("/includeStdValidation", Collections.singletonList(excludes), + TestData test1 = new TestData("includeStdValidation", Collections.singletonList(excludes), setup, validatorData -> { assertThat(validatorData.getStatistic().getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(4); @@ -1241,6 +1241,9 @@ public class ReportTestDataProvider { case UNAPPROVED_LICENSES: TextUtils.assertContainsExactly(1, "Files with unapproved licenses:" + System.lineSeparator() + " /Missing.java", actualText); break; + case XHTML5: + TextUtils.assertPatternInTarget("<td>Approved<\\/td>\\s+<td>1<\\/td>\\s+<td>A count of approved licenses.<\\/td>", actualText); + break; default: fail("No test for stylesheet " + sheet); break; diff --git a/apache-rat-core/src/test/java/org/apache/rat/testhelpers/data/TestData.java b/apache-rat-core/src/test/java/org/apache/rat/testhelpers/data/TestData.java index 5df4efe1..74e0bdbd 100644 --- a/apache-rat-core/src/test/java/org/apache/rat/testhelpers/data/TestData.java +++ b/apache-rat-core/src/test/java/org/apache/rat/testhelpers/data/TestData.java @@ -27,12 +27,14 @@ import java.util.function.Consumer; import org.apache.commons.cli.Option; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.Pair; +import org.apache.commons.text.WordUtils; +import org.apache.rat.ui.ArgumentTracker; import org.apache.rat.utils.CasedString; /** * The definition of a test. */ -public class TestData { +public final class TestData { /** if set, the expected exception from the test. */ private Exception expectedException; /** The sub name of the test */ @@ -48,13 +50,23 @@ public class TestData { * Constructs the Test data * @param name the sub name of the test. May not be {@code null} but may be an empty string. Should * be specified in Camel case for multiple words. - * @param commandLine The command line for the test. - * @param setupFiles the method to set up the files for the test. - * @param validator the validator for the results of the test. + * @param commandLine The command line for the test. May not be {@code null} but may consist of a single {@link ImmutablePair#nullPair()}. + * @param setupFiles the method to set up the files for the test. May not be {@code null}. + * @param validator the validator for the results of the test. May not be {@code null}. */ public TestData(String name, List<ImmutablePair<Option, String[]>> commandLine, Consumer<Path> setupFiles, Consumer<ValidatorData> validator) { + Objects.requireNonNull(name, " name cannot be null"); + Objects.requireNonNull(commandLine, "commandLine cannot be null"); + Objects.requireNonNull(setupFiles, "setupFiles cannot be null"); + Objects.requireNonNull(validator, "validator cannot be null"); + if (name.contains("/")) { + throw new IllegalArgumentException("name may not contain '/', use camel case instead"); + } + if (commandLine.isEmpty()) { + throw new IllegalArgumentException("commandLine may not be empty but contain an ImmutablePair.nullPair()"); + } this.name = name; this.commandLine = commandLine; this.setupFiles = setupFiles; @@ -172,17 +184,34 @@ public class TestData { * @return the unique test name */ public String getTestName() { - List<String> parts = new ArrayList<>(); + new ArrayList<>(); String result = null; if (getOption() == null) { result = name + "_DefaultTest"; } else { - parts.addAll(Arrays.asList(new CasedString(CasedString.StringCase.KEBAB, getOption().getLongOpt()).getSegments())); - result = CasedString.StringCase.CAMEL.assemble(parts.toArray(new String[0])); - if (name.length() > 0) { + result = new CasedString(CasedString.StringCase.KEBAB, ArgumentTracker.extractKey(getOption())).toString(); + if (!name.isEmpty()) { result += "/" + name; } } return result; } + + /** + * Gets the test name as a class name. This is based on the option concatenated with the name. + * @return the unique Java class name + */ + public String getClassName() { + String result = null; + if (getOption() == null) { + result = name + "_DefaultTest"; + } else { + List<String> parts = new ArrayList<>(Arrays.asList(new CasedString(CasedString.StringCase.KEBAB, ArgumentTracker.extractKey(getOption())).getSegments())); + if (!name.isEmpty()) { + parts.addAll(Arrays.asList(new CasedString(CasedString.StringCase.CAMEL, name).getSegments())); + } + result = CasedString.StringCase.CAMEL.assemble(parts.toArray(new String[0])); + } + return WordUtils.capitalize(result); + } } diff --git a/apache-rat-plugin-parent/impl/pom.xml b/apache-rat-plugin-parent/impl/pom.xml index 48cc1e69..8a91eda6 100644 --- a/apache-rat-plugin-parent/impl/pom.xml +++ b/apache-rat-plugin-parent/impl/pom.xml @@ -199,7 +199,7 @@ <argument>-t</argument> <argument>${project.build.testSourceDirectory}</argument> <argument>-r</argument> - <argument>${project.build.testSourceDirectory}/../resources</argument> + <argument>${project.build.testSourceDirectory}/../../resources</argument> <argument>-p</argument> <argument>org.apache.rat.maven</argument> </arguments> @@ -263,9 +263,22 @@ <directory>src/main/java/org/apache/rat/maven/</directory> <includes> <include>AbstractMaven.java</include> + <include>stubs/**</include> </includes> <followSymlinks>false</followSymlinks> </fileset> + <fileset> + <directory>src/test/java/org/apache/rat/maven/</directory> + <includes> + <include>MavenTest.java</include> + <include>stubs/**</include> + </includes> + <followSymlinks>false</followSymlinks> + </fileset> + <fileset> + <directory>src/test/resources/org/apache/rat/maven/stubs</directory> + <followSymlinks>false</followSymlinks> + </fileset> </filesets> </configuration> </plugin> diff --git a/apache-rat-plugin-parent/impl/src/main/java/org/apache/rat/maven/RatCheckMojo.java b/apache-rat-plugin-parent/impl/src/main/java/org/apache/rat/maven/RatCheckMojo.java index b4112320..d45ca0fa 100644 --- a/apache-rat-plugin-parent/impl/src/main/java/org/apache/rat/maven/RatCheckMojo.java +++ b/apache-rat-plugin-parent/impl/src/main/java/org/apache/rat/maven/RatCheckMojo.java @@ -55,9 +55,17 @@ import static java.lang.String.format; @Mojo(name = "check", defaultPhase = LifecyclePhase.VALIDATE, threadSafe = true) public final class RatCheckMojo extends AbstractRatMojo { + /** The output from the last {@link #execute()}. */ + private Reporter.Output output; + public RatCheckMojo() { super(); } + + public Reporter.Output getOutput() { + return output; + } + /** The default output file if no other is specified. */ @Parameter(defaultValue = "${project.build.directory}/rat.txt", readonly = true) private File defaultReportFile; @@ -102,12 +110,13 @@ public final class RatCheckMojo extends AbstractRatMojo { ReportConfiguration config = getConfiguration(); logLicenses(config.getLicenses(LicenseFilter.ALL)); if (verbose) { - config.reportExclusions(logWriter); + config.reportExclusions(logWoutput = reporter.execute(); + writeMojoRatReport(output); + iriter); } try { final Reporter reporter = new Reporter(config); - final Reporter.Output output = reporter.execute(); - writeMojoRatReport(output);if (verbose) { + f (verbose) { output.writeSummary(DefaultLog.getInstance().asWriter()); } // produce the requested output. diff --git a/apache-rat-plugin-parent/impl/src/main/java/org/apache/rat/maven/RatReportMojo.java b/apache-rat-plugin-parent/impl/src/main/java/org/apache/rat/maven/RatReportMojo.java index 2c29be6c..d7a3e7f7 100644 --- a/apache-rat-plugin-parent/impl/src/main/java/org/apache/rat/maven/RatReportMojo.java +++ b/apache-rat-plugin-parent/impl/src/main/java/org/apache/rat/maven/RatReportMojo.java @@ -18,7 +18,6 @@ */ package org.apache.rat.maven; -import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; @@ -412,7 +411,7 @@ public class RatReportMojo extends AbstractRatMojo implements MavenMultiPageRepo Reporter.Output readReportFile() throws MavenReportException { File f = new File(outputDirectory, ".rat.xml"); try (InputStream inputStream = new FileInputStream(f)) { - return new Reporter.Output(DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(inputStream)); + return Reporter.Output.builder().document(DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(inputStream)).build(); } catch (FileNotFoundException e) { throw new MavenReportException("Can not find RAT report file. Was reporter executed?"); } catch (IOException | ParserConfigurationException | SAXException e) { @@ -447,7 +446,6 @@ public class RatReportMojo extends AbstractRatMojo implements MavenMultiPageRepo sink.link(bundle.getString("report.rat.url")); sink.text(bundle.getString("report.rat.fullName")); sink.link_(); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); File f = new File(outputDirectory, ".rat.xhtml5"); try { readReportFile().format(StyleSheets.XHTML5.getStyleSheet(), () -> Files.newOutputStream(f.toPath())); diff --git a/apache-rat-plugin-parent/impl/src/test/java/org/apache/rat/maven/RatCheckMojoTest.java b/apache-rat-plugin-parent/impl/src/test/java/org/apache/rat/maven/RatCheckMojoTest.java new file mode 100644 index 00000000..9abbaac0 --- /dev/null +++ b/apache-rat-plugin-parent/impl/src/test/java/org/apache/rat/maven/RatCheckMojoTest.java @@ -0,0 +1,475 @@ +///* +// * 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.maven; +// +//import static java.lang.String.format; +//import static java.nio.charset.StandardCharsets.UTF_8; +//import static org.apache.rat.mp.RatTestHelpers.ensureRatReportIsCorrect; +//import static org.assertj.core.api.Assertions.assertThat; +//import static org.assertj.core.api.Fail.fail; +// +//import java.io.File; +// +//import java.io.IOException; +//import java.nio.file.Files; +//import java.nio.file.Path; +//import java.util.ArrayList; +//import java.util.Arrays; +//import java.util.HashMap; +//import java.util.List; +//import java.util.Map; +//import javax.xml.xpath.XPath; +//import javax.xml.xpath.XPathFactory; +//import org.apache.commons.io.FileUtils; +//import org.apache.rat.ReportConfiguration; +//import org.apache.rat.ReportConfigurationTest; +//import org.apache.rat.ReporterTestUtils; +//import org.apache.rat.api.Document; +//import org.apache.rat.commandline.Arg; +//import org.apache.rat.license.ILicenseFamily; +//import org.apache.rat.license.LicenseSetFactory; +//import org.apache.rat.license.LicenseSetFactory.LicenseFilter; +//import org.apache.rat.mp.OptionMojoTest; +//import org.apache.rat.report.claim.ClaimStatistic; +//import org.apache.rat.test.utils.Resources; +//import org.apache.rat.testhelpers.TextUtils; +//import org.apache.rat.testhelpers.XmlUtils; +//import org.junit.jupiter.api.AfterAll; +//import org.junit.jupiter.api.Assertions; +//import org.junit.jupiter.api.Test; +//import org.junit.jupiter.api.condition.EnabledOnOs; +//import org.junit.jupiter.api.condition.OS; +//import org.junit.jupiter.api.io.TempDir; +//import org.w3c.dom.NamedNodeMap; +//import org.w3c.dom.NodeList; +// +///** +// * Test case for the {@link RatCheckMojo} and {@link RatReportMojo}. +// */ +//public class RatCheckMojoTest { +// +// @TempDir +// static Path tempDir; +// +// private final static XPath xPath = XPathFactory.newInstance().newXPath(); +// +// @AfterAll +// @EnabledOnOs(OS.WINDOWS) +// static void cleanup() { +// System.gc(); // hacky workaround for windows bug. +// } +// +// private RatCheckMojo getMojo(File pomFile) throws IOException { +// try { +// final RatCheckMojo mojo = new OptionMojoTest.SimpleMojoTestcase() { +// }.getMojo(pomFile); +// Assertions.assertNotNull(mojo); +// return mojo; +// } catch (IOException e) { +// throw e; +// } catch (Exception e) { +// throw new IOException(format("Unable to generate mojo for %s", pomFile), e); +// } +// } +// +// /** +// * Creates a new instance of {@link AbstractRatMojo}. +// * +// * @param testDir The directory, where to look for a pom.xml file. +// * copy location. +// * @return The configured Mojo. +// * @throws Exception An error occurred while creating the Mojo. +// */ +// private RatCheckMojo newRatMojo(String testDir) throws Exception { +// Arg.reset(); +// final File sourceDir = Resources.getResourceDirectory(format("unit/%s", testDir)); +// final File baseDir = tempDir.resolve(testDir).toFile(); +// FileUtils.copyDirectory(sourceDir, baseDir); +// final File pomFile = new File(baseDir, "pom.xml"); +// RatCheckMojo mojo = getMojo(pomFile); +// assertThat(mojo).isNotNull(); +// assertThat(mojo.getProject()) +// .as("The mojo is missing its MavenProject, which will result in an NPE during RAT runs.") +// .isNotNull(); +// +// File buildDirectory = new File(baseDir, "target"); +// assertThat(buildDirectory.mkdirs()).isTrue(); +// final File ratTxtFile = new File(buildDirectory, "rat.txt"); +// FileUtils.write(ratTxtFile, "", UTF_8); // Ensure the output file exists and is empty (rerunning the test will append) +// mojo.setOutputFile(ratTxtFile.getAbsolutePath()); +// return mojo; +// } +// +// /** +// * Runs a check, which should expose no problems. +// * +// * @throws Exception The test failed. +// */ +// @Test +// void it1() throws Exception { +// final RatCheckMojo mojo = newRatMojo("it1"); +// final File ratTxtFile = mojo.getRatTxtFile(); +// +// ReportConfiguration config = mojo.getConfiguration(); +// ReportConfigurationTest.validateDefault(config); +// +// mojo.execute(); +// Map<ClaimStatistic.Counter, String> data = new HashMap<>(); +// data.put(ClaimStatistic.Counter.ARCHIVES, "0"); +// data.put(ClaimStatistic.Counter.APPROVED, "1"); +// data.put(ClaimStatistic.Counter.BINARIES, "0"); +// data.put(ClaimStatistic.Counter.DOCUMENT_TYPES, "2"); +// data.put(ClaimStatistic.Counter.IGNORED, "2"); +// data.put(ClaimStatistic.Counter.LICENSE_CATEGORIES, "1"); +// data.put(ClaimStatistic.Counter.LICENSE_NAMES, "1"); +// data.put(ClaimStatistic.Counter.NOTICES, "0"); +// data.put(ClaimStatistic.Counter.STANDARDS, "1"); +// data.put(ClaimStatistic.Counter.UNAPPROVED, "0"); +// data.put(ClaimStatistic.Counter.UNKNOWN, "0"); +// +// org.w3c.dom.Document document = XmlUtils.toDom(Files.newInputStream(ratTxtFile.toPath())); +// XPath xPath = XPathFactory.newInstance().newXPath(); +// +// for (ClaimStatistic.Counter counter : ClaimStatistic.Counter.values()) { +// String xpath = String.format("/rat-report/statistics/statistic[@name='%s']", counter.displayName()); +// Map<String, String> map = mapOf("approval", "true", "count", data.get(counter), +// "description", counter.getDescription()); +// XmlUtils.assertAttributes(document, xPath, xpath, map); +// } +// +// XmlUtils.assertAttributes(document, xPath, "/rat-report/resource[@name='/.bzrignore']", +// mapOf("mediaType", "application/octet-stream", "type", "IGNORED")); +// +// XmlUtils.assertAttributes(document, xPath, "/rat-report/resource[@name='/pom.xml']", +// mapOf("mediaType", "application/xml", "type", "STANDARD", "encoding", "ISO-8859-1")); +// } +// +// private static Map<String, String> mapOf(String... parts) { +// Map<String, String> map = new HashMap<>(); +// for (int i = 0; i < parts.length; i += 2) { +// map.put(parts[i], parts[i + 1]); +// } +// return map; +// } +// +// /** +// * Runs a check, which should detect a problem. +// * +// * @throws Exception The test failed. +// */ +// @Test +// void it2() throws Exception { +// final RatCheckMojo mojo = newRatMojo("it2"); +// final File ratTxtFile = mojo.getRatTxtFile(); +// final String[] expected = { +// "^Files with unapproved licenses\\s+\\*+\\s+\\Q/src.txt\\E\\s+", +// ReporterTestUtils.counterText(ClaimStatistic.Counter.NOTICES, 0, false), +// ReporterTestUtils.counterText(ClaimStatistic.Counter.BINARIES, 0, false), +// ReporterTestUtils.counterText(ClaimStatistic.Counter.ARCHIVES, 0, false), +// ReporterTestUtils.counterText(ClaimStatistic.Counter.STANDARDS, 2, false), +// ReporterTestUtils.counterText(ClaimStatistic.Counter.IGNORED, 1, false), +// ReporterTestUtils.apacheLicenseVersion2(1), +// ReporterTestUtils.unknownLicense(1), +// ReporterTestUtils.documentOut(false, Document.Type.STANDARD, "/src.txt") + +// ReporterTestUtils.UNKNOWN_LICENSE, +// ReporterTestUtils.documentOut(true, Document.Type.STANDARD, "/pom.xml") + +// ReporterTestUtils.APACHE_LICENSE +// }; +// try { +// mojo.execute(); +// fail("Expected RatCheckException"); +// } catch (RatCheckException e) { +// final String msg = e.getMessage(); +// assertThat(msg.contains(ratTxtFile.getName())).as(() -> format("report filename was not contained in '%s'", msg)) +// .isTrue(); +// assertThat(msg.toUpperCase()).contains("UNAPPROVED EXCEEDED MINIMUM"); +// +// ensureRatReportIsCorrect(ratTxtFile, expected, TextUtils.EMPTY); +// } +// } +// +// /** +// * Tests adding license headers. +// */ +// @Test +// void it3() throws Exception { +// final RatCheckMojo mojo = newRatMojo("it3"); +// final File ratTxtFile = mojo.getRatTxtFile(); +// +// ReportConfiguration config = mojo.getConfiguration(); +// assertThat(config.isAddingLicenses()).as("should be adding licenses").isTrue(); +// mojo.execute(); +// org.w3c.dom.Document document = XmlUtils.toDom(Files.newInputStream(ratTxtFile.toPath())); +// +// XmlUtils.assertAttributes(document, xPath, "/rat-report/resource[@name='/pom.xml']", "type", +// "STANDARD"); +// XmlUtils.assertAttributes(document, xPath, "/rat-report/resource[@name='/src.apt']", "type", +// "STANDARD"); +// XmlUtils.assertIsPresent(document, xPath, "/rat-report/resource[@name='/src.apt']/license[@approval='false']"); +// +// XmlUtils.assertAttributes(document, xPath, "/rat-report/resource[@name='/src.apt']", "type", +// "STANDARD"); +// +// for (Document.Type type : Document.Type.values()) { +// if (type == Document.Type.STANDARD) { +// XmlUtils.assertAttributes(document, xPath, "/rat-report/statistics/documentType[@name='STANDARD']", "count", +// "2"); +// } else if (type == Document.Type.IGNORED) { +// XmlUtils.assertAttributes(document, xPath, "/rat-report/statistics/documentType[@name='IGNORED']", "count", +// "1"); +// } else { +// XmlUtils.assertIsNotPresent(document, xPath, format("/rat-report/statistics/documentType[@name='%s']", type)); +// } +// } +// } +// +// /** +// * Tests defining licenses in configuration +// */ +// @Test +// void it5() throws Exception { +// final RatCheckMojo mojo = newRatMojo("it5"); +// final File ratTxtFile = mojo.getRatTxtFile(); +// +// ReportConfiguration config = mojo.getConfiguration(); +// assertThat(config.isAddingLicenses()).as("Should not be adding licenses").isFalse(); +// assertThat(config.isAddingLicensesForced()).as("Should not be forcing licenses").isFalse(); +// +// ReportConfigurationTest.validateDefaultApprovedLicenses(config, 1); +// assertThat(config.getLicenseCategories(LicenseFilter.APPROVED)).doesNotContain(ILicenseFamily.makeCategory("YAL")) +// .contains(ILicenseFamily.makeCategory("CC")); +// ReportConfigurationTest.validateDefaultLicenseFamilies(config, "YAL", "CC"); +// assertThat(LicenseSetFactory.familySearch("YAL", config.getLicenseFamilies(LicenseFilter.APPROVED))).isNull(); +// assertThat(LicenseSetFactory.familySearch("YAL", config.getLicenseFamilies(LicenseFilter.ALL))).isNotNull(); +// assertThat(LicenseSetFactory.familySearch("CC", config.getLicenseFamilies(LicenseFilter.APPROVED))).isNotNull(); +// assertThat(LicenseSetFactory.familySearch("CC", config.getLicenseFamilies(LicenseFilter.ALL))).isNotNull(); +// +// ReportConfigurationTest.validateDefaultLicenses(config, "CC-BY-NC-ND", "YAL"); +// assertThat(LicenseSetFactory.search("YAL", "YAL", config.getLicenses(LicenseFilter.ALL))).isPresent(); +// +// mojo.execute(); +// +// Map<ClaimStatistic.Counter, String> data = new HashMap<>(); +// data.put(ClaimStatistic.Counter.APPROVED, "1"); +// data.put(ClaimStatistic.Counter.ARCHIVES, "0"); +// data.put(ClaimStatistic.Counter.BINARIES, "0"); +// data.put(ClaimStatistic.Counter.DOCUMENT_TYPES, "2"); +// data.put(ClaimStatistic.Counter.IGNORED, "3"); +// data.put(ClaimStatistic.Counter.LICENSE_CATEGORIES, "1"); +// data.put(ClaimStatistic.Counter.LICENSE_NAMES, "1"); +// data.put(ClaimStatistic.Counter.NOTICES, "0"); +// data.put(ClaimStatistic.Counter.STANDARDS, "1"); +// data.put(ClaimStatistic.Counter.UNAPPROVED, "0"); +// data.put(ClaimStatistic.Counter.UNKNOWN, "0"); +// +// org.w3c.dom.Document document = XmlUtils.toDom(Files.newInputStream(ratTxtFile.toPath())); +// XPath xPath = XPathFactory.newInstance().newXPath(); +// +// for (ClaimStatistic.Counter counter : ClaimStatistic.Counter.values()) { +// String xpath = String.format("/rat-report/statistics/statistic[@name='%s']", counter.displayName()); +// Map<String, String> map = mapOf("approval", +// "true", +// "count", data.get(counter), +// "description", counter.getDescription()); +// XmlUtils.assertAttributes(document, xPath, xpath, map); +// } +// +// XmlUtils.assertAttributes(document, xPath, "/rat-report/resource[@name='/.rat']", +// "mediaType", "application/octet-stream", "type", "IGNORED", "isDirectory", "true"); +// XmlUtils.assertAttributes(document, xPath, "/rat-report/resource[@name='/pom.xml']", +// "mediaType", "application/xml", "type", "IGNORED", "isDirectory", "false"); +// XmlUtils.assertAttributes(document, xPath, "/rat-report/resource[@name='/src/main/java/nl/basjes/something/Something.java']", +// "mediaType", "text/x-java-source", "type", "STANDARD", "encoding", "ISO-8859-1"); +// XmlUtils.assertAttributes(document, xPath, "/rat-report/resource[@name='/src/main/java/nl/basjes/something/Something.java']/license", +// "approval", "true", "family", ILicenseFamily.makeCategory("CC"), "id", "CC-BY-NC-ND", "name", +// "Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International"); +// } +// +// /** +// * Runs a check, which should expose no problems. +// * +// * @throws Exception The test failed. +// */ +// @Test +// void rat343() throws Exception { +// final RatCheckMojo mojo = newRatMojo("RAT-343"); +// final File ratTxtFile = mojo.getRatTxtFile(); +// // POM reports AL, BSD and CC BYas BSD because it contains the BSD and CC BY strings +// final String[] expected = { +// ReporterTestUtils.documentOut(false, Document.Type.STANDARD, "/pom.xml") + +// ReporterTestUtils.APACHE_LICENSE + +// ReporterTestUtils.licenseOut("BSD", "BSD") + +// ReporterTestUtils.licenseOut("CC BY", "Creative Commons Attribution (Unapproved)"), +// ReporterTestUtils.counterText(ClaimStatistic.Counter.NOTICES, 0, false), +// ReporterTestUtils.counterText(ClaimStatistic.Counter.BINARIES, 0, false), +// ReporterTestUtils.counterText(ClaimStatistic.Counter.ARCHIVES, 0, false), +// ReporterTestUtils.counterText(ClaimStatistic.Counter.STANDARDS, 1, false), +// ReporterTestUtils.counterText(ClaimStatistic.Counter.IGNORED, 1, false), +// ReporterTestUtils.apacheLicenseVersion2(1), +// "^BSD: 1 ", +// "^Creative Commons Attribution: 1 ", +// }; +// final String[] notExpected = { +// "^Unknown License:" +// }; +// +// ReportConfiguration config = mojo.getConfiguration(); +// // validate configuration +// assertThat(config.isAddingLicenses()).isFalse(); +// assertThat(config.isAddingLicensesForced()).isFalse(); +// assertThat(config.getCopyrightMessage()).isNull(); +// assertThat(config.getStyleSheet()).withFailMessage("Stylesheet should not be null").isNotNull(); +// +// ReportConfigurationTest.validateDefaultApprovedLicenses(config, 1); +// ReportConfigurationTest.validateDefaultLicenseFamilies(config, "BSD", "CC BY"); +// ReportConfigurationTest.validateDefaultLicenses(config, "BSD", "CC BY"); +// +// mojo.execute(); +// ensureRatReportIsCorrect(ratTxtFile, expected, notExpected); +// } +// +// /** +// * Tests verifying gitignore parsing +// */ +// @Test +// void rat335() throws Exception { +// final RatCheckMojo mojo = newRatMojo("RAT-335"); +// final File ratTxtFile = mojo.getRatTxtFile(); +// try { +// mojo.execute(); +// fail("Expected RatCheckException"); +// } catch (RatCheckException e) { +// final String msg = e.getMessage(); +// assertThat(msg).contains(ratTxtFile.getName()); +// assertThat(msg).contains("UNAPPROVED exceeded minimum"); +// +// Map<ClaimStatistic.Counter, String> data = new HashMap<>(); +// data.put(ClaimStatistic.Counter.APPROVED, "1"); +// data.put(ClaimStatistic.Counter.ARCHIVES, "0"); +// data.put(ClaimStatistic.Counter.BINARIES, "0"); +// data.put(ClaimStatistic.Counter.DOCUMENT_TYPES, "3"); +// data.put(ClaimStatistic.Counter.IGNORED, "6"); +// data.put(ClaimStatistic.Counter.LICENSE_CATEGORIES, "2"); +// data.put(ClaimStatistic.Counter.LICENSE_NAMES, "2"); +// data.put(ClaimStatistic.Counter.NOTICES, "1"); +// data.put(ClaimStatistic.Counter.STANDARDS, "5"); +// data.put(ClaimStatistic.Counter.UNAPPROVED, "4"); +// data.put(ClaimStatistic.Counter.UNKNOWN, "4"); +// +// org.w3c.dom.Document document = XmlUtils.toDom(Files.newInputStream(ratTxtFile.toPath())); +// +// for (ClaimStatistic.Counter counter : ClaimStatistic.Counter.values()) { +// String xpath = String.format("/rat-report/statistics/statistic[@name='%s']", counter.displayName()); +// Map<String, String> map = mapOf("approval", +// counter == ClaimStatistic.Counter.UNAPPROVED ? "false" : "true", +// "count", data.get(counter), +// "description", counter.getDescription()); +// XmlUtils.assertAttributes(document, xPath, xpath, map); +// } +// +// // license categories +// XmlUtils.assertAttributes(document, xPath, "/rat-report/statistics/licenseCategory[@name='?????']", +// mapOf("count", "4")); +// +// XmlUtils.assertAttributes(document, xPath, "/rat-report/statistics/licenseCategory[@name='AL ']", +// mapOf("count", "1")); +// +// // license names +// XmlUtils.assertAttributes(document, xPath, "/rat-report/statistics/licenseName[@name='Apache License 2.0']", +// mapOf("count", "1")); +// +// XmlUtils.assertAttributes(document, xPath, "/rat-report/statistics/licenseName[@name='Unknown license']", +// mapOf("count", "4")); +// +// // Document types +// XmlUtils.assertAttributes(document, xPath, "/rat-report/statistics/documentType[@name='IGNORED']", +// mapOf("count", "6")); +// +// XmlUtils.assertAttributes(document, xPath, "/rat-report/statistics/documentType[@name='NOTICE']", +// mapOf("count", "1")); +// +// XmlUtils.assertAttributes(document, xPath, "/rat-report/statistics/documentType[@name='STANDARD']", +// mapOf("count", "5")); +// +// List<String> ignoredFiles = new ArrayList<>(Arrays.asList( +// "/dir1/dir1.txt", +// "/dir1/.gitignore", +// "/dir2/dir2.md", +// "/dir3/dir3.log", +// "/.gitignore", +// "/root.md")); +// +// NodeList nodeList = XmlUtils.getNodeList(document, xPath, "/rat-report/resource[@type='IGNORED']"); +// for (int i = 0; i < nodeList.getLength(); i++) { +// NamedNodeMap attr = nodeList.item(i).getAttributes(); +// String s = attr.getNamedItem("name").getNodeValue(); +// assertThat(ignoredFiles).contains(s); +// ignoredFiles.remove(s); +// } +// assertThat(ignoredFiles).isEmpty(); +// } +// } +// +// /** +// * Tests verifying gitignore parsing under a special edge case condition +// * The problem occurs when '/foo.md' is to be ignored and a file with that name exists +// * in a directory which is the project base directory twice concatenated. +// * So for this test we must create such a file which is specific for the current +// * working directory. +// */ +// @Test +// void rat362() throws Exception { +// final RatCheckMojo mojo = newRatMojo("RAT-362"); +// final File ratTxtFile = mojo.getRatTxtFile(); +// try { +// mojo.execute(); +// fail("Expected RatCheckException"); +// } catch (RatCheckException e) { +// final String msg = e.getMessage(); +// assertThat(msg).contains(ratTxtFile.getName()); +// assertThat(msg).contains("UNAPPROVED exceeded minimum"); +// +// org.w3c.dom.Document document = XmlUtils.toDom(Files.newInputStream(ratTxtFile.toPath())); +// // Document types +// XmlUtils.assertAttributes(document, xPath, "/rat-report/statistics/documentType[@name='IGNORED']", +// "count", "3"); +// +// XmlUtils.assertAttributes(document, xPath, "/rat-report/resource[@name='/bar.md']", +// "type", "STANDARD"); +// XmlUtils.assertAttributes(document, xPath, "/rat-report/resource[@name='/foo.md']", +// "type", "IGNORED"); +// } +// } +// +// /** +// * Tests implicit excludes apply to submodules too +// */ +// @Test +// void rat107() throws Exception { +// final RatCheckMojo mojo = newRatMojo("RAT-107"); +// final File ratTxtFile = mojo.getRatTxtFile(); +// final String[] expected = {}; +// final String[] notExpected = {}; +// //setVariableValueToObject(mojo, "excludeSubProjects", Boolean.FALSE); +// mojo.setInputExcludeParsedScm("MAVEN"); +// mojo.setInputExcludeParsedScm("idea"); +// mojo.setInputExcludeParsedScm("eclipse"); +// mojo.execute(); +// +// ensureRatReportIsCorrect(ratTxtFile, expected, notExpected); +// } +//} diff --git a/apache-rat-plugin-parent/impl/src/test/java/org/apache/rat/maven/SettingsStub.java b/apache-rat-plugin-parent/impl/src/test/java/org/apache/rat/maven/SettingsStub.java new file mode 100644 index 00000000..32961756 --- /dev/null +++ b/apache-rat-plugin-parent/impl/src/test/java/org/apache/rat/maven/SettingsStub.java @@ -0,0 +1,16 @@ +package org.apache.rat.maven; + +import java.util.Collections; +import java.util.List; +import org.apache.maven.settings.Proxy; +import org.apache.maven.settings.Settings; + +public class SettingsStub + extends Settings +{ + /** {@inheritDoc} */ + public List<Proxy> getProxies() + { + return Collections.EMPTY_LIST; + } +} diff --git a/apache-rat-plugin-parent/impl/src/test/java/org/apache/rat/mp/BetterAbstractMojoTestCase.java b/apache-rat-plugin-parent/impl/src/test/java/org/apache/rat/mp/BetterAbstractMojoTestCase.java index 0f8db5a0..530319c2 100644 --- a/apache-rat-plugin-parent/impl/src/test/java/org/apache/rat/mp/BetterAbstractMojoTestCase.java +++ b/apache-rat-plugin-parent/impl/src/test/java/org/apache/rat/mp/BetterAbstractMojoTestCase.java @@ -1,125 +1,125 @@ - -/* - * 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. - * -* - * This software is copyright (c) 2015 by Alex Heneveld and Cloudsoft Corporation. - * - * code lifted from https://github.com/ahgittin/license-audit-maven-plugin - */ -package org.apache.rat.mp; - -import java.io.File; -import java.util.Arrays; - -import org.apache.maven.DefaultMaven; -import org.apache.maven.Maven; -import org.apache.maven.execution.DefaultMavenExecutionRequest; -import org.apache.maven.execution.DefaultMavenExecutionResult; -import org.apache.maven.execution.MavenExecutionRequest; -import org.apache.maven.execution.MavenExecutionRequestPopulator; -import org.apache.maven.execution.MavenExecutionResult; -import org.apache.maven.execution.MavenSession; -import org.apache.maven.plugin.Mojo; -import org.apache.maven.plugin.testing.AbstractMojoTestCase; -import org.apache.maven.project.MavenProject; -import org.apache.maven.project.ProjectBuilder; -import org.apache.maven.project.ProjectBuildingRequest; -import org.eclipse.aether.DefaultRepositorySystemSession; -import org.eclipse.aether.internal.impl.SimpleLocalRepositoryManagerFactory; -import org.eclipse.aether.repository.LocalRepository; - -/** - * Use this as you would {@link AbstractMojoTestCase}, where you want more of - * the standard maven defaults to be set (and where the - * {@link AbstractMojoTestCase} leaves them as null or empty). This includes: - * <li>local repo, repo sessions and managers configured - * <li>maven default remote repos installed (NB: this does not use your ~/.m2 - * local settings) - * <li>system properties are copies - * <p> - * No changes to subclass code is needed; this simply intercepts the - * {@link #newMavenSession(MavenProject)} method used by the various - * {@link #lookupMojo(String, File)} methods. - * <p> - * This also provides new methods, {@link #newMavenSession()} to conveniently - * create a maven session, and {@link #lookupConfiguredMojo(File, String)} so - * you don't have to always build the project yourself. - */ -public abstract class BetterAbstractMojoTestCase extends AbstractMojoTestCase { - - protected MavenSession newMavenSession() { - try { - MavenExecutionRequest request = new DefaultMavenExecutionRequest(); - MavenExecutionResult result = new DefaultMavenExecutionResult(); - - // populate sensible defaults, including repository basedir and remote repos - MavenExecutionRequestPopulator populator; - populator = getContainer().lookup(MavenExecutionRequestPopulator.class); - populator.populateDefaults(request); - - // this is needed to allow java profiles to get resolved; i.e. avoid during - // project builds: - // [ERROR] Failed to determine Java version for profile java-1.5-detected @ - // org.apache.commons:commons-parent:22, - // /Users/alex/.m2/repository/org/apache/commons/commons-parent/22/commons-parent-22.pom, - // line 909, column 14 - request.setSystemProperties(System.getProperties()); - - // and this is needed so that the repo session in the maven session - // has a repo manager, and it points at the local repo - // (cf MavenRepositorySystemUtils.newSession() which is what is otherwise done) - DefaultMaven maven = (DefaultMaven) getContainer().lookup(Maven.class); - DefaultRepositorySystemSession repoSession = (DefaultRepositorySystemSession) maven - .newRepositorySession(request); - repoSession.setLocalRepositoryManager(new SimpleLocalRepositoryManagerFactory().newInstance(repoSession, - new LocalRepository(request.getLocalRepository().getBasedir()))); - - return new MavenSession(getContainer(), repoSession, request, result); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - /** - * Extends the super to use the new {@link #newMavenSession()} introduced here - * which sets the defaults one expects from maven; the standard test case leaves - * a lot of things blank - */ - @Override - protected MavenSession newMavenSession(MavenProject project) { - MavenSession session = newMavenSession(); - session.setCurrentProject(project); - session.setProjects(Arrays.asList(project)); - return session; - } - - /** - * As {@link #lookupConfiguredMojo(MavenProject, String)} but taking the pom - * file and creating the {@link MavenProject}. - */ - protected Mojo lookupConfiguredMojo(File pom, String goal) throws Exception { - assertNotNull(pom); - assertTrue(pom.exists()); - - ProjectBuildingRequest buildingRequest = newMavenSession().getProjectBuildingRequest(); - ProjectBuilder projectBuilder = lookup(ProjectBuilder.class); - MavenProject project = projectBuilder.build(pom, buildingRequest).getProject(); - - return lookupConfiguredMojo(project, goal); - } - -} +// +///* +// * 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. +// * +//* +// * This software is copyright (c) 2015 by Alex Heneveld and Cloudsoft Corporation. +// * +// * code lifted from https://github.com/ahgittin/license-audit-maven-plugin +// */ +//package org.apache.rat.mp; +// +//import java.io.File; +//import java.util.Arrays; +// +//import org.apache.maven.DefaultMaven; +//import org.apache.maven.Maven; +//import org.apache.maven.execution.DefaultMavenExecutionRequest; +//import org.apache.maven.execution.DefaultMavenExecutionResult; +//import org.apache.maven.execution.MavenExecutionRequest; +//import org.apache.maven.execution.MavenExecutionRequestPopulator; +//import org.apache.maven.execution.MavenExecutionResult; +//import org.apache.maven.execution.MavenSession; +//import org.apache.maven.plugin.Mojo; +//import org.apache.maven.plugin.testing.AbstractMojoTestCase; +//import org.apache.maven.project.MavenProject; +//import org.apache.maven.project.ProjectBuilder; +//import org.apache.maven.project.ProjectBuildingRequest; +//import org.eclipse.aether.DefaultRepositorySystemSession; +//import org.eclipse.aether.internal.impl.SimpleLocalRepositoryManagerFactory; +//import org.eclipse.aether.repository.LocalRepository; +// +///** +// * Use this as you would {@link AbstractMojoTestCase}, where you want more of +// * the standard maven defaults to be set (and where the +// * {@link AbstractMojoTestCase} leaves them as null or empty). This includes: +// * <li>local repo, repo sessions and managers configured +// * <li>maven default remote repos installed (NB: this does not use your ~/.m2 +// * local settings) +// * <li>system properties are copies +// * <p> +// * No changes to subclass code is needed; this simply intercepts the +// * {@link #newMavenSession(MavenProject)} method used by the various +// * {@link #lookupMojo(String, File)} methods. +// * <p> +// * This also provides new methods, {@link #newMavenSession()} to conveniently +// * create a maven session, and {@link #lookupConfiguredMojo(File, String)} so +// * you don't have to always build the project yourself. +// */ +//public abstract class BetterAbstractMojoTestCase extends AbstractMojoTestCase { +// +// protected MavenSession newMavenSession() { +// try { +// MavenExecutionRequest request = new DefaultMavenExecutionRequest(); +// MavenExecutionResult result = new DefaultMavenExecutionResult(); +// +// // populate sensible defaults, including repository basedir and remote repos +// MavenExecutionRequestPopulator populator; +// populator = getContainer().lookup(MavenExecutionRequestPopulator.class); +// populator.populateDefaults(request); +// +// // this is needed to allow java profiles to get resolved; i.e. avoid during +// // project builds: +// // [ERROR] Failed to determine Java version for profile java-1.5-detected @ +// // org.apache.commons:commons-parent:22, +// // /Users/alex/.m2/repository/org/apache/commons/commons-parent/22/commons-parent-22.pom, +// // line 909, column 14 +// request.setSystemProperties(System.getProperties()); +// +// // and this is needed so that the repo session in the maven session +// // has a repo manager, and it points at the local repo +// // (cf MavenRepositorySystemUtils.newSession() which is what is otherwise done) +// DefaultMaven maven = (DefaultMaven) getContainer().lookup(Maven.class); +// DefaultRepositorySystemSession repoSession = (DefaultRepositorySystemSession) maven +// .newRepositorySession(request); +// repoSession.setLocalRepositoryManager(new SimpleLocalRepositoryManagerFactory().newInstance(repoSession, +// new LocalRepository(request.getLocalRepository().getBasedir()))); +// +// return new MavenSession(getContainer(), repoSession, request, result); +// } catch (Exception e) { +// throw new RuntimeException(e); +// } +// } +// +// /** +// * Extends the super to use the new {@link #newMavenSession()} introduced here +// * which sets the defaults one expects from maven; the standard test case leaves +// * a lot of things blank +// */ +// @Override +// protected MavenSession newMavenSession(MavenProject project) { +// MavenSession session = newMavenSession(); +// session.setCurrentProject(project); +// session.setProjects(Arrays.asList(project)); +// return session; +// } +// +// /** +// * As {@link #lookupConfiguredMojo(MavenProject, String)} but taking the pom +// * file and creating the {@link MavenProject}. +// */ +// protected Mojo lookupConfiguredMojo(File pom, String goal) throws Exception { +// assertNotNull(pom); +// assertTrue(pom.exists()); +// +// ProjectBuildingRequest buildingRequest = newMavenSession().getProjectBuildingRequest(); +// ProjectBuilder projectBuilder = lookup(ProjectBuilder.class); +// MavenProject project = projectBuilder.build(pom, buildingRequest).getProject(); +// +// return lookupConfiguredMojo(project, goal); +// } +// +//} diff --git a/apache-rat-plugin-parent/impl/src/test/java/org/apache/rat/mp/MavenOption.java b/apache-rat-plugin-parent/impl/src/test/java/org/apache/rat/mp/MavenOption.java index 7ac495c8..da4f64f5 100644 --- a/apache-rat-plugin-parent/impl/src/test/java/org/apache/rat/mp/MavenOption.java +++ b/apache-rat-plugin-parent/impl/src/test/java/org/apache/rat/mp/MavenOption.java @@ -1,91 +1,91 @@ -/* - * 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.mp; - -import org.apache.commons.cli.Option; -import org.apache.rat.plugin.BaseRatMojo; - -import static java.lang.String.format; - -/** - * A wrapper on Option to provide access to Option info with Maven nomenclature and formatting. - */ -public class MavenOption { - final Option option; - final String name; - - /** - * Constructor. - * @param option The CLI option - */ - MavenOption(Option option) { - this.option = option; - this.name = BaseRatMojo.createName(option.getLongOpt()); - } - - /** - * Returns the value as an POM xml node. - * @param value the value - * @return the pom xml node. - */ - public String xmlNode(String value) { - return format("<%1$s>%2$s</%1$s>%n", name, value==null ? "false" : value); - } - - /** - * Returns true if the option should be an attribute. - * @return {@code true} if the option should be an attribute - */ - public boolean isAttribute() { - return (!option.hasArgs()); - } - - /** - * Returns true if the option should be an element. - * @return {@code true} if the option should be an element. - */ - public boolean isElement() { - return !isAttribute() || option.getType() != String.class; - } - - /** - * Gets the simple class name for the data type for this option. - * Normally "String". - * @return the simple class name for the type. - */ - public String getType() { - return ((Class<?>) option.getType()).getSimpleName(); - } - - /** - * Determine if true if the enclosed option expects an argument. - * @return {@code true} if the enclosed option expects at least one argument. - */ - public boolean hasArg() { - return option.hasArg(); - } - - /** - * the key value for the option. - * @return the key value for the CLI argument map. - */ - public String keyValue() { - return option.getLongOpt(); - } -} +///* +// * 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.mp; +// +//import org.apache.commons.cli.Option; +//import org.apache.rat.plugin.BaseRatMojo; +// +//import static java.lang.String.format; +// +///** +// * A wrapper on Option to provide access to Option info with Maven nomenclature and formatting. +// */ +//public class MavenOption { +// final Option option; +// final String name; +// +// /** +// * Constructor. +// * @param option The CLI option +// */ +// MavenOption(Option option) { +// this.option = option; +// this.name = BaseRatMojo.createName(option.getLongOpt()); +// } +// +// /** +// * Returns the value as an POM xml node. +// * @param value the value +// * @return the pom xml node. +// */ +// public String xmlNode(String value) { +// return format("<%1$s>%2$s</%1$s>%n", name, value==null ? "false" : value); +// } +// +// /** +// * Returns true if the option should be an attribute. +// * @return {@code true} if the option should be an attribute +// */ +// public boolean isAttribute() { +// return (!option.hasArgs()); +// } +// +// /** +// * Returns true if the option should be an element. +// * @return {@code true} if the option should be an element. +// */ +// public boolean isElement() { +// return !isAttribute() || option.getType() != String.class; +// } +// +// /** +// * Gets the simple class name for the data type for this option. +// * Normally "String". +// * @return the simple class name for the type. +// */ +// public String getType() { +// return ((Class<?>) option.getType()).getSimpleName(); +// } +// +// /** +// * Determine if true if the enclosed option expects an argument. +// * @return {@code true} if the enclosed option expects at least one argument. +// */ +// public boolean hasArg() { +// return option.hasArg(); +// } +// +// /** +// * the key value for the option. +// * @return the key value for the CLI argument map. +// */ +// public String keyValue() { +// return option.getLongOpt(); +// } +//} diff --git a/apache-rat-plugin-parent/impl/src/test/java/org/apache/rat/mp/OptionMojoTest.java b/apache-rat-plugin-parent/impl/src/test/java/org/apache/rat/mp/OptionMojoTest.java index bc77a78f..352e5eff 100644 --- a/apache-rat-plugin-parent/impl/src/test/java/org/apache/rat/mp/OptionMojoTest.java +++ b/apache-rat-plugin-parent/impl/src/test/java/org/apache/rat/mp/OptionMojoTest.java @@ -1,172 +1,172 @@ -/* - * 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.mp; - -import org.apache.commons.cli.Option; -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang3.tuple.Pair; -import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.project.MavenProject; -import org.apache.maven.project.ProjectBuilder; -import org.apache.maven.project.ProjectBuildingRequest; -import org.apache.rat.maven.RatCheckMojo; -import org.apache.rat.test.AbstractConfigurationOptionsProvider; -import org.apache.rat.OptionCollectionTest; -import org.apache.rat.ReportConfiguration; -import org.apache.rat.plugin.BaseRatMojo; -import org.apache.rat.utils.DefaultLog; -import org.codehaus.plexus.component.configurator.ComponentConfigurationException; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.condition.EnabledOnOs; -import org.junit.jupiter.api.condition.OS; -import org.junit.jupiter.api.io.TempDir; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ArgumentsProvider; -import org.junit.jupiter.params.provider.ArgumentsSource; - -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.lang.reflect.Method; -import java.nio.charset.StandardCharsets; -import java.nio.file.Path; -import java.util.ArrayList; -import java.util.List; - -import static java.lang.String.format; -import static org.junit.jupiter.api.Assertions.fail; - - -public class OptionMojoTest { - - @TempDir - static Path testPath; - - static String POM_FMT; - - @BeforeAll - public static void makeDirs() throws IOException { - POM_FMT = IOUtils.resourceToString("/optionTest/pom.tpl", StandardCharsets.UTF_8); - } - - @AfterAll - static void preserveData() { - AbstractConfigurationOptionsProvider.preserveData(testPath.toFile(), "optionTest"); - } - - /** - * This method is a known workaround for - * {@link <a href="https://github.com/junit-team/junit5/issues/2811">junit 5 issue #2811</a> }. - */ - @AfterEach - @EnabledOnOs(OS.WINDOWS) - void cleanUp() { - System.gc(); - } - - @ParameterizedTest - @ArgumentsSource(MojoOptionsProvider.class) - void testOptionsUpdateConfig(String name, OptionCollectionTest.OptionTest test) { - DefaultLog.getInstance().info("Running " + name); - test.test(); - } - - static class MojoOptionsProvider extends AbstractConfigurationOptionsProvider implements ArgumentsProvider { - - private RatCheckMojo mojo = null; - - public MojoOptionsProvider() { - super(BaseRatMojo.unsupportedArgs(), testPath.toFile()); - } - - private RatCheckMojo generateMojo(List<Pair<Option, String[]>> args) throws IOException { - MavenOption keyOption = new MavenOption(args.get(0).getKey() == null ? - Option.builder().longOpt("no-option").build() : - args.get(0).getKey()); - List<String> mavenOptions = new ArrayList<>(); - for (Pair<Option, String[]> pair : args) { - if (pair.getKey() != null) { - String[] values = pair.getValue(); - if (values != null) { - for (String value : values) { - mavenOptions.add(new MavenOption(pair.getKey()).xmlNode(value)); - } - } else { - mavenOptions.add(new MavenOption(pair.getKey()).xmlNode("true")); - } - } - } - // StringBuilder develops the core pom commands. - StringBuilder sb = new StringBuilder(); - mavenOptions.forEach(sb::append); - Path pomPath = testPath.resolve(keyOption.name).resolve("pom.xml"); - File pomFile = pomPath.toFile(); - pomFile.getParentFile().mkdirs(); - try (FileWriter writer = new FileWriter(pomFile)) { - writer.append(format(POM_FMT, keyOption.name, sb)); - writer.flush(); - } - try { - final RatCheckMojo mojo = new SimpleMojoTestcase(){}.getMojo(pomFile); - Assertions.assertNotNull(mojo); - return mojo; - } catch (IOException e) { - throw e; - } catch (Exception e) { - throw new IOException(format("Unable to generate mojo for %s (%s)", keyOption.name, keyOption), e); - } - } - - @Override - protected final ReportConfiguration generateConfig(List<Pair<Option, String[]>> args) throws IOException { - try { - this.mojo = generateMojo(args); - AbstractConfigurationOptionsProvider.setup(this.mojo.getProject().getBasedir()); - return mojo.getConfiguration(); - } catch (MojoExecutionException e) { - throw new IOException(e.getMessage(), e); - } - } - - @Override - protected void helpTest() { - fail("Should not call help"); - } - } - - public abstract static class SimpleMojoTestcase extends BetterAbstractMojoTestCase { - public RatCheckMojo getMojo(File pomFile) throws Exception { - setUp(); - ProjectBuildingRequest buildingRequest = newMavenSession().getProjectBuildingRequest(); - ProjectBuilder projectBuilder = lookup(ProjectBuilder.class); - MavenProject project = projectBuilder.build(pomFile, buildingRequest).getProject(); - try { - return (RatCheckMojo) lookupConfiguredMojo(project, "check"); - } catch (ComponentConfigurationException e) { - for (Method m : RatCheckMojo.class.getMethods()) { - System.out.println( m ); - } - throw e; - } - } - } -} +///* +// * 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.mp; +// +//import org.apache.commons.cli.Option; +//import org.apache.commons.io.IOUtils; +//import org.apache.commons.lang3.tuple.Pair; +//import org.apache.maven.plugin.MojoExecutionException; +//import org.apache.maven.project.MavenProject; +//import org.apache.maven.project.ProjectBuilder; +//import org.apache.maven.project.ProjectBuildingRequest; +//import org.apache.rat.maven.RatCheckMojo; +//import org.apache.rat.test.AbstractConfigurationOptionsProvider; +//import org.apache.rat.OptionCollectionTest; +//import org.apache.rat.ReportConfiguration; +//import org.apache.rat.plugin.BaseRatMojo; +//import org.apache.rat.utils.DefaultLog; +//import org.codehaus.plexus.component.configurator.ComponentConfigurationException; +//import org.junit.jupiter.api.AfterAll; +//import org.junit.jupiter.api.AfterEach; +//import org.junit.jupiter.api.Assertions; +//import org.junit.jupiter.api.BeforeAll; +//import org.junit.jupiter.api.condition.EnabledOnOs; +//import org.junit.jupiter.api.condition.OS; +//import org.junit.jupiter.api.io.TempDir; +//import org.junit.jupiter.params.ParameterizedTest; +//import org.junit.jupiter.params.provider.ArgumentsProvider; +//import org.junit.jupiter.params.provider.ArgumentsSource; +// +//import java.io.File; +//import java.io.FileWriter; +//import java.io.IOException; +//import java.lang.reflect.Method; +//import java.nio.charset.StandardCharsets; +//import java.nio.file.Path; +//import java.util.ArrayList; +//import java.util.List; +// +//import static java.lang.String.format; +//import static org.junit.jupiter.api.Assertions.fail; +// +// +//public class OptionMojoTest { +// +// @TempDir +// static Path testPath; +// +// static String POM_FMT; +// +// @BeforeAll +// public static void makeDirs() throws IOException { +// POM_FMT = IOUtils.resourceToString("/optionTest/pom.tpl", StandardCharsets.UTF_8); +// } +// +// @AfterAll +// static void preserveData() { +// AbstractConfigurationOptionsProvider.preserveData(testPath.toFile(), "optionTest"); +// } +// +// /** +// * This method is a known workaround for +// * {@link <a href="https://github.com/junit-team/junit5/issues/2811">junit 5 issue #2811</a> }. +// */ +// @AfterEach +// @EnabledOnOs(OS.WINDOWS) +// void cleanUp() { +// System.gc(); +// } +// +// @ParameterizedTest +// @ArgumentsSource(MojoOptionsProvider.class) +// void testOptionsUpdateConfig(String name, OptionCollectionTest.OptionTest test) { +// DefaultLog.getInstance().info("Running " + name); +// test.test(); +// } +// +// static class MojoOptionsProvider extends AbstractConfigurationOptionsProvider implements ArgumentsProvider { +// +// private RatCheckMojo mojo = null; +// +// public MojoOptionsProvider() { +// super(BaseRatMojo.unsupportedArgs(), testPath.toFile()); +// } +// +// private RatCheckMojo generateMojo(List<Pair<Option, String[]>> args) throws IOException { +// MavenOption keyOption = new MavenOption(args.get(0).getKey() == null ? +// Option.builder().longOpt("no-option").build() : +// args.get(0).getKey()); +// List<String> mavenOptions = new ArrayList<>(); +// for (Pair<Option, String[]> pair : args) { +// if (pair.getKey() != null) { +// String[] values = pair.getValue(); +// if (values != null) { +// for (String value : values) { +// mavenOptions.add(new MavenOption(pair.getKey()).xmlNode(value)); +// } +// } else { +// mavenOptions.add(new MavenOption(pair.getKey()).xmlNode("true")); +// } +// } +// } +// // StringBuilder develops the core pom commands. +// StringBuilder sb = new StringBuilder(); +// mavenOptions.forEach(sb::append); +// Path pomPath = testPath.resolve(keyOption.name).resolve("pom.xml"); +// File pomFile = pomPath.toFile(); +// pomFile.getParentFile().mkdirs(); +// try (FileWriter writer = new FileWriter(pomFile)) { +// writer.append(format(POM_FMT, keyOption.name, sb)); +// writer.flush(); +// } +// try { +// final RatCheckMojo mojo = new SimpleMojoTestcase(){}.getMojo(pomFile); +// Assertions.assertNotNull(mojo); +// return mojo; +// } catch (IOException e) { +// throw e; +// } catch (Exception e) { +// throw new IOException(format("Unable to generate mojo for %s (%s)", keyOption.name, keyOption), e); +// } +// } +// +// @Override +// protected final ReportConfiguration generateConfig(List<Pair<Option, String[]>> args) throws IOException { +// try { +// this.mojo = generateMojo(args); +// AbstractConfigurationOptionsProvider.setup(this.mojo.getProject().getBasedir()); +// return mojo.getConfiguration(); +// } catch (MojoExecutionException e) { +// throw new IOException(e.getMessage(), e); +// } +// } +// +// @Override +// protected void helpTest() { +// fail("Should not call help"); +// } +// } +// +// public abstract static class SimpleMojoTestcase extends BetterAbstractMojoTestCase { +// public RatCheckMojo getMojo(File pomFile) throws Exception { +// setUp(); +// ProjectBuildingRequest buildingRequest = newMavenSession().getProjectBuildingRequest(); +// ProjectBuilder projectBuilder = lookup(ProjectBuilder.class); +// MavenProject project = projectBuilder.build(pomFile, buildingRequest).getProject(); +// try { +// return (RatCheckMojo) lookupConfiguredMojo(project, "check"); +// } catch (ComponentConfigurationException e) { +// for (Method m : RatCheckMojo.class.getMethods()) { +// System.out.println( m ); +// } +// throw e; +// } +// } +// } +//} diff --git a/apache-rat-plugin-parent/impl/src/test/java/org/apache/rat/mp/RatCheckMojoTest.java b/apache-rat-plugin-parent/impl/src/test/java/org/apache/rat/mp/RatCheckMojoTest.java deleted file mode 100644 index 7c8dfd9a..00000000 --- a/apache-rat-plugin-parent/impl/src/test/java/org/apache/rat/mp/RatCheckMojoTest.java +++ /dev/null @@ -1,484 +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.mp; - -import static java.lang.String.format; -import static java.nio.charset.StandardCharsets.UTF_8; -import static org.apache.rat.mp.RatTestHelpers.ensureRatReportIsCorrect; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Fail.fail; - -import java.io.File; - -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import javax.xml.xpath.XPath; -import javax.xml.xpath.XPathFactory; -import org.apache.commons.io.FileUtils; -import org.apache.rat.ReportConfiguration; -import org.apache.rat.ReportConfigurationTest; -import org.apache.rat.ReporterTestUtils; -import org.apache.rat.api.Document; -import org.apache.rat.commandline.Arg; -import org.apache.rat.license.ILicenseFamily; -import org.apache.rat.license.LicenseSetFactory; -import org.apache.rat.license.LicenseSetFactory.LicenseFilter; -import org.apache.rat.maven.AbstractRatMojo; -import org.apache.rat.maven.RatCheckException; -import org.apache.rat.maven.RatCheckMojo; -import org.apache.rat.maven.RatReportMojo; -import org.apache.rat.report.claim.ClaimStatistic; -import org.apache.rat.test.AbstractConfigurationOptionsProvider; -import org.apache.rat.test.utils.Resources; -import org.apache.rat.testhelpers.TextUtils; -import org.apache.rat.testhelpers.XmlUtils; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.condition.EnabledOnOs; -import org.junit.jupiter.api.condition.OS; -import org.junit.jupiter.api.io.TempDir; -import org.w3c.dom.NamedNodeMap; -import org.w3c.dom.NodeList; - -/** - * Test case for the {@link RatCheckMojo} and {@link RatReportMojo}. - */ -public class RatCheckMojoTest { - - @TempDir - static Path tempDir; - - private final static XPath xPath = XPathFactory.newInstance().newXPath(); - - @AfterAll - static void preserveData() { - AbstractConfigurationOptionsProvider.preserveData(tempDir.toFile(), "unit"); - } - - @AfterAll - @EnabledOnOs(OS.WINDOWS) - static void cleanup() { - System.gc(); // hacky workaround for windows bug. - } - - private RatCheckMojo getMojo(File pomFile) throws IOException { - try { - final RatCheckMojo mojo = new OptionMojoTest.SimpleMojoTestcase() { - }.getMojo(pomFile); - Assertions.assertNotNull(mojo); - return mojo; - } catch (IOException e) { - throw e; - } catch (Exception e) { - throw new IOException(format("Unable to generate mojo for %s", pomFile), e); - } - } - - /** - * Creates a new instance of {@link AbstractRatMojo}. - * - * @param testDir The directory, where to look for a pom.xml file. - * copy location. - * @return The configured Mojo. - * @throws Exception An error occurred while creating the Mojo. - */ - private RatCheckMojo newRatMojo(String testDir) throws Exception { - Arg.reset(); - final File sourceDir = Resources.getResourceDirectory(format("unit/%s", testDir)); - final File baseDir = tempDir.resolve(testDir).toFile(); - FileUtils.copyDirectory(sourceDir, baseDir); - final File pomFile = new File(baseDir, "pom.xml"); - RatCheckMojo mojo = getMojo(pomFile); - assertThat(mojo).isNotNull(); - assertThat(mojo.getProject()) - .as("The mojo is missing its MavenProject, which will result in an NPE during RAT runs.") - .isNotNull(); - - File buildDirectory = new File(baseDir, "target"); - assertThat(buildDirectory.mkdirs()).isTrue(); - final File ratTxtFile = new File(buildDirectory, "rat.txt"); - FileUtils.write(ratTxtFile, "", UTF_8); // Ensure the output file exists and is empty (rerunning the test will append) - mojo.setOutputFile(ratTxtFile.getAbsolutePath()); - return mojo; - } - - /** - * Runs a check, which should expose no problems. - * - * @throws Exception The test failed. - */ - @Test - void it1() throws Exception { - final RatCheckMojo mojo = newRatMojo("it1"); - final File ratTxtFile = mojo.getRatTxtFile(); - - ReportConfiguration config = mojo.getConfiguration(); - ReportConfigurationTest.validateDefault(config); - - mojo.execute(); - Map<ClaimStatistic.Counter, String> data = new HashMap<>(); - data.put(ClaimStatistic.Counter.ARCHIVES, "0"); - data.put(ClaimStatistic.Counter.APPROVED, "1"); - data.put(ClaimStatistic.Counter.BINARIES, "0"); - data.put(ClaimStatistic.Counter.DOCUMENT_TYPES, "2"); - data.put(ClaimStatistic.Counter.IGNORED, "2"); - data.put(ClaimStatistic.Counter.LICENSE_CATEGORIES, "1"); - data.put(ClaimStatistic.Counter.LICENSE_NAMES, "1"); - data.put(ClaimStatistic.Counter.NOTICES, "0"); - data.put(ClaimStatistic.Counter.STANDARDS, "1"); - data.put(ClaimStatistic.Counter.UNAPPROVED, "0"); - data.put(ClaimStatistic.Counter.UNKNOWN, "0"); - - org.w3c.dom.Document document = XmlUtils.toDom(Files.newInputStream(ratTxtFile.toPath())); - XPath xPath = XPathFactory.newInstance().newXPath(); - - for (ClaimStatistic.Counter counter : ClaimStatistic.Counter.values()) { - String xpath = String.format("/rat-report/statistics/statistic[@name='%s']", counter.displayName()); - Map<String, String> map = mapOf("approval", "true", "count", data.get(counter), - "description", counter.getDescription()); - XmlUtils.assertAttributes(document, xPath, xpath, map); - } - - XmlUtils.assertAttributes(document, xPath, "/rat-report/resource[@name='/.bzrignore']", - mapOf("mediaType", "application/octet-stream", "type", "IGNORED")); - - XmlUtils.assertAttributes(document, xPath, "/rat-report/resource[@name='/pom.xml']", - mapOf("mediaType", "application/xml", "type", "STANDARD", "encoding", "ISO-8859-1")); - } - - private static Map<String, String> mapOf(String... parts) { - Map<String, String> map = new HashMap<>(); - for (int i = 0; i < parts.length; i += 2) { - map.put(parts[i], parts[i + 1]); - } - return map; - } - - /** - * Runs a check, which should detect a problem. - * - * @throws Exception The test failed. - */ - @Test - void it2() throws Exception { - final RatCheckMojo mojo = newRatMojo("it2"); - final File ratTxtFile = mojo.getRatTxtFile(); - final String[] expected = { - "^Files with unapproved licenses\\s+\\*+\\s+\\Q/src.txt\\E\\s+", - ReporterTestUtils.counterText(ClaimStatistic.Counter.NOTICES, 0, false), - ReporterTestUtils.counterText(ClaimStatistic.Counter.BINARIES, 0, false), - ReporterTestUtils.counterText(ClaimStatistic.Counter.ARCHIVES, 0, false), - ReporterTestUtils.counterText(ClaimStatistic.Counter.STANDARDS, 2, false), - ReporterTestUtils.counterText(ClaimStatistic.Counter.IGNORED, 1, false), - ReporterTestUtils.apacheLicenseVersion2(1), - ReporterTestUtils.unknownLicense(1), - ReporterTestUtils.documentOut(false, Document.Type.STANDARD, "/src.txt") + - ReporterTestUtils.UNKNOWN_LICENSE, - ReporterTestUtils.documentOut(true, Document.Type.STANDARD, "/pom.xml") + - ReporterTestUtils.APACHE_LICENSE - }; - try { - mojo.execute(); - fail("Expected RatCheckException"); - } catch (RatCheckException e) { - final String msg = e.getMessage(); - assertThat(msg.contains(ratTxtFile.getName())).as(() -> format("report filename was not contained in '%s'", msg)) - .isTrue(); - assertThat(msg.toUpperCase()).contains("UNAPPROVED EXCEEDED MINIMUM"); - - ensureRatReportIsCorrect(ratTxtFile, expected, TextUtils.EMPTY); - } - } - - /** - * Tests adding license headers. - */ - @Test - void it3() throws Exception { - final RatCheckMojo mojo = newRatMojo("it3"); - final File ratTxtFile = mojo.getRatTxtFile(); - - ReportConfiguration config = mojo.getConfiguration(); - assertThat(config.isAddingLicenses()).as("should be adding licenses").isTrue(); - mojo.execute(); - org.w3c.dom.Document document = XmlUtils.toDom(Files.newInputStream(ratTxtFile.toPath())); - - XmlUtils.assertAttributes(document, xPath, "/rat-report/resource[@name='/pom.xml']", "type", - "STANDARD"); - XmlUtils.assertAttributes(document, xPath, "/rat-report/resource[@name='/src.apt']", "type", - "STANDARD"); - XmlUtils.assertIsPresent(document, xPath, "/rat-report/resource[@name='/src.apt']/license[@approval='false']"); - - XmlUtils.assertAttributes(document, xPath, "/rat-report/resource[@name='/src.apt']", "type", - "STANDARD"); - - for (Document.Type type : Document.Type.values()) { - if (type == Document.Type.STANDARD) { - XmlUtils.assertAttributes(document, xPath, "/rat-report/statistics/documentType[@name='STANDARD']", "count", - "2"); - } else if (type == Document.Type.IGNORED) { - XmlUtils.assertAttributes(document, xPath, "/rat-report/statistics/documentType[@name='IGNORED']", "count", - "1"); - } else { - XmlUtils.assertIsNotPresent(document, xPath, format("/rat-report/statistics/documentType[@name='%s']", type)); - } - } - } - - /** - * Tests defining licenses in configuration - */ - @Test - void it5() throws Exception { - final RatCheckMojo mojo = newRatMojo("it5"); - final File ratTxtFile = mojo.getRatTxtFile(); - - ReportConfiguration config = mojo.getConfiguration(); - assertThat(config.isAddingLicenses()).as("Should not be adding licenses").isFalse(); - assertThat(config.isAddingLicensesForced()).as("Should not be forcing licenses").isFalse(); - - ReportConfigurationTest.validateDefaultApprovedLicenses(config, 1); - assertThat(config.getLicenseCategories(LicenseFilter.APPROVED)).doesNotContain(ILicenseFamily.makeCategory("YAL")) - .contains(ILicenseFamily.makeCategory("CC")); - ReportConfigurationTest.validateDefaultLicenseFamilies(config, "YAL", "CC"); - assertThat(LicenseSetFactory.familySearch("YAL", config.getLicenseFamilies(LicenseFilter.APPROVED))).isNull(); - assertThat(LicenseSetFactory.familySearch("YAL", config.getLicenseFamilies(LicenseFilter.ALL))).isNotNull(); - assertThat(LicenseSetFactory.familySearch("CC", config.getLicenseFamilies(LicenseFilter.APPROVED))).isNotNull(); - assertThat(LicenseSetFactory.familySearch("CC", config.getLicenseFamilies(LicenseFilter.ALL))).isNotNull(); - - ReportConfigurationTest.validateDefaultLicenses(config, "CC-BY-NC-ND", "YAL"); - assertThat(LicenseSetFactory.search("YAL", "YAL", config.getLicenses(LicenseFilter.ALL))).isPresent(); - - mojo.execute(); - - Map<ClaimStatistic.Counter, String> data = new HashMap<>(); - data.put(ClaimStatistic.Counter.APPROVED, "1"); - data.put(ClaimStatistic.Counter.ARCHIVES, "0"); - data.put(ClaimStatistic.Counter.BINARIES, "0"); - data.put(ClaimStatistic.Counter.DOCUMENT_TYPES, "2"); - data.put(ClaimStatistic.Counter.IGNORED, "3"); - data.put(ClaimStatistic.Counter.LICENSE_CATEGORIES, "1"); - data.put(ClaimStatistic.Counter.LICENSE_NAMES, "1"); - data.put(ClaimStatistic.Counter.NOTICES, "0"); - data.put(ClaimStatistic.Counter.STANDARDS, "1"); - data.put(ClaimStatistic.Counter.UNAPPROVED, "0"); - data.put(ClaimStatistic.Counter.UNKNOWN, "0"); - - org.w3c.dom.Document document = XmlUtils.toDom(Files.newInputStream(ratTxtFile.toPath())); - XPath xPath = XPathFactory.newInstance().newXPath(); - - for (ClaimStatistic.Counter counter : ClaimStatistic.Counter.values()) { - String xpath = String.format("/rat-report/statistics/statistic[@name='%s']", counter.displayName()); - Map<String, String> map = mapOf("approval", - "true", - "count", data.get(counter), - "description", counter.getDescription()); - XmlUtils.assertAttributes(document, xPath, xpath, map); - } - - XmlUtils.assertAttributes(document, xPath, "/rat-report/resource[@name='/.rat']", - "mediaType", "application/octet-stream", "type", "IGNORED", "isDirectory", "true"); - XmlUtils.assertAttributes(document, xPath, "/rat-report/resource[@name='/pom.xml']", - "mediaType", "application/xml", "type", "IGNORED", "isDirectory", "false"); - XmlUtils.assertAttributes(document, xPath, "/rat-report/resource[@name='/src/main/java/nl/basjes/something/Something.java']", - "mediaType", "text/x-java-source", "type", "STANDARD", "encoding", "ISO-8859-1"); - XmlUtils.assertAttributes(document, xPath, "/rat-report/resource[@name='/src/main/java/nl/basjes/something/Something.java']/license", - "approval", "true", "family", ILicenseFamily.makeCategory("CC"), "id", "CC-BY-NC-ND", "name", - "Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International"); - } - - /** - * Runs a check, which should expose no problems. - * - * @throws Exception The test failed. - */ - @Test - void rat343() throws Exception { - final RatCheckMojo mojo = newRatMojo("RAT-343"); - final File ratTxtFile = mojo.getRatTxtFile(); - // POM reports AL, BSD and CC BYas BSD because it contains the BSD and CC BY strings - final String[] expected = { - ReporterTestUtils.documentOut(false, Document.Type.STANDARD, "/pom.xml") + - ReporterTestUtils.APACHE_LICENSE + - ReporterTestUtils.licenseOut("BSD", "BSD") + - ReporterTestUtils.licenseOut("CC BY", "Creative Commons Attribution (Unapproved)"), - ReporterTestUtils.counterText(ClaimStatistic.Counter.NOTICES, 0, false), - ReporterTestUtils.counterText(ClaimStatistic.Counter.BINARIES, 0, false), - ReporterTestUtils.counterText(ClaimStatistic.Counter.ARCHIVES, 0, false), - ReporterTestUtils.counterText(ClaimStatistic.Counter.STANDARDS, 1, false), - ReporterTestUtils.counterText(ClaimStatistic.Counter.IGNORED, 1, false), - ReporterTestUtils.apacheLicenseVersion2(1), - "^BSD: 1 ", - "^Creative Commons Attribution: 1 ", - }; - final String[] notExpected = { - "^Unknown License:" - }; - - ReportConfiguration config = mojo.getConfiguration(); - // validate configuration - assertThat(config.isAddingLicenses()).isFalse(); - assertThat(config.isAddingLicensesForced()).isFalse(); - assertThat(config.getCopyrightMessage()).isNull(); - assertThat(config.getStyleSheet()).withFailMessage("Stylesheet should not be null").isNotNull(); - - ReportConfigurationTest.validateDefaultApprovedLicenses(config, 1); - ReportConfigurationTest.validateDefaultLicenseFamilies(config, "BSD", "CC BY"); - ReportConfigurationTest.validateDefaultLicenses(config, "BSD", "CC BY"); - - mojo.execute(); - ensureRatReportIsCorrect(ratTxtFile, expected, notExpected); - } - - /** - * Tests verifying gitignore parsing - */ - @Test - void rat335() throws Exception { - final RatCheckMojo mojo = newRatMojo("RAT-335"); - final File ratTxtFile = mojo.getRatTxtFile(); - try { - mojo.execute(); - fail("Expected RatCheckException"); - } catch (RatCheckException e) { - final String msg = e.getMessage(); - assertThat(msg).contains(ratTxtFile.getName()); - assertThat(msg).contains("UNAPPROVED exceeded minimum"); - - Map<ClaimStatistic.Counter, String> data = new HashMap<>(); - data.put(ClaimStatistic.Counter.APPROVED, "1"); - data.put(ClaimStatistic.Counter.ARCHIVES, "0"); - data.put(ClaimStatistic.Counter.BINARIES, "0"); - data.put(ClaimStatistic.Counter.DOCUMENT_TYPES, "3"); - data.put(ClaimStatistic.Counter.IGNORED, "6"); - data.put(ClaimStatistic.Counter.LICENSE_CATEGORIES, "2"); - data.put(ClaimStatistic.Counter.LICENSE_NAMES, "2"); - data.put(ClaimStatistic.Counter.NOTICES, "1"); - data.put(ClaimStatistic.Counter.STANDARDS, "5"); - data.put(ClaimStatistic.Counter.UNAPPROVED, "4"); - data.put(ClaimStatistic.Counter.UNKNOWN, "4"); - - org.w3c.dom.Document document = XmlUtils.toDom(Files.newInputStream(ratTxtFile.toPath())); - - for (ClaimStatistic.Counter counter : ClaimStatistic.Counter.values()) { - String xpath = String.format("/rat-report/statistics/statistic[@name='%s']", counter.displayName()); - Map<String, String> map = mapOf("approval", - counter == ClaimStatistic.Counter.UNAPPROVED ? "false" : "true", - "count", data.get(counter), - "description", counter.getDescription()); - XmlUtils.assertAttributes(document, xPath, xpath, map); - } - - // license categories - XmlUtils.assertAttributes(document, xPath, "/rat-report/statistics/licenseCategory[@name='?????']", - mapOf("count", "4")); - - XmlUtils.assertAttributes(document, xPath, "/rat-report/statistics/licenseCategory[@name='AL ']", - mapOf("count", "1")); - - // license names - XmlUtils.assertAttributes(document, xPath, "/rat-report/statistics/licenseName[@name='Apache License 2.0']", - mapOf("count", "1")); - - XmlUtils.assertAttributes(document, xPath, "/rat-report/statistics/licenseName[@name='Unknown license']", - mapOf("count", "4")); - - // Document types - XmlUtils.assertAttributes(document, xPath, "/rat-report/statistics/documentType[@name='IGNORED']", - mapOf("count", "6")); - - XmlUtils.assertAttributes(document, xPath, "/rat-report/statistics/documentType[@name='NOTICE']", - mapOf("count", "1")); - - XmlUtils.assertAttributes(document, xPath, "/rat-report/statistics/documentType[@name='STANDARD']", - mapOf("count", "5")); - - List<String> ignoredFiles = new ArrayList<>(Arrays.asList( - "/dir1/dir1.txt", - "/dir1/.gitignore", - "/dir2/dir2.md", - "/dir3/dir3.log", - "/.gitignore", - "/root.md")); - - NodeList nodeList = XmlUtils.getNodeList(document, xPath, "/rat-report/resource[@type='IGNORED']"); - for (int i = 0; i < nodeList.getLength(); i++) { - NamedNodeMap attr = nodeList.item(i).getAttributes(); - String s = attr.getNamedItem("name").getNodeValue(); - assertThat(ignoredFiles).contains(s); - ignoredFiles.remove(s); - } - assertThat(ignoredFiles).isEmpty(); - } - } - - /** - * Tests verifying gitignore parsing under a special edge case condition - * The problem occurs when '/foo.md' is to be ignored and a file with that name exists - * in a directory which is the project base directory twice concatenated. - * So for this test we must create such a file which is specific for the current - * working directory. - */ - @Test - void rat362() throws Exception { - final RatCheckMojo mojo = newRatMojo("RAT-362"); - final File ratTxtFile = mojo.getRatTxtFile(); - try { - mojo.execute(); - fail("Expected RatCheckException"); - } catch (RatCheckException e) { - final String msg = e.getMessage(); - assertThat(msg).contains(ratTxtFile.getName()); - assertThat(msg).contains("UNAPPROVED exceeded minimum"); - - org.w3c.dom.Document document = XmlUtils.toDom(Files.newInputStream(ratTxtFile.toPath())); - // Document types - XmlUtils.assertAttributes(document, xPath, "/rat-report/statistics/documentType[@name='IGNORED']", - "count", "3"); - - XmlUtils.assertAttributes(document, xPath, "/rat-report/resource[@name='/bar.md']", - "type", "STANDARD"); - XmlUtils.assertAttributes(document, xPath, "/rat-report/resource[@name='/foo.md']", - "type", "IGNORED"); - } - } - - /** - * Tests implicit excludes apply to submodules too - */ - @Test - void rat107() throws Exception { - final RatCheckMojo mojo = newRatMojo("RAT-107"); - final File ratTxtFile = mojo.getRatTxtFile(); - final String[] expected = {}; - final String[] notExpected = {}; - //setVariableValueToObject(mojo, "excludeSubProjects", Boolean.FALSE); - mojo.setInputExcludeParsedScm("MAVEN"); - mojo.setInputExcludeParsedScm("idea"); - mojo.setInputExcludeParsedScm("eclipse"); - mojo.execute(); - - ensureRatReportIsCorrect(ratTxtFile, expected, notExpected); - } -} diff --git a/apache-rat-plugin-parent/impl/src/test/java/org/apache/rat/mp/RatTestHelpers.java b/apache-rat-plugin-parent/impl/src/test/java/org/apache/rat/mp/RatTestHelpers.java index cc8ba9d3..5d847ce1 100644 --- a/apache-rat-plugin-parent/impl/src/test/java/org/apache/rat/mp/RatTestHelpers.java +++ b/apache-rat-plugin-parent/impl/src/test/java/org/apache/rat/mp/RatTestHelpers.java @@ -1,209 +1,209 @@ -package org.apache.rat.mp; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.FileReader; -import java.io.IOException; -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Proxy; -import java.nio.file.Files; -import java.util.List; - -import org.apache.commons.io.FileUtils; - -/* - * 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. - */ - -import org.apache.commons.io.IOUtils; -import org.apache.maven.artifact.factory.ArtifactFactory; -import org.apache.maven.artifact.factory.DefaultArtifactFactory; -import org.apache.maven.artifact.repository.ArtifactRepository; -import org.apache.maven.artifact.repository.ArtifactRepositoryPolicy; -import org.apache.maven.artifact.repository.MavenArtifactRepository; -import org.apache.maven.artifact.repository.layout.ArtifactRepositoryLayout; -import org.apache.maven.doxia.siterenderer.Renderer; -import org.apache.maven.settings.Settings; -import org.apache.maven.settings.io.xpp3.SettingsXpp3Reader; -import org.apache.rat.testhelpers.TextUtils; -import org.codehaus.plexus.PlexusContainer; -import org.codehaus.plexus.util.DirectoryScanner; - -import com.google.common.base.Charsets; - -/** - * Test helpers used when verifying mojo interaction in RAT integration tests. - */ -public final class RatTestHelpers { - - /** - * @param pDir Removes the given directory recursively. - * @throws IOException in case of errors. - */ - public static void remove(File pDir) throws IOException { - if (pDir.isFile()) { - if (!pDir.delete()) { - throw new IOException("Unable to delete file: " + pDir); - } - } else if (pDir.isDirectory()) { - FileUtils.deleteDirectory(pDir); - } else if (pDir.exists()) { - throw new IOException("Unable to delete unknown object " + pDir); - } - } - - /** - * Copies the given files recursively in order to get all integration test files - * into a target directory. - * - * @param pSource source files. - * @param pTarget target directory - * @throws IOException in case of errors. - */ - public static void copy(File pSource, File pTarget) throws IOException { - if (pSource.isDirectory()) { - if (!pTarget.isDirectory() && !pTarget.mkdirs()) { - throw new IOException("Unable to create directory: " + pTarget); - } - final DirectoryScanner scanner = new DirectoryScanner(); - scanner.setBasedir(pSource); - scanner.addDefaultExcludes(); - scanner.setIncludes(new String[] { "*" }); - scanner.scan(); - final String[] dirs = scanner.getIncludedDirectories(); - - for (final String dir : dirs) { - if (!"".equals(dir)) { - copy(new File(pSource, dir), new File(pTarget, dir)); - } - } - final String[] files = scanner.getIncludedFiles(); - for (String file : files) { - copy(new File(pSource, file), new File(pTarget, file)); - } - } else if (pSource.isFile()) { - try (final FileInputStream fis = new FileInputStream(pSource); - final FileOutputStream fos = new FileOutputStream(pTarget)) { - final byte[] buffer = new byte[8192]; - for (;;) { - int res = fis.read(buffer); - if (res == -1) { - break; - } - if (res > 0) { - fos.write(buffer, 0, res); - } - } - } - } else { - throw new IOException("Unable to copy unknown object " + pSource); - } - } - - /** - * Creates a new instance of {@link Renderer}. - * - * @param container current plexus container. - * @return A configured instance of a Default renderer. - * @throws Exception Creating the object failed. - */ - public static Renderer newSiteRenderer(PlexusContainer container) throws Exception { - // Replaced deprecated ROLE-based lookup with type+hint lookup. - return container.lookup(Renderer.class, "default"); - } - - /** - * Creates a new instance of {@link ArtifactFactory}. - * - * @return A configured instance of {@link DefaultArtifactFactory}. - */ - public static ArtifactFactory newArtifactFactory() { - final InvocationHandler handler = (pProxy, pMethod, pArgs) -> { - System.out.println("Invoking method " + pMethod); - throw new IllegalStateException("Not implemented"); - }; - return (ArtifactFactory) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), - new Class[] { ArtifactFactory.class }, handler); - } - - /** - * Creates an instance of {@link ArtifactRepository}. - * - * @param container current plexus container. - * @return A configured instance of {@link MavenArtifactRepository}. - * @throws Exception Creating the object failed. - */ - public static ArtifactRepository newArtifactRepository(PlexusContainer container) throws Exception { - File m2Dir = new File(System.getProperty("user.home"), ".m2"); - File settingsFile = new File(m2Dir, "settings.xml"); - String localRepo = null; - if (settingsFile.exists()) { - Settings settings = new SettingsXpp3Reader().read(new FileReader(settingsFile)); - localRepo = settings.getLocalRepository(); - } - if (localRepo == null) { - localRepo = System.getProperty("user.home") + "/.m2/repository"; - } - ArtifactRepositoryLayout repositoryLayout = (ArtifactRepositoryLayout) container - .lookup(ArtifactRepositoryLayout.ROLE, "default"); - return new MavenArtifactRepository("local", "file://" + localRepo, repositoryLayout, - new ArtifactRepositoryPolicy(), new ArtifactRepositoryPolicy()); - } - - public static File makeSourceDirectory(String mvnBaseDir, File pFile, String pDir, boolean pCreateCopy) - throws IOException { - if (!pCreateCopy) { - return pFile; - } - - final File targetDir = new File(new File(new File(mvnBaseDir), "target/it-source"), pDir); - remove(targetDir); - copy(pFile, targetDir); - return targetDir; - } - - public static File getSourceDirectory(String mvnBaseDir, String pDir, boolean pCreateCopy, final File baseDir) - throws IOException { - return makeSourceDirectory(mvnBaseDir, new File(new File(baseDir, "src/test/resources/unit"), pDir), pDir, - pCreateCopy); - } - - /** - * Reads the created report file and verifies, whether the detected numbers are - * matching. - * - * @param pRatTxtFile The file to read. - * @param in An array of regex expressions that must be in the file. - * @param notIn An array of regex expressions that must NOT be in the file. - * @throws IOException An error occurred while reading the file or the file does - * not exist at all. - * @throws IllegalArgumentException In case of mismatches in file numbers passed - * in as parameter. - */ - public static void ensureRatReportIsCorrect(File pRatTxtFile, String[] in, String[] notIn) throws IOException { - List<String> lines = IOUtils.readLines(Files.newInputStream(pRatTxtFile.toPath()), Charsets.UTF_8); - String document = String.join("\n", lines); - for (String pattern : in) { - TextUtils.assertPatternInTarget(pattern, document); - } - - for (String pattern : notIn) { - TextUtils.assertPatternNotInTarget(pattern, document); - } - } - -} \ No newline at end of file +//package org.apache.rat.mp; +// +//import java.io.File; +//import java.io.FileInputStream; +//import java.io.FileOutputStream; +//import java.io.FileReader; +//import java.io.IOException; +//import java.lang.reflect.InvocationHandler; +//import java.lang.reflect.Proxy; +//import java.nio.file.Files; +//import java.util.List; +// +//import org.apache.commons.io.FileUtils; +// +///* +// * 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. +// */ +// +//import org.apache.commons.io.IOUtils; +//import org.apache.maven.artifact.factory.ArtifactFactory; +//import org.apache.maven.artifact.factory.DefaultArtifactFactory; +//import org.apache.maven.artifact.repository.ArtifactRepository; +//import org.apache.maven.artifact.repository.ArtifactRepositoryPolicy; +//import org.apache.maven.artifact.repository.MavenArtifactRepository; +//import org.apache.maven.artifact.repository.layout.ArtifactRepositoryLayout; +//import org.apache.maven.doxia.siterenderer.Renderer; +//import org.apache.maven.settings.Settings; +//import org.apache.maven.settings.io.xpp3.SettingsXpp3Reader; +//import org.apache.rat.testhelpers.TextUtils; +//import org.codehaus.plexus.PlexusContainer; +//import org.codehaus.plexus.util.DirectoryScanner; +// +//import com.google.common.base.Charsets; +// +///** +// * Test helpers used when verifying mojo interaction in RAT integration tests. +// */ +//public final class RatTestHelpers { +// +// /** +// * @param pDir Removes the given directory recursively. +// * @throws IOException in case of errors. +// */ +// public static void remove(File pDir) throws IOException { +// if (pDir.isFile()) { +// if (!pDir.delete()) { +// throw new IOException("Unable to delete file: " + pDir); +// } +// } else if (pDir.isDirectory()) { +// FileUtils.deleteDirectory(pDir); +// } else if (pDir.exists()) { +// throw new IOException("Unable to delete unknown object " + pDir); +// } +// } +// +// /** +// * Copies the given files recursively in order to get all integration test files +// * into a target directory. +// * +// * @param pSource source files. +// * @param pTarget target directory +// * @throws IOException in case of errors. +// */ +// public static void copy(File pSource, File pTarget) throws IOException { +// if (pSource.isDirectory()) { +// if (!pTarget.isDirectory() && !pTarget.mkdirs()) { +// throw new IOException("Unable to create directory: " + pTarget); +// } +// final DirectoryScanner scanner = new DirectoryScanner(); +// scanner.setBasedir(pSource); +// scanner.addDefaultExcludes(); +// scanner.setIncludes(new String[] { "*" }); +// scanner.scan(); +// final String[] dirs = scanner.getIncludedDirectories(); +// +// for (final String dir : dirs) { +// if (!"".equals(dir)) { +// copy(new File(pSource, dir), new File(pTarget, dir)); +// } +// } +// final String[] files = scanner.getIncludedFiles(); +// for (String file : files) { +// copy(new File(pSource, file), new File(pTarget, file)); +// } +// } else if (pSource.isFile()) { +// try (final FileInputStream fis = new FileInputStream(pSource); +// final FileOutputStream fos = new FileOutputStream(pTarget)) { +// final byte[] buffer = new byte[8192]; +// for (;;) { +// int res = fis.read(buffer); +// if (res == -1) { +// break; +// } +// if (res > 0) { +// fos.write(buffer, 0, res); +// } +// } +// } +// } else { +// throw new IOException("Unable to copy unknown object " + pSource); +// } +// } +// +// /** +// * Creates a new instance of {@link Renderer}. +// * +// * @param container current plexus container. +// * @return A configured instance of a Default renderer. +// * @throws Exception Creating the object failed. +// */ +// public static Renderer newSiteRenderer(PlexusContainer container) throws Exception { +// // Replaced deprecated ROLE-based lookup with type+hint lookup. +// return container.lookup(Renderer.class, "default"); +// } +// +// /** +// * Creates a new instance of {@link ArtifactFactory}. +// * +// * @return A configured instance of {@link DefaultArtifactFactory}. +// */ +// public static ArtifactFactory newArtifactFactory() { +// final InvocationHandler handler = (pProxy, pMethod, pArgs) -> { +// System.out.println("Invoking method " + pMethod); +// throw new IllegalStateException("Not implemented"); +// }; +// return (ArtifactFactory) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), +// new Class[] { ArtifactFactory.class }, handler); +// } +// +// /** +// * Creates an instance of {@link ArtifactRepository}. +// * +// * @param container current plexus container. +// * @return A configured instance of {@link MavenArtifactRepository}. +// * @throws Exception Creating the object failed. +// */ +// public static ArtifactRepository newArtifactRepository(PlexusContainer container) throws Exception { +// File m2Dir = new File(System.getProperty("user.home"), ".m2"); +// File settingsFile = new File(m2Dir, "settings.xml"); +// String localRepo = null; +// if (settingsFile.exists()) { +// Settings settings = new SettingsXpp3Reader().read(new FileReader(settingsFile)); +// localRepo = settings.getLocalRepository(); +// } +// if (localRepo == null) { +// localRepo = System.getProperty("user.home") + "/.m2/repository"; +// } +// ArtifactRepositoryLayout repositoryLayout = (ArtifactRepositoryLayout) container +// .lookup(ArtifactRepositoryLayout.ROLE, "default"); +// return new MavenArtifactRepository("local", "file://" + localRepo, repositoryLayout, +// new ArtifactRepositoryPolicy(), new ArtifactRepositoryPolicy()); +// } +// +// public static File makeSourceDirectory(String mvnBaseDir, File pFile, String pDir, boolean pCreateCopy) +// throws IOException { +// if (!pCreateCopy) { +// return pFile; +// } +// +// final File targetDir = new File(new File(new File(mvnBaseDir), "target/it-source"), pDir); +// remove(targetDir); +// copy(pFile, targetDir); +// return targetDir; +// } +// +// public static File getSourceDirectory(String mvnBaseDir, String pDir, boolean pCreateCopy, final File baseDir) +// throws IOException { +// return makeSourceDirectory(mvnBaseDir, new File(new File(baseDir, "src/test/resources/unit"), pDir), pDir, +// pCreateCopy); +// } +// +// /** +// * Reads the created report file and verifies, whether the detected numbers are +// * matching. +// * +// * @param pRatTxtFile The file to read. +// * @param in An array of regex expressions that must be in the file. +// * @param notIn An array of regex expressions that must NOT be in the file. +// * @throws IOException An error occurred while reading the file or the file does +// * not exist at all. +// * @throws IllegalArgumentException In case of mismatches in file numbers passed +// * in as parameter. +// */ +// public static void ensureRatReportIsCorrect(File pRatTxtFile, String[] in, String[] notIn) throws IOException { +// List<String> lines = IOUtils.readLines(Files.newInputStream(pRatTxtFile.toPath()), Charsets.UTF_8); +// String document = String.join("\n", lines); +// for (String pattern : in) { +// TextUtils.assertPatternInTarget(pattern, document); +// } +// +// for (String pattern : notIn) { +// TextUtils.assertPatternNotInTarget(pattern, document); +// } +// } +// +//} diff --git a/apache-rat-plugin-parent/tools/src/main/java/org/apache/rat/maven/CodeGenerator.java b/apache-rat-plugin-parent/tools/src/main/java/org/apache/rat/maven/CodeGenerator.java index 008145cf..ba6a818e 100644 --- a/apache-rat-plugin-parent/tools/src/main/java/org/apache/rat/maven/CodeGenerator.java +++ b/apache-rat-plugin-parent/tools/src/main/java/org/apache/rat/maven/CodeGenerator.java @@ -180,12 +180,12 @@ public final class CodeGenerator { /** * Gets parameter annotation for the method in {@code AbstractMaven.java}. * @param mavenOption the maven option generating the method. - * @param methodName the method name. + * @param propertyName the name of the "rat.X" property for command line override. * @return the method name description for the method in {@code AbstractMaven.java}. */ - private String createParameterAnnotation(final MavenOption mavenOption, final String methodName) { + private String createParameterAnnotation(final MavenOption mavenOption, final String propertyName) { StringBuilder sb = new StringBuilder("@Parameter"); - String property = mavenOption.hasArgs() ? null : format("property = \"rat.%s\"", methodName); + String property = mavenOption.hasArgs() ? null : format("property = \"rat.%s\"", propertyName); String defaultValue = mavenOption.isDeprecated() ? null : mavenOption.getDefaultValue(); if (property != null || defaultValue != null) { sb.append("("); @@ -214,7 +214,7 @@ public final class CodeGenerator { context.put("argDesc", createArgDesc(mavenOption, desc)); String functionName = createMethodName(mavenOption); context.put("fname", functionName); - context.put("parameterAnnotation", createParameterAnnotation(mavenOption, functionName)); + context.put("parameterAnnotation", createParameterAnnotation(mavenOption, mavenOption.getName())); context.put("args", (mavenOption.hasArg() ? "String" : "boolean") + (mavenOption.hasArgs() ? "[]" : "")); methodTemplate.merge(context, methodWriter); diff --git a/apache-rat-plugin-parent/tools/src/main/java/org/apache/rat/maven/TestGenerator.java b/apache-rat-plugin-parent/tools/src/main/java/org/apache/rat/maven/TestGenerator.java index 92387149..56a6cb78 100644 --- a/apache-rat-plugin-parent/tools/src/main/java/org/apache/rat/maven/TestGenerator.java +++ b/apache-rat-plugin-parent/tools/src/main/java/org/apache/rat/maven/TestGenerator.java @@ -25,6 +25,7 @@ import java.io.StringWriter; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; +import java.util.Locale; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.DefaultParser; @@ -33,6 +34,7 @@ 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.commons.text.WordUtils; import org.apache.rat.DeprecationReporter; import org.apache.rat.VersionInfo; import org.apache.rat.testhelpers.FileUtils; @@ -53,20 +55,22 @@ public final class TestGenerator { /** The package name as a cased string */ private final CasedString packageName; /** The resource directory where the test resources will be written */ - private final String resourceDirectory; + private final Path resourceDirectory; /** The directory where the test classes will be written*/ - private final String testDirectory; + private final Path testDirectory; /** The template for the pom.xml files */ private final Template pomTemplate; /** The template for the test class file */ private final Template javaTemplate; /** The template for the methods within the test class */ private final Template methodTemplate; + /** The template for the test maven stubs */ + private final Template stubTemplate; private TestGenerator(final String packageName, final String resourceDirectory, final String testDirectory) { this.packageName = new CasedString(CasedString.StringCase.DOT, packageName); - this.resourceDirectory = resourceDirectory; - this.testDirectory = testDirectory; + this.resourceDirectory = Paths.get(resourceDirectory); + this.testDirectory = Paths.get(testDirectory).resolve(this.packageName.toCase(CasedString.StringCase.SLASH)); VelocityEngine velocityEngine = new VelocityEngine(); velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath"); @@ -76,11 +80,14 @@ public final class TestGenerator { // retrieve the templates CasedString casedTemplateName = new CasedString(CasedString.StringCase.DOT, TestGenerator.class.getName()); String[] nameParts = Arrays.copyOf(casedTemplateName.getSegments(), casedTemplateName.getSegments().length); - pomTemplate = velocityEngine.getTemplate(casedTemplateName.toCase(CasedString.StringCase.SLASH) + ".vm"); + nameParts[nameParts.length - 1] = "TestPom.vm"; + pomTemplate = velocityEngine.getTemplate(CasedString.StringCase.SLASH.assemble(nameParts)); nameParts[nameParts.length - 1] = "TestJava.vm"; javaTemplate = velocityEngine.getTemplate(CasedString.StringCase.SLASH.assemble(nameParts)); nameParts[nameParts.length - 1] = "TestMethod.vm"; methodTemplate = velocityEngine.getTemplate(CasedString.StringCase.SLASH.assemble(nameParts)); + nameParts[nameParts.length - 1] = "TestStub.vm"; + stubTemplate = velocityEngine.getTemplate(CasedString.StringCase.SLASH.assemble(nameParts)); } /** @@ -88,7 +95,9 @@ public final class TestGenerator { * @return the resource path. */ private Path resourcePath() { - return Paths.get(resourceDirectory).resolve(packageName.toCase(CasedString.StringCase.SLASH)); + return resourceDirectory + .resolve(packageName.toCase(CasedString.StringCase.SLASH)) + .resolve("stubs"); } /** @@ -144,7 +153,7 @@ public final class TestGenerator { context.put("rat_version", versionInfo.getSpecVersion()); context.put("plugin_version", versionInfo.getVersion()); context.put("tests", writeTestPoms(context)); - writeTestFile(context); + writeTestFiles(context); } /** @@ -152,9 +161,8 @@ public final class TestGenerator { * @param context * @throws IOException */ - private void writeTestFile(final VelocityContext context) throws IOException { - File javaFile = Paths.get(testDirectory).resolve(packageName.toCase(CasedString.StringCase.SLASH)) - .resolve("MavenTest.java").toFile(); + private void writeTestFiles(final VelocityContext context) throws IOException { + File javaFile = testDirectory.resolve("MavenTest.java").toFile(); FileUtils.mkDir(javaFile.getParentFile()); try (FileWriter fileWriter = new FileWriter(javaFile)) { javaTemplate.merge(context, fileWriter); @@ -173,15 +181,23 @@ public final class TestGenerator { StringWriter funcCode = new StringWriter(); for (final TestData testData : new ReportTestDataProvider().getOptionTests(MavenOption.UNSUPPORTED_SET)) { - context.put("pomFile", testData.getTestName() + "/pom.xml"); + context.put("option", testData.getOption()); + // relative directory to test resources. + Path testDir = Paths.get("src/test/resources").resolve(packageName.toCase(CasedString.StringCase.SLASH)) + .resolve("stubs").resolve(testData.getTestName()); + context.put("testdir", testDir); + context.put("basedir", Paths.get("target/test-classes") + .resolve(packageName.toCase(CasedString.StringCase.SLASH)) + .resolve("stubs").resolve(testData.getTestName())); + // absolute path to the test resources. Path testPath = resourcePath().resolve(testData.getTestName()); context.put("baseDir", testPath.toFile().getAbsolutePath()); FileUtils.mkDir(testPath.toFile()); - CasedString testName = new CasedString(CasedString.StringCase.SLASH, testData.getTestName()); - - context.put("artifactId", testName.toCase(CasedString.StringCase.KEBAB)); + CasedString casedTestName = new CasedString(CasedString.StringCase.CAMEL, testData.getClassName()); + context.put("artifactId", casedTestName.toCase(CasedString.StringCase.KEBAB).toLowerCase(Locale.ROOT)); context.put("testName", testData.getTestName()); - context.put("funcName", String.join("", testName.getSegments())); + context.put("stubName", testData.getClassName()); + context.put("funcName", WordUtils.uncapitalize(testData.getClassName())); StringBuilder configuration = new StringBuilder(); for (Pair<Option, String[]> pair : testData.getArgs()) { @@ -198,6 +214,12 @@ public final class TestGenerator { } methodTemplate.merge(context, funcCode); + File stubFile = testDirectory.resolve("stubs") + .resolve(testData.getClassName() + ".java").toFile(); + FileUtils.mkDir(stubFile.getParentFile()); + try (FileWriter fileWriter = new FileWriter(stubFile)) { + stubTemplate.merge(context, fileWriter); + } } return funcCode.toString(); diff --git a/apache-rat-plugin-parent/tools/src/main/resources/org/apache/rat/maven/TestJava.vm b/apache-rat-plugin-parent/tools/src/main/resources/org/apache/rat/maven/TestJava.vm index 10a64614..7cf5e5d8 100644 --- a/apache-rat-plugin-parent/tools/src/main/resources/org/apache/rat/maven/TestJava.vm +++ b/apache-rat-plugin-parent/tools/src/main/resources/org/apache/rat/maven/TestJava.vm @@ -16,15 +16,12 @@ */ package ${packageName}; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Fail.fail; - -import java.nio.file.Path; +import java.nio.file.Paths; import java.util.Map; -import javax.xml.xpath.XPath; -import javax.xml.xpath.XPathFactory; +import org.apache.maven.api.plugin.testing.Basedir; import org.apache.maven.api.plugin.testing.InjectMojo; import org.apache.maven.api.plugin.testing.MojoTest; +import org.apache.maven.plugin.MojoExecutionException; import org.apache.rat.testhelpers.data.ReportTestDataProvider; import org.apache.rat.testhelpers.data.TestData; import org.apache.rat.testhelpers.data.ValidatorData; @@ -32,7 +29,8 @@ import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.EnabledOnOs; import org.junit.jupiter.api.condition.OS; -import org.junit.jupiter.api.io.TempDir; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; /** * Tests extracted from {@link ReportTestDataProvider}. @@ -41,15 +39,9 @@ import org.junit.jupiter.api.io.TempDir; @MojoTest public class MavenTest { - @TempDir - static Path tempDir; - static ReportTestDataProvider reportTestDataProvider = new ReportTestDataProvider(); - - final Map<String, TestData> testDataMap = reportTestDataProvider.getOptionTestMap(MavenOption.UNSUPPORTED_LIST); - - private final static XPath xPath = XPathFactory.newInstance().newXPath(); + final Map<String, TestData> testDataMap = reportTestDataProvider.getOptionTestMap(MavenOption.UNSUPPORTED_SET); @AfterAll @EnabledOnOs(OS.WINDOWS) diff --git a/apache-rat-plugin-parent/tools/src/main/resources/org/apache/rat/maven/TestMethod.vm b/apache-rat-plugin-parent/tools/src/main/resources/org/apache/rat/maven/TestMethod.vm index 304e5318..f0bcd491 100644 --- a/apache-rat-plugin-parent/tools/src/main/resources/org/apache/rat/maven/TestMethod.vm +++ b/apache-rat-plugin-parent/tools/src/main/resources/org/apache/rat/maven/TestMethod.vm @@ -20,9 +20,16 @@ * Generated test for ${testName} */ @Test -@InjectMojo(goal = "validate", pom = "${pomFile}") -public void ${funcName}Test(RatCheckMojo mojo) { +@InjectMojo(goal = "check") +@Basedir("${basedir}") +public void ${funcName}Test(RatCheckMojo mojo) throws MojoExecutionException { TestData testData = testDataMap.get("${testName}"); - ValidatorData validatorData = new ValidatorData(mojo.getOutput(), mojo.getConfiguration(), "${baseDir}"); - testData.getValidator().accept(validatorData); + testData.setupFiles(Paths.get("impl/${basedir}")); + if (testData.getExpectedException() != null) { + assertThatThrownBy(mojo::execute).hasMessageContaining(testData.getExpectedException().getMessage()); + } else { + mojo.execute(); + ValidatorData validatorData = new ValidatorData(mojo.getOutput(), "src/test/java/../../resources/org/apache/rat/maven/config/noDefaults"); + testData.getValidator().accept(validatorData); + } } diff --git a/apache-rat-plugin-parent/tools/src/main/resources/org/apache/rat/maven/TestGenerator.vm b/apache-rat-plugin-parent/tools/src/main/resources/org/apache/rat/maven/TestPom.vm similarity index 81% rename from apache-rat-plugin-parent/tools/src/main/resources/org/apache/rat/maven/TestGenerator.vm rename to apache-rat-plugin-parent/tools/src/main/resources/org/apache/rat/maven/TestPom.vm index 71cadc20..7fa3acff 100644 --- a/apache-rat-plugin-parent/tools/src/main/resources/org/apache/rat/maven/TestGenerator.vm +++ b/apache-rat-plugin-parent/tools/src/main/resources/org/apache/rat/maven/TestPom.vm @@ -32,6 +32,12 @@ <version>${plugin_version}</version> <configuration> ${rat_configuration} + <!-- Specify where this pom will output files --> +## <outputDirectory>target/test-harness/project-to-test</outputDirectory> + + <!-- The defined stubs --> + <project implementation="${packageName}.stubs.${stubName}"/> + <settings implementation="org.apache.rat.maven.SettingsStub"/> </configuration> </plugin> </plugins> diff --git a/apache-rat-plugin-parent/tools/src/main/resources/org/apache/rat/maven/TestStub.vm b/apache-rat-plugin-parent/tools/src/main/resources/org/apache/rat/maven/TestStub.vm new file mode 100644 index 00000000..39ec0036 --- /dev/null +++ b/apache-rat-plugin-parent/tools/src/main/resources/org/apache/rat/maven/TestStub.vm @@ -0,0 +1,78 @@ +/* + * 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 ${packageName}.stubs; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; +import org.apache.maven.model.Build; +import org.apache.maven.model.Model; +import org.apache.maven.model.io.xpp3.MavenXpp3Reader; +import org.apache.maven.plugin.testing.stubs.MavenProjectStub; +import org.apache.rat.testhelpers.data.ReportTestDataProvider; +import org.codehaus.plexus.util.ReaderFactory; + +/** + * Tests extracted from {@link ReportTestDataProvider}. + * DO NOT EDIT - GENERATED FILE + */ +public class ${stubName} extends MavenProjectStub { + /** + * Default constructor + */ + public ${stubName}() + { + MavenXpp3Reader pomReader = new MavenXpp3Reader(); + Model model; + try { + model = pomReader.read( ReaderFactory.newXmlReader( new File( getBasedir(), "pom.xml" ) ) ); + setModel( model ); + } catch ( Exception e ) { + throw new RuntimeException( e ); + } + + setGroupId( model.getGroupId() ); + setArtifactId( model.getArtifactId() ); + setVersion( model.getVersion() ); + setName( model.getName() ); + setUrl( model.getUrl() ); + setPackaging( model.getPackaging() ); + + Build build = new Build(); + build.setFinalName( model.getArtifactId() ); + build.setDirectory( getBasedir() + "/target" ); + build.setSourceDirectory( getBasedir() + "/src/main/java" ); + build.setOutputDirectory( getBasedir() + "/target/classes" ); + build.setTestSourceDirectory( getBasedir() + "/src/test/java" ); + build.setTestOutputDirectory( getBasedir() + "/target/test-classes" ); + setBuild( build ); + + List<String> compileSourceRoots = new ArrayList<>(); + compileSourceRoots.add( getBasedir() + "/src/main/java" ); + setCompileSourceRoots( compileSourceRoots ); + + List<String> testCompileSourceRoots = new ArrayList<>(); + testCompileSourceRoots.add( getBasedir() + "/src/test/java" ); + setTestCompileSourceRoots( testCompileSourceRoots ); + } + + /** {@inheritDoc} */ + public File getBasedir() + { + return new File( super.getBasedir() + "${testdir}" ); + } +}
